Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_TXMEMPOOL_H7#define BITCOIN_TXMEMPOOL_H9#include <coins.h>10#include <consensus/amount.h>11#include <indirectmap.h>12#include <kernel/cs_main.h>13#include <kernel/mempool_entry.h> // IWYU pragma: export14#include <kernel/mempool_limits.h> // IWYU pragma: export15#include <kernel/mempool_options.h> // IWYU pragma: export16#include <kernel/mempool_removal_reason.h> // IWYU pragma: export17#include <policy/feerate.h>18#include <policy/packages.h>19#include <primitives/transaction.h>20#include <primitives/transaction_identifier.h>21#include <sync.h>22#include <txgraph.h>23#include <util/feefrac.h>24#include <util/hasher.h>25#include <util/result.h>27#include <boost/multi_index/hashed_index.hpp>28#include <boost/multi_index/identity.hpp>29#include <boost/multi_index/indexed_by.hpp>30#include <boost/multi_index/ordered_index.hpp>31#include <boost/multi_index/sequenced_index.hpp>32#include <boost/multi_index/tag.hpp>33#include <boost/multi_index_container.hpp>35#include <atomic>36#include <map>37#include <optional>38#include <set>39#include <string>40#include <string_view>41#include <utility>42#include <vector>44class CChain;45class ValidationSignals;47struct bilingual_str;49/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */50inline constexpr uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;52/** How much linearization cost required for TxGraph clusters to have53* "acceptable" quality, if they cannot be optimally linearized with less cost. */54inline constexpr uint64_t ACCEPTABLE_COST = 75'000;56/** How much work we ask TxGraph to do after a mempool change occurs (either57* due to a changeset being applied, a new block being found, or a reorg). */58inline constexpr uint64_t POST_CHANGE_COST = 5 * ACCEPTABLE_COST;60/**61* Test whether the LockPoints height and time are still valid on the current chain62*/63bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);65// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef66struct mempoolentry_txid67{68typedef Txid result_type;69result_type operator() (const CTxMemPoolEntry &entry) const70{71return entry.GetTx().GetHash();72}74result_type operator() (const CTransactionRef& tx) const75{76return tx->GetHash();77}78};80// extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef81struct mempoolentry_wtxid82{83typedef Wtxid result_type;84result_type operator() (const CTxMemPoolEntry &entry) const85{86return entry.GetTx().GetWitnessHash();87}89result_type operator() (const CTransactionRef& tx) const90{91return tx->GetWitnessHash();92}93};95class CompareTxMemPoolEntryByEntryTime96{97public:98bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const99{100return a.GetTime() < b.GetTime();101}102};104// Multi_index tag names105struct entry_time {};106struct index_by_wtxid {};108/**109* Information about a mempool transaction.110*/111struct TxMempoolInfo112{113/** The transaction itself */114CTransactionRef tx;116/** Time the transaction entered the mempool. */117std::chrono::seconds m_time;119/** Fee of the transaction. */120CAmount fee;122/** Virtual size of the transaction. */123int32_t vsize;125/** The fee delta. */126int64_t nFeeDelta;127};129/**130* CTxMemPool stores valid-according-to-the-current-best-chain transactions131* that may be included in the next block.132*133* Transactions are added when they are seen on the network (or created by the134* local node), but not all transactions seen are added to the pool. For135* example, the following new transactions will not be added to the mempool:136* - a transaction which doesn't meet the minimum fee requirements.137* - a new transaction that double-spends an input of a transaction already in138* the pool where the new transaction does not meet the Replace-By-Fee139* requirements as defined in doc/policy/mempool-replacements.md.140* - a non-standard transaction.141*142* TxGraph (CTxMemPool::m_txgraph) provides an abstraction layer for separating143* the transaction graph parts of the mempool from the rest of the144* Bitcoin-specific logic. Specifically, TxGraph handles (for each transaction)145* managing the in-mempool parents and children, and has knowledge of the fee146* and size of every transaction. It uses this to partition the mempool into147* connected clusters, and it implements (among other things):148* - limits on the size of a cluster (in both number of transactions149* and total weight)150* - sorting the mempool optimally for block inclusion, taking into account151* dependencies152* - selecting transactions for removal due to cluster size limit violations153* after a reorg.154* See txgraph.h and txgraph.cpp for more details.155*156* CTxMemPool itself handles the Bitcoin-specific parts of mempool157* transactions; it stores the full transaction inside CTxMemPoolEntry, along158* with other consensus-specific fields (such as whether a transaction spends a159* coinbase, or the LockPoints for transaction finality). And it provides160* interfaces to the rest of the codebase, such as:161* - to validation for replace-by-fee calculations and cluster size limits162* when evaluating unconfirmed transactions163* - to validation for evicting transactions due to expiry or the mempool size164* limit being hit165* - to validation for updating the mempool to be consistent with the best166* chain after a new block is connected or after a reorg.167* - to net_processing for ordering transactions that are to-be-announced to168* other peers169* - to RPC code for inspecting the mempool170*171* (Many of these interfaces are just wrappers around corresponding TxGraph172* functions.)173*174* Within CTxMemPool, the mempool entries are stored in a boost::multi_index175* mapTx, which sorts the mempool on 3 criteria:176* - transaction hash (txid)177* - witness-transaction hash (wtxid)178* - time in mempool179*180* We also maintain a map from COutPoint to the (in-mempool) transaction that181* spends it (mapNextTx). This allows us to recover from a reorg and find182* transactions in the mempool that conflict with transactions that are183* confirmed in a block.184*185*/186class CTxMemPool187{188protected:189std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation191uint64_t totalTxSize GUARDED_BY(cs){0}; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.192CAmount m_total_fee GUARDED_BY(cs){0}; //!< sum of all mempool tx's fees (NOT modified fee)193uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)195mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};196mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};197mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially199// In-memory counter for external mempool tracking purposes.200// This number is incremented once every time a transaction201// is added or removed from the mempool for any reason.202mutable uint64_t m_sequence_number GUARDED_BY(cs){1};204void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);206bool m_load_tried GUARDED_BY(cs){false};208CFeeRate GetMinFee(size_t sizelimit) const;210public:212static constexpr int ROLLING_FEE_HALFLIFE{60 * 60 * 12}; // public only for testing214using indexed_transaction_set = boost::multi_index_container<215CTxMemPoolEntry,216boost::multi_index::indexed_by<217// sorted by txid218boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,219// sorted by wtxid220boost::multi_index::hashed_unique<221boost::multi_index::tag<index_by_wtxid>,222mempoolentry_wtxid,223SaltedWtxidHasher224>,225// sorted by entry time226boost::multi_index::ordered_non_unique<227boost::multi_index::tag<entry_time>,228boost::multi_index::identity<CTxMemPoolEntry>,229CompareTxMemPoolEntryByEntryTime230>231>232>;234/**235* This mutex needs to be locked when accessing `mapTx` or other members236* that are guarded by it.237*238* @par Consistency guarantees239* By design, it is guaranteed that:240* 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool241* that is consistent with current chain tip (`ActiveChain()` and242* `CoinsTip()`) and is fully populated. Fully populated means that if the243* current active chain is missing transactions that were present in a244* previously active chain, all the missing transactions will have been245* re-added to the mempool and should be present if they meet size and246* consistency constraints.247* 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool248* consistent with some chain that was active since `cs_main` was last249* locked, and that is fully populated as described above. It is ok for250* code that only needs to query or remove transactions from the mempool
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.