天天看點

比特币源代碼--14--資料結構-交易池基本概念 代碼分析CTxMemPool

基本概念

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

引用《精通比特币》:

比特币網絡中幾乎每個節點都會維護一份未确認交易的臨時清單,被稱為記憶體池或交易池。節點們利用這個池來追蹤記錄那些被網絡所知曉、但還未被區塊鍊所包含的交易。例如,儲存使用者錢包的節點會利用這個交易池來記錄那些網絡已經接收但還未被确認的、屬于該使用者錢包的預支付資訊。随着交易被接收和驗證,它們被添加到交易池并通知到相鄰節點處,進而傳播到網絡中。

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

礦工選哪個交易、不選哪個交易主要看什麼?很顯然,看哪個交易給的手續費更高。

但不是所有交易都會被加入交易池,例如:

  • 不符合最低收費标準的交易
  • “雙花”交易
  • 非标準交易

 代碼分析

代碼路徑: bitcoin/src/txmempool.h

交易池主要介紹兩個類CTxMemPoolEntry和CTxMemPool,都位于txmempool.h中。第一個是交易池中每一個元素的基本結構,第二個是整個交易池包含的所有資訊。

CTxMemPoolEntry

交易池中基本單元

class CTxMemPoolEntry
{
private:
    CTransactionRef tx;		   // 交易引用
    CAmount nFee;              // 交易費用
    size_t nTxWeight;          //!< ... and avoid recomputing tx weight (also used for GetTxSize())
    size_t nUsageSize;         // 大小
    int64_t nTime;             // 時間戳
    unsigned int entryHeight;  // 區塊高度
    bool spendsCoinbase;       // 前一個交易是否是coinbase[創币交易]
    int64_t sigOpCost;         //!< Total sigop cost
    int64_t feeDelta;          // 交易優先級的一個标量
    LockPoints lockPoints;     // 交易最後的所在區塊高度和打包的時間

    // 交易池中關于該交易的子孫交易;如果移除交易,我們必須同時移除它所有的子孫交易
    uint64_t nCountWithDescendants;  // 子孫交易數量
    uint64_t nSizeWithDescendants;   // 大小
    CAmount nModFeesWithDescendants; // 總費用,包括目前交易

    // 祖先交易資訊
    uint64_t nCountWithAncestors;
    uint64_t nSizeWithAncestors;
    CAmount nModFeesWithAncestors;
    int64_t nSigOpCostWithAncestors;
    ...
}
           

CTxMemPool

記憶體交易池

  •  交易記憶體池,儲存所有在目前主鍊上有效的交易。
  •  當交易在網絡上廣播之後,就會被加進交易池。
  •  但并不是所有的交易都會被加入,
  •  例如交易費太小的,或者“雙花”的交易或者非标準交易。
  •  記憶體池中通過一個boost::multi_index類型的變量mapTx來排序所有交易,
 按照下面四個标準:
  1.  * -交易hash
  2.  * -交易費(包括所有子孫交易)
  3.  * -在mempool中的時間
  4.  * -挖礦分數
  •  為了保證交易費的正确性,當新交易被加進mempool時,我們必須更新
  •  該交易的所有祖先交易資訊,而這個操作可能會導緻處理速度變慢,
  •  是以必須對更需祖先的數量進行限制。
class CTxMemPool
{
private:
    uint32_t nCheckFrequency; //表示在2^32時間内檢查的次數
    unsigned int nTransactionsUpdated; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
    CBlockPolicyEstimator* minerPolicyEstimator;
 
    uint64_t totalTxSize;      //所有mempool中交易的虛拟大小,不包括見證資料
    uint64_t cachedInnerUsage; //map中元素使用的動态記憶體大小之和
 
    mutable int64_t lastRollingFeeUpdate;
    mutable bool blockSinceLastRollingFeeBump;
    mutable double rollingMinimumFeeRate; //進入pool需要的最小費用
 
    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, 首先根據交易hash排
            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 score (for mining prioritization), 分數
            boost::multi_index::ordered_unique<
                boost::multi_index::tag<mining_score>,
                boost::multi_index::identity<CTxMemPoolEntry>,
                CompareTxMemPoolEntryByScore
            >,
            // 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; //所有交易見證資料的哈希
 
    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;
 
    /** 建立新的mempool
     */
    explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
 
    /**
     * 如果開啟了sanity-check,那麼check函數将會保證pool的一緻性,
     * 即不包含雙花交易,所有的輸入都在mapNextTx數組中。
     * 如果關閉了sanity-check,那麼check函數什麼都不做
     */
    void check(const CCoinsViewCache *pcoins) const;
    void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; }
 
     /**
     * 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);
    /**
     * 檢查交易的輸入是否在目前的mempool中
     */
    bool HasNoInputsOf(const CTransaction& tx) const;
 
    /** 調整 CreateNewBlock 時交易的優先級 */
    void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
    void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
    void ClearPrioritisation(const uint256 hash);
 
public:
    /** 
     *  從mempool中移除一個交易集合,
     *  如果一個交易在這個集合中,那麼它的所有子孫交易都必須在集合中,
     *  除非該交易已經被打包到區塊中。
     *  如果要移除一個已經被打包到區塊中的交易,
     *  那麼要把updateDescendants設為true,
     *  進而更新mempool中所有子孫節點的祖先資訊
     */
    void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
 
    /** 
     *  從競争失敗的Block中更新交易資訊到mempool
     */
    void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);
 
    /** 計算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);
 
    /** 
      *  傳回進入mempool需要的最小交易費,
      *  incrementalRelayFee變量用來限制feerate降到0所需的時間。
      */
    CFeeRate GetMinFee(size_t sizelimit) const;
 
    /** 
      *  移除所有動态大小超過sizelimit的交易,
      *  如果傳入了pvNoSpendsRemaining,那麼将傳回不在mempool中并且也沒有
      *  任何輸出在mempool的交易清單
      */
    void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=nullptr);
 
    /**
    * 移除所有在time之前的交易和它的子孫交易,
    * 傳回移除的數量
    */
    int Expire(int64_t time);
 
    /** 如果交易不滿足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 是被 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);
 
    /** 設定一個entry的祖先 */
    void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors);
 
    /** 對于每一個要移除的交易,更新它的祖先和直接的兒子。
      * 如果updateDescendants 設為 true, 那麼還同時更新mempool中子孫的祖先狀态
    */
    void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants);
 
    /** Sever link between specified transaction and direct children. */
    void UpdateChildrenForRemoval(txiter entry);
 
    /** 對于一個特定的交易,調用 removeUnchecked 之前,
     * 必須為同時為要移除的交易集合調用UpdateForRemoveFromMempool。
     *  我們使用每個CTxMemPoolEntry中的setMemPoolParents來周遊
     *  要移除交易的祖先,這樣能保證我們更新的正确性。
     */
    void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
};