比特幣原始碼研讀(4)資料結構-交易池TransactionPool

chaors發表於2018-04-25

上一篇:資料結構-交易Transaction

瞭解了區塊和交易的資料結構,接下來就是介於這兩者之間的一個重要的資料結構:交易池。

當比特幣網路把某個時刻產生的交易廣播到網路時,礦工接收到交易後並不是立即打包到備選區塊。而是將接收到的交易放到類似緩衝區的一個交易池裡,然後會根據一定的優先順序來選擇交易打包,以此來保障自己能獲得儘可能多的交易費。

所以瞭解交易池的資料結構,對理解礦工打包交易會有很大的裨益。

找啊找啊找交易池

首先我猜測有關交易池的類可能叫transactionPool,於是我試著全域性搜這個詞:

悲劇了,寶寶沒找到啊

於是,我擴大搜尋範圍,搜尋pool。搜到的結果很多,我大概地往下翻,試圖尋找是交易池的那個。找到很多處mempool,於是我點進去試著搜尋mempool,找到了txmempool.h這個標頭檔案,交易記憶體池,應該就是這個了。

image.png

原始碼初窺

  • 程式碼路徑: bitcoin/src/txmempool.h

LockPoints

/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
//一個"假"的高度值,用來標識它們只存在於交易池中
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;

//交易鎖定點,交易最後的區塊高度和打包時間
struct LockPoints
{
    // Will be set to the blockchain height and median time past
    // values that would be necessary to satisfy all relative locktime
    // constraints (BIP68) of this tx given our view of block chain history
    /**
    *   將設定為區塊鏈高度和中值時間過去值,
    *   這些值對於滿足tx相對時間鎖是至關重要的(BIP68)
    *   
    */
    int height;
    int64_t time;
    // As long as the current chain descends from the highest height block
    // containing one of the inputs used in the calculation, then the cached
    // values are still valid even after a reorg.
    /**
    *   只要當前鏈包含計算中使用的某個輸入的最高快高度,
    *   則即使在鏈重新構建後快取的值依然有效
    */
    CBlockIndex* maxInputBlock;

    LockPoints() : height(0), time(0), maxInputBlock(nullptr) { }
};
複製程式碼

CTxMemPoolEntry

class CTxMemPool;

/** \class CTxMemPoolEntry
 *
 * CTxMemPoolEntry stores data about the corresponding transaction, as well
 * as data about all in-mempool transactions that depend on the transaction
 * ("descendant" transactions).
 *
 * When a new entry is added to the mempool, we update the descendant state
 * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
 * all ancestors of the newly added transaction.
 *
 **CTxMemPoolEntry 儲存相應的交易
 * 以及該交易對應的所有子孫交易
 *
 * 當一個新的CTxMemPoolEntry被新增到交易池,我們會更新新新增交易的所有子孫交易的狀態
 * (包括子孫交易數量,大小,和交易費用)和祖父交易狀態
 */

//交易池基本構成元素
class CTxMemPoolEntry
{
private:
    CTransactionRef tx;         //交易引用
    CAmount nFee;               //交易費用      //!< Cached to avoid expensive parent-transaction lookups
    size_t nTxWeight;           //            //!< ... and avoid recomputing tx weight (also used for GetTxSize())
    size_t nUsageSize;          //大小        //!< ... and total memory usage
    int64_t nTime;              //交易時間戳   //!< Local time when entering the mempool
    unsigned int entryHeight;   //區塊高度  //!< Chain height when entering the mempool
    bool spendsCoinbase;        //上個交易是否是創幣交易   //!< keep track of transactions that spend a coinbase
    int64_t sigOpCost;          //???  !< Total sigop cost
    int64_t feeDelta;           //交易優先順序的一個標量    //!< Used for determining the priority of the transaction for mining in a block
    LockPoints lockPoints;      //鎖定點,交易最後的區塊高度和打包時間 //!< Track the height and time at which tx was final

    // Information about descendants of this transaction that are in the
    // mempool; if we remove this transaction we must remove all of these
    // descendants as well.
    /* 
    **  子孫交易資訊
    *   如果我們移除一個交易,我們也必須同時移除它所有的子孫交易
    */
    uint64_t nCountWithDescendants;     //子孫交易數量 //!< number of descendant transactions
    uint64_t nSizeWithDescendants;      //大小        //!< ... and size
    CAmount nModFeesWithDescendants;    //費用總和,包括當前交易   //!< ... and total fees (all including us)

    // Analogous statistics for ancestor transactions
    //祖先交易資訊
    uint64_t nCountWithAncestors;       //祖先交易數量
    uint64_t nSizeWithAncestors;        //大小
    CAmount nModFeesWithAncestors;      //費用總和
    int64_t nSigOpCostWithAncestors;    //??? 

public:
    CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
                    int64_t _nTime, unsigned int _entryHeight,
                    bool spendsCoinbase,
                    int64_t nSigOpsCost, LockPoints lp);

    const CTransaction& GetTx() const { return *this->tx; }
    CTransactionRef GetSharedTx() const { return this->tx; }
    const CAmount& GetFee() const { return nFee; }
    size_t GetTxSize() const;
    size_t GetTxWeight() const { return nTxWeight; }
    int64_t GetTime() const { return nTime; }
    unsigned int GetHeight() const { return entryHeight; }
    int64_t GetSigOpCost() const { return sigOpCost; }
    int64_t GetModifiedFee() const { return nFee + feeDelta; }
    size_t DynamicMemoryUsage() const { return nUsageSize; }
    const LockPoints& GetLockPoints() const { return lockPoints; }

    // Adjusts the descendant state.
    // 更新子孫交易狀態
    void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
    // Adjusts the ancestor state
    // 更新祖先交易狀態
    void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps);
    // Updates the fee delta used for mining priority score, and the
    // modified fees with descendants.
    // 更新交易優先順序
    void UpdateFeeDelta(int64_t feeDelta);
    // Update the LockPoints after a reorg
    // 更新鎖定點
    void UpdateLockPoints(const LockPoints& lp);

    //獲取子孫交易資訊
    uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
    uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
    CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }

    bool GetSpendsCoinbase() const { return spendsCoinbase; }

    //獲取祖先交易資訊
    uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
    uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
    CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
    int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }

    mutable size_t vTxHashesIdx;    //交易池雜湊的下標  //!< Index in mempool's vTxHashes
};
複製程式碼

CTxMemPoolEntry幾種排序方法


/** \class CompareTxMemPoolEntryByDescendantScore
 *
 *  Sort an entry by max(score/size of entry's tx, score/size with all descendants).
 *
 ** 按score/size原則對CTxMemPoolEntry排序
 */
class CompareTxMemPoolEntryByDescendantScore
{
public:
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
    {
        double a_mod_fee, a_size, b_mod_fee, b_size;

        GetModFeeAndSize(a, a_mod_fee, a_size);
        GetModFeeAndSize(b, b_mod_fee, b_size);

        // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
        double f1 = a_mod_fee * b_size;
        double f2 = a_size * b_mod_fee;

        if (f1 == f2) {
            return a.GetTime() >= b.GetTime();
        }
        return f1 < f2;
    }

    // Return the fee/size we're using for sorting this entry.
    void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
    {
        // Compare feerate with descendants to feerate of the transaction, and
        // return the fee/size for the max.
        double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
        double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();

        if (f2 > f1) {
            mod_fee = a.GetModFeesWithDescendants();
            size = a.GetSizeWithDescendants();
        } else {
            mod_fee = a.GetModifiedFee();
            size = a.GetTxSize();
        }
    }
};

/** \class CompareTxMemPoolEntryByScore
 *
 *  Sort by score of entry ((fee+delta)/size) in descending order
 **
 *  按(fee+delta)/size原則對CTxMemPoolEntry排序
 */
class CompareTxMemPoolEntryByScore
{
public:
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
    {
        double f1 = (double)a.GetModifiedFee() * b.GetTxSize();
        double f2 = (double)b.GetModifiedFee() * a.GetTxSize();
        if (f1 == f2) {
            return b.GetTx().GetHash() < a.GetTx().GetHash();
        }
        return f1 > f2;
    }
};

//按時間CTxMemPoolEntry對排序
class CompareTxMemPoolEntryByEntryTime
{
public:
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
    {
        return a.GetTime() < b.GetTime();
    }
};

/** \class CompareTxMemPoolEntryByAncestorScore
 *
 *  Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
 */
class CompareTxMemPoolEntryByAncestorFee
{
public:
    template<typename T>
    bool operator()(const T& a, const T& b) const
    {
        double a_mod_fee, a_size, b_mod_fee, b_size;

        GetModFeeAndSize(a, a_mod_fee, a_size);
        GetModFeeAndSize(b, b_mod_fee, b_size);

        // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
        double f1 = a_mod_fee * b_size;
        double f2 = a_size * b_mod_fee;

        if (f1 == f2) {
            return a.GetTx().GetHash() < b.GetTx().GetHash();
        }
        return f1 > f2;
    }

    // Return the fee/size we're using for sorting this entry.
    template <typename T>
    void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
    {
        // Compare feerate with ancestors to feerate of the transaction, and
        // return the fee/size for the min.
        double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
        double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();

        if (f1 > f2) {
            mod_fee = a.GetModFeesWithAncestors();
            size = a.GetSizeWithAncestors();
        } else {
            mod_fee = a.GetModifiedFee();
            size = a.GetTxSize();
        }
    }
};
複製程式碼

TxMempoolInfo

/**
 * Information about a mempool transaction.
 * 交易進入記憶體池的資訊
 */
struct TxMempoolInfo
{
    /** The transaction itself */
    CTransactionRef tx;     //交易引用

    /** Time the transaction entered the mempool. */
    int64_t nTime;          //交易進入記憶體池時間

    /** Feerate of the transaction. */
    CFeeRate feeRate;       //交易費率

    /** The fee delta. */   
    int64_t nFeeDelta;      //交易優先順序
};
複製程式碼

###MemPoolRemovalReason

/** Reason why a transaction was removed from the mempool,
 * this is passed to the notification signal.
 *
 * 交易被移出記憶體池的原因
 */
enum class MemPoolRemovalReason {
    UNKNOWN = 0,        //未知原因     //! Manually removed or unknown reason
    EXPIRY,             //過期        //! Expired from mempool
    SIZELIMIT,          //大小限制     //! Removed in size limiting
    REORG,              //被重組      //! Removed for reorganization
    BLOCK,              //因為區塊    //! Removed for block
    CONFLICT,           //區塊內交易衝突//! Removed for conflict with in-block transaction
    REPLACED            //被替代       //! Removed for replacement
};
複製程式碼

CTxMemPool

/**
 * CTxMemPool stores valid-according-to-the-current-best-chain transactions
 * that may be included in the next block.
 *
 * CTxMemPool 儲存當前主鏈所有的交易。這些交易有可能被加入到下一個有效區塊中
 *
 * Transactions are added when they are seen on the network (or created by the
 * local node), but not all transactions seen are added to the pool. For
 * example, the following new transactions will not be added to the mempool:
 * - a transaction which doesn't meet the minimum fee requirements.
 * - a new transaction that double-spends an input of a transaction already in
 * the pool where the new transaction does not meet the Replace-By-Fee
 * requirements as defined in BIP 125.
 * - a non-standard transaction.
 *
 **當交易在比特幣網路上廣播時會被加入到交易池。
 * 比如以下新的交易將不會被加入到交易池中:
 *  - 1.沒有滿足最低交易費的交易
 *  - 2."雙花"交易
 *  - 3.一個非標準交易
 *
 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
 *
 * mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
 * - transaction hash       //交易hash
 * - //交易費率(包括所有子孫交易)
 * - feerate [we use max(feerate of tx, feerate of tx with all descendants)]
 * - time in mempool        //加入交易池的時間
 *
 * Note: the term "descendant" refers to in-mempool transactions that depend on
 * this one, while "ancestor" refers to in-mempool transactions that a given
 * transaction depends on.
 *
 * In order for the feerate sort to remain correct, we must update transactions
 * in the mempool when new descendants arrive.  To facilitate this, we track
 * the set of in-mempool direct parents and direct children in mapLinks.  Within
 * each CTxMemPoolEntry, we track the size and fees of all descendants.
 *
 ** 為了保障交易費的正確性,當新交易被加入到交易池時,我們必須更新該交易的所有祖先交易和子孫交易。
 *  
 * Usually when a new transaction is added to the mempool, it has no in-mempool
 * children (because any such children would be an orphan).  So in
 * addUnchecked(), we:
 * - update a new entry's setMemPoolParents to include all in-mempool parents
 * - update the new entry's direct parents to include the new tx as a child
 * - update all ancestors of the transaction to include the new tx's size/fee
 *
 * When a transaction is removed from the mempool, we must:
 * - update all in-mempool parents to not track the tx in setMemPoolChildren
 * - update all ancestors to not include the tx's size/fees in descendant state
 * - update all in-mempool children to not include it as a parent
 *
 * These happen in UpdateForRemoveFromMempool().  (Note that when removing a
 * transaction along with its descendants, we must calculate that set of
 * transactions to be removed before doing the removal, or else the mempool can
 * be in an inconsistent state where it's impossible to walk the ancestors of
 * a transaction.)
 *
 * In the event of a reorg, the assumption that a newly added tx has no
 * in-mempool children is false.  In particular, the mempool is in an
 * inconsistent state while new transactions are being added, because there may
 * be descendant transactions of a tx coming from a disconnected block that are
 * unreachable from just looking at transactions in the mempool (the linking
 * transactions may also be in the disconnected block, waiting to be added).
 * Because of this, there's not much benefit in trying to search for in-mempool
 * children in addUnchecked().  Instead, in the special case of transactions
 * being added from a disconnected block, we require the caller to clean up the
 * state, to account for in-mempool, out-of-block descendants for all the
 * in-block transactions by calling UpdateTransactionsFromBlock().  Note that
 * until this is called, the mempool state is not consistent, and in particular
 * mapLinks may not be correct (and therefore functions like
 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
 * on them to walk the mempool are not generally safe to use).
 *
 * Computational limits:
 *
 * Updating all in-mempool ancestors of a newly added transaction can be slow,
 * if no bound exists on how many in-mempool ancestors there may be.
 * CalculateMemPoolAncestors() takes configurable limits that are designed to
 * prevent these calculations from being too CPU intensive.
 *
 */
class CTxMemPool
{
private:
    uint32_t nCheckFrequency;           //2^32時間檢查的次數   //!< Value n means that n times in 2^32 we check.
    unsigned int nTransactionsUpdated;  //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
    CBlockPolicyEstimator* minerPolicyEstimator;

    uint64_t totalTxSize;      //交易池虛擬大小,不包括見證資料 //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
    uint64_t cachedInnerUsage; //map使用的動態記憶體大小        //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)

    mutable int64_t lastRollingFeeUpdate;
    mutable bool blockSinceLastRollingFeeBump;
    mutable double rollingMinimumFeeRate;   //進入交易池需要滿足的最小費用    //!< minimum fee to get into the pool, decreases exponentially

    void trackPackageRemoved(const CFeeRate& rate);

public:

    static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing

    typedef boost::multi_index_container<
        CTxMemPoolEntry,
        boost::multi_index::indexed_by<
            // sorted by txid   根據交易雜湊排序
            boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
            // sorted by fee rate   交易費
            boost::multi_index::ordered_non_unique<
                boost::multi_index::tag<descendant_score>,
                boost::multi_index::identity<CTxMemPoolEntry>,
                CompareTxMemPoolEntryByDescendantScore
            >,
            // sorted by entry time 進入交易池的時間
            boost::multi_index::ordered_non_unique<
                boost::multi_index::tag<entry_time>,
                boost::multi_index::identity<CTxMemPoolEntry>,
                CompareTxMemPoolEntryByEntryTime
            >,
            // sorted by fee rate with ancestors    祖父交易交易費
            boost::multi_index::ordered_non_unique<
                boost::multi_index::tag<ancestor_score>,
                boost::multi_index::identity<CTxMemPoolEntry>,
                CompareTxMemPoolEntryByAncestorFee
            >
        >
    > indexed_transaction_set;

    mutable CCriticalSection cs;
    indexed_transaction_set mapTx;

    typedef indexed_transaction_set::nth_index<0>::type::iterator txiter;
    std::vector<std::pair<uint256, txiter> > vTxHashes; //見證資料的雜湊   //!< All tx witness hashes/entries in mapTx, in random order

    struct CompareIteratorByHash {
        bool operator()(const txiter &a, const txiter &b) const {
            return a->GetTx().GetHash() < b->GetTx().GetHash();
        }
    };
    typedef std::set<txiter, CompareIteratorByHash> setEntries;

    const setEntries & GetMemPoolParents(txiter entry) const;
    const setEntries & GetMemPoolChildren(txiter entry) const;
private:
    typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;

    struct TxLinks {
        setEntries parents;
        setEntries children;
    };

    typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
    txlinksMap mapLinks;

    void UpdateParent(txiter entry, txiter parent, bool add);
    void UpdateChild(txiter entry, txiter child, bool add);

    std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const;

public:
    indirectmap<COutPoint, const CTransaction*> mapNextTx;
    std::map<uint256, CAmount> mapDeltas;

    /** Create a new CTxMemPool.
    *   建立一個新的交易池
     */
    explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);

    /**
     * If sanity-checking is turned on, check makes sure the pool is
     * consistent (does not contain two transactions that spend the same inputs,
     * all inputs are in the mapNextTx array). If sanity-checking is turned off,
     * check does nothing.
     *
     **如果開啟了sanity-check,check函式將保證pool的一致性(不包含兩個在同一個輸入中的交易)
     * 所有的輸入都在mapNextTx陣列裡;sanity-check關閉,check函式無效
     *
     */
    void check(const CCoinsViewCache *pcoins) const;
    void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = static_cast<uint32_t>(dFrequency * 4294967295.0); }

    // addUnchecked must updated state for all ancestors of a given transaction,
    // to track size/count of descendant transactions.  First version of
    // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
    // then invoke the second version.
    // Note that addUnchecked is ONLY called from ATMP outside of tests
    // and any other callers may break wallet's in-mempool tracking (due to
    // lack of CValidationInterface::TransactionAddedToMempool callbacks).
    /**
    *  addUnchecked函式必先更新祖先交易的狀態
    *  第一個addUnchecked函式可以用來呼叫CalculateMemPoolAncestors
    *  然後再呼叫第二個addUnchecked
    */
    bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool validFeeEstimate = true);
    bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool validFeeEstimate = true);

    void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
    void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
    void removeConflicts(const CTransaction &tx);
    void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight);

    void clear();
    void _clear(); //lock free
    bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
    void queryHashes(std::vector<uint256>& vtxid);
    bool isSpent(const COutPoint& outpoint);
    unsigned int GetTransactionsUpdated() const;
    void AddTransactionsUpdated(unsigned int n);
    /**
     * Check that none of this transactions inputs are in the mempool, and thus
     * the tx is not dependent on other mempool transactions to be included in a block.
     **
     * 檢查交易的輸入是否在當前交易池中
     */
    bool HasNoInputsOf(const CTransaction& tx) const;

    /** Affect CreateNewBlock prioritisation of transactions */
    //調整CreateNewBlock時的交易優先順序
    void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
    void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
    void ClearPrioritisation(const uint256 hash);

public:
    /** Remove a set of transactions from the mempool.
     *  If a transaction is in this set, then all in-mempool descendants must
     *  also be in the set, unless this transaction is being removed for being
     *  in a block.
     *  Set updateDescendants to true when removing a tx that was in a block, so
     *  that any in-mempool descendants have their ancestor state updated.
     ** 
     *  從mempool中移除一個交易集合,
     *  如果一個交易在這個集合中,那麼它的所有子孫交易都必須在集合中,
     *  除非該交易已經被打包到區塊中。
     *  如果要移除一個已經被打包到區塊中的交易,
     *  那麼要把updateDescendants設為true,
     *  從而更新mempool中所有子孫節點的祖先資訊
     */
    void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);

    /** When adding transactions from a disconnected block back to the mempool,
     *  new mempool entries may have children in the mempool (which is generally
     *  not the case when otherwise adding transactions).
     *  UpdateTransactionsFromBlock() will find child transactions and update the
     *  descendant state for each transaction in vHashesToUpdate (excluding any
     *  child transactions present in vHashesToUpdate, which are already accounted
     *  for).  Note: vHashesToUpdate should be the set of transactions from the
     *  disconnected block that have been accepted back into the mempool.
     **
     *  更新每一個交易的所有子孫交易狀態
     *
     */
    void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);

    /** Try to calculate all in-mempool ancestors of entry.
     *  (these are all calculated including the tx itself)
     *  limitAncestorCount = max number of ancestors
     *  limitAncestorSize = max size of ancestors
     *  limitDescendantCount = max number of descendants any ancestor can have
     *  limitDescendantSize = max size of descendants any ancestor can have
     *  errString = populated with error reason if any limits are hit
     *  fSearchForParents = whether to search a tx's vin for in-mempool parents, or
     *    look up parents from mapLinks. Must be true for entries not in the mempool
     ** 
     *  計算mempool中所有entry的祖先
     *  limitAncestorCount   = 最大祖先數量
     *  limitAncestorSize    = 最大祖先交易大小
     *  limitDescendantCount = 任意祖先的最大子孫數量
     *  limitDescendantSize  = 任意祖先的最大子孫大小
     *  errString            = 超過了任何limit限制的錯誤提示
     *  fSearchForParents    = 是否在mempool中搜尋交易的輸入,
     *  或者從mapLinks中查詢,對於不在mempool中的entry必須設為true
     */
    bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents = true) const;

    /** Populate setDescendants with all in-mempool descendants of hash.
     *  Assumes that setDescendants includes all in-mempool descendants of anything
     *  already in it.  */
    //計算所有子孫交易
    void CalculateDescendants(txiter it, setEntries &setDescendants);

    /** The minimum fee to get into the mempool, which may itself not be enough
      *  for larger-sized transactions.
      *  The incrementalRelayFee policy variable is used to bound the time it
      *  takes the fee rate to go back down all the way to 0. When the feerate
      *  would otherwise be half of this, it is set to 0 instead.
      **
      * 獲取進入交易池需要滿足的最小交易費,本身可能不夠適用於大型交易
      * incrementalRelayFee變數用來限制feerate降到0所需的時間
      * 當交易費是它的一半時,它被設定為0
      */
    CFeeRate GetMinFee(size_t sizelimit) const;

    /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
      *  pvNoSpendsRemaining, if set, will be populated with the list of outpoints
      *  which are not in mempool which no longer have any spends in this mempool.
      ** 
      *  移除所有動態大小超過sizelimit的交易,
      *  如果傳入了pvNoSpendsRemaining,那麼將返回不在mempool中並且也沒有
      *  任何輸出在mempool的交易列表
      */
    void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=nullptr);

    /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
    /*
    ** 移除所有在time之前的交易和它的子孫交易,
    *  並返回被移除交易的數量
    int Expire(int64_t time);

    /** Returns false if the transaction is in the mempool and not within the chain limit specified. */
    //如果交易不滿足chain limit,返回false
    bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const;

    unsigned long size()
    {
        LOCK(cs);
        return mapTx.size();
    }

    uint64_t GetTotalTxSize() const
    {
        LOCK(cs);
        return totalTxSize;
    }

    bool exists(uint256 hash) const
    {
        LOCK(cs);
        return (mapTx.count(hash) != 0);
    }

    CTransactionRef get(const uint256& hash) const;
    TxMempoolInfo info(const uint256& hash) const;
    std::vector<TxMempoolInfo> infoAll() const;

    size_t DynamicMemoryUsage() const;

    boost::signals2::signal<void (CTransactionRef)> NotifyEntryAdded;
    boost::signals2::signal<void (CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved;

private:
    /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
     *  the descendants for a single transaction that has been added to the
     *  mempool but may have child transactions in the mempool, eg during a
     *  chain reorg.  setExclude is the set of descendant transactions in the
     *  mempool that must not be accounted for (because any descendants in
     *  setExclude were added to the mempool after the transaction being
     *  updated and hence their state is already reflected in the parent
     *  state).
     *
     *  cachedDescendants will be updated with the descendants of the transaction
     *  being updated, so that future invocations don't need to walk the
     *  same transaction again, if encountered in another transaction chain.
     **
     *  UpdateForDescendants 是被 UpdateTransactionsFromBlock 呼叫,
     *  用來更新被加入pool中的單個交易的子孫節節點;
     *  setExclude 是記憶體池中不用更新的子孫交易集合 (because any descendants in
     *  setExclude were added to the mempool after the transaction being
     *  updated and hence their state is already reflected in the parent
     *  state).
     *
     *  當子孫交易被更新時,cachedDescendants也同時更新
     */
    void UpdateForDescendants(txiter updateIt,
            cacheMap &cachedDescendants,
            const std::set<uint256> &setExclude);
    /** Update ancestors of hash to add/remove it as a descendant transaction. */
    //更新一個祖先交易去新增或移除 為一個子孫交易
    void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors);
    /** Set ancestor state for an entry */
    //設定一個祖先交易
    void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
    /** For each transaction being removed, update ancestors and any direct children.
      * If updateDescendants is true, then also update in-mempool descendants'
      * ancestor state. */
    /** 對於每一個要移除的交易,更新它的祖先和直接的兒子。
      * 如果updateDescendants 設為 true, 那麼還同時更新mempool中子孫的祖先狀態
    */
    void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
    /** Sever link between specified transaction and direct children. */
    //切斷指定交易與直接子女之間的連結
    void UpdateChildrenForRemoval(txiter entry);

    /** Before calling removeUnchecked for a given transaction,
     *  UpdateForRemoveFromMempool must be called on the entire (dependent) set
     *  of transactions being removed at the same time.  We use each
     *  CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
     *  given transaction that is removed, so we can't remove intermediate
     *  transactions in a chain before we've updated all the state for the
     *  removal.
     ** 
     *  對於一個特定的交易,呼叫 removeUnchecked 之前,
     *  必須為同時為要移除的交易集合呼叫UpdateForRemoveFromMempool。
     *  我們使用每個CTxMemPoolEntry中的setMemPoolParents來遍歷
     *  要移除交易的祖先,這樣能保證我們更新的正確性。
     */
    void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
};
複製程式碼

有關交易池的概念,光標頭檔案就900多行。我們先大概瞭解下一個交易池(TxMemPool)是由若干個CTxMemPoolEntry構成。然後對交易池某些關鍵函式知道其意思,以後具體遇到了再回過頭來檢視。

. . . .

網際網路顛覆世界,區塊鏈顛覆網際網路!

--------------------------------------------------20180423 23:44

相關文章