LCOV - code coverage report
Current view: top level - src - txmempool.h (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 68.0 % 122 83
Test Date: 2025-12-04 04:31:41 Functions: 73.9 % 23 17
Branches: 35.9 % 206 74

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #ifndef BITCOIN_TXMEMPOOL_H
       7                 :             : #define BITCOIN_TXMEMPOOL_H
       8                 :             : 
       9                 :             : #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: export
      14                 :             : #include <kernel/mempool_limits.h>         // IWYU pragma: export
      15                 :             : #include <kernel/mempool_options.h>        // IWYU pragma: export
      16                 :             : #include <kernel/mempool_removal_reason.h> // IWYU pragma: export
      17                 :             : #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/epochguard.h>
      24                 :             : #include <util/feefrac.h>
      25                 :             : #include <util/hasher.h>
      26                 :             : #include <util/result.h>
      27                 :             : 
      28                 :             : #include <boost/multi_index/hashed_index.hpp>
      29                 :             : #include <boost/multi_index/identity.hpp>
      30                 :             : #include <boost/multi_index/indexed_by.hpp>
      31                 :             : #include <boost/multi_index/ordered_index.hpp>
      32                 :             : #include <boost/multi_index/sequenced_index.hpp>
      33                 :             : #include <boost/multi_index/tag.hpp>
      34                 :             : #include <boost/multi_index_container.hpp>
      35                 :             : 
      36                 :             : #include <atomic>
      37                 :             : #include <map>
      38                 :             : #include <optional>
      39                 :             : #include <set>
      40                 :             : #include <string>
      41                 :             : #include <string_view>
      42                 :             : #include <utility>
      43                 :             : #include <vector>
      44                 :             : 
      45                 :             : class CChain;
      46                 :             : class ValidationSignals;
      47                 :             : 
      48                 :             : struct bilingual_str;
      49                 :             : 
      50                 :             : /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
      51                 :             : static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
      52                 :             : 
      53                 :             : /** How many linearization iterations required for TxGraph clusters to have
      54                 :             :  * "acceptable" quality, if they cannot be optimally linearized with fewer
      55                 :             :  * iterations. */
      56                 :             : static constexpr uint64_t ACCEPTABLE_ITERS = 1'700;
      57                 :             : 
      58                 :             : /** How much work we ask TxGraph to do after a mempool change occurs (either
      59                 :             :  * due to a changeset being applied, a new block being found, or a reorg). */
      60                 :             : static constexpr uint64_t POST_CHANGE_WORK = 5 * ACCEPTABLE_ITERS;
      61                 :             : 
      62                 :             : /**
      63                 :             :  * Test whether the LockPoints height and time are still valid on the current chain
      64                 :             :  */
      65                 :             : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
      66                 :             : 
      67                 :             : // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
      68                 :             : struct mempoolentry_txid
      69                 :             : {
      70                 :             :     typedef Txid result_type;
      71                 :      124701 :     result_type operator() (const CTxMemPoolEntry &entry) const
      72                 :             :     {
      73   [ +  -  -  +  :      124701 :         return entry.GetTx().GetHash();
             +  +  -  - ]
           [ +  +  #  #  
             #  #  #  # ]
      74                 :             :     }
      75                 :             : 
      76                 :             :     result_type operator() (const CTransactionRef& tx) const
      77                 :             :     {
      78                 :             :         return tx->GetHash();
      79                 :             :     }
      80                 :             : };
      81                 :             : 
      82                 :             : // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
      83                 :             : struct mempoolentry_wtxid
      84                 :             : {
      85                 :             :     typedef Wtxid result_type;
      86                 :       63666 :     result_type operator() (const CTxMemPoolEntry &entry) const
      87                 :             :     {
      88   [ +  -  -  +  :       63666 :         return entry.GetTx().GetWitnessHash();
           +  + ][ +  +  
             #  #  #  # ]
      89                 :             :     }
      90                 :             : 
      91                 :             :     result_type operator() (const CTransactionRef& tx) const
      92                 :             :     {
      93                 :             :         return tx->GetWitnessHash();
      94                 :             :     }
      95                 :             : };
      96                 :             : 
      97                 :             : class CompareTxMemPoolEntryByEntryTime
      98                 :             : {
      99                 :             : public:
     100                 :      198672 :     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
     101                 :             :     {
     102                 :      198672 :         return a.GetTime() < b.GetTime();
     103                 :             :     }
     104                 :             : };
     105                 :             : 
     106                 :             : // Multi_index tag names
     107                 :             : struct entry_time {};
     108                 :             : struct index_by_wtxid {};
     109                 :             : 
     110                 :             : /**
     111                 :             :  * Information about a mempool transaction.
     112                 :             :  */
     113   [ #  #  #  #  :           0 : struct TxMempoolInfo
          #  #  #  #  #  
                #  #  # ]
         [ #  # ][ #  #  
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     114                 :             : {
     115                 :             :     /** The transaction itself */
     116                 :             :     CTransactionRef tx;
     117                 :             : 
     118                 :             :     /** Time the transaction entered the mempool. */
     119                 :             :     std::chrono::seconds m_time;
     120                 :             : 
     121                 :             :     /** Fee of the transaction. */
     122                 :             :     CAmount fee;
     123                 :             : 
     124                 :             :     /** Virtual size of the transaction. */
     125                 :             :     int32_t vsize;
     126                 :             : 
     127                 :             :     /** The fee delta. */
     128                 :             :     int64_t nFeeDelta;
     129                 :             : };
     130                 :             : 
     131                 :             : /**
     132                 :             :  * CTxMemPool stores valid-according-to-the-current-best-chain transactions
     133                 :             :  * that may be included in the next block.
     134                 :             :  *
     135                 :             :  * Transactions are added when they are seen on the network (or created by the
     136                 :             :  * local node), but not all transactions seen are added to the pool. For
     137                 :             :  * example, the following new transactions will not be added to the mempool:
     138                 :             :  * - a transaction which doesn't meet the minimum fee requirements.
     139                 :             :  * - a new transaction that double-spends an input of a transaction already in
     140                 :             :  * the pool where the new transaction does not meet the Replace-By-Fee
     141                 :             :  * requirements as defined in doc/policy/mempool-replacements.md.
     142                 :             :  * - a non-standard transaction.
     143                 :             :  *
     144                 :             :  * TxGraph (CTxMemPool::m_txgraph) provides an abstraction layer for separating
     145                 :             :  * the transaction graph parts of the mempool from the rest of the
     146                 :             :  * Bitcoin-specific logic. Specifically, TxGraph handles (for each transaction)
     147                 :             :  * managing the in-mempool parents and children, and has knowledge of the fee
     148                 :             :  * and size of every transaction. It uses this to partition the mempool into
     149                 :             :  * connected clusters, and it implements (among other things):
     150                 :             :  *  - limits on the size of a cluster (in both number of transactions
     151                 :             :  *    and total weight)
     152                 :             :  *  - sorting the mempool optimally for block inclusion, taking into account
     153                 :             :  *    dependencies
     154                 :             :  *  - selecting transactions for removal due to cluster size limit violations
     155                 :             :  *    after a reorg.
     156                 :             :  * See txgraph.h and txgraph.cpp for more details.
     157                 :             :  *
     158                 :             :  * CTxMemPool itself handles the Bitcoin-specific parts of mempool
     159                 :             :  * transactions; it stores the full transaction inside CTxMemPoolEntry, along
     160                 :             :  * with other consensus-specific fields (such as whether a transaction spends a
     161                 :             :  * coinbase, or the LockPoints for transaction finality). And it provides
     162                 :             :  * interfaces to the rest of the codebase, such as:
     163                 :             :  *  - to validation for replace-by-fee calculations and cluster size limits
     164                 :             :  *    when evaluating unconfirmed transactions
     165                 :             :  *  - to validation for evicting transactions due to expiry or the mempool size
     166                 :             :  *    limit being hit
     167                 :             :  *  - to validation for updating the mempool to be consistent with the best
     168                 :             :  *    chain after a new block is connected or after a reorg.
     169                 :             :  *  - to net_processing for ordering transactions that are to-be-announced to
     170                 :             :  *    other peers
     171                 :             :  *  - to RPC code for inspecting the mempool
     172                 :             :  *
     173                 :             :  * (Many of these interfaces are just wrappers around corresponding TxGraph
     174                 :             :  * functions.)
     175                 :             :  *
     176                 :             :  * Within CTxMemPool, the mempool entries are stored in a boost::multi_index
     177                 :             :  * mapTx, which sorts the mempool on 3 criteria:
     178                 :             :  * - transaction hash (txid)
     179                 :             :  * - witness-transaction hash (wtxid)
     180                 :             :  * - time in mempool
     181                 :             :  *
     182                 :             :  * We also maintain a map from COutPoint to the (in-mempool) transaction that
     183                 :             :  * spends it (mapNextTx). This allows us to recover from a reorg and find
     184                 :             :  * transactions in the mempool that conflict with transactions that are
     185                 :             :  * confirmed in a block.
     186                 :             :  *
     187                 :             :  */
     188                 :             : class CTxMemPool
     189                 :             : {
     190                 :             : protected:
     191                 :             :     std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
     192                 :             : 
     193                 :             :     uint64_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.
     194                 :             :     CAmount m_total_fee GUARDED_BY(cs){0};       //!< sum of all mempool tx's fees (NOT modified fee)
     195                 :             :     uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
     196                 :             : 
     197                 :             :     mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
     198                 :             :     mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
     199                 :             :     mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially
     200                 :             :     mutable Epoch m_epoch GUARDED_BY(cs){};
     201                 :             : 
     202                 :             :     // In-memory counter for external mempool tracking purposes.
     203                 :             :     // This number is incremented once every time a transaction
     204                 :             :     // is added or removed from the mempool for any reason.
     205                 :             :     mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
     206                 :             : 
     207                 :             :     void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
     208                 :             : 
     209                 :             :     bool m_load_tried GUARDED_BY(cs){false};
     210                 :             : 
     211                 :             :     CFeeRate GetMinFee(size_t sizelimit) const;
     212                 :             : 
     213                 :             : public:
     214                 :             : 
     215                 :             :     static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
     216                 :             : 
     217                 :             :     struct CTxMemPoolEntry_Indices final : boost::multi_index::indexed_by<
     218                 :             :             // sorted by txid
     219                 :             :             boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
     220                 :             :             // sorted by wtxid
     221                 :             :             boost::multi_index::hashed_unique<
     222                 :             :                 boost::multi_index::tag<index_by_wtxid>,
     223                 :             :                 mempoolentry_wtxid,
     224                 :             :                 SaltedWtxidHasher
     225                 :             :             >,
     226                 :             :             // sorted by entry time
     227                 :             :             boost::multi_index::ordered_non_unique<
     228                 :             :                 boost::multi_index::tag<entry_time>,
     229                 :             :                 boost::multi_index::identity<CTxMemPoolEntry>,
     230                 :             :                 CompareTxMemPoolEntryByEntryTime
     231                 :             :             >
     232                 :             :         >
     233                 :             :         {};
     234                 :             :     typedef boost::multi_index_container<
     235                 :             :         CTxMemPoolEntry,
     236                 :             :         CTxMemPoolEntry_Indices
     237                 :             :     > indexed_transaction_set;
     238                 :             : 
     239                 :             :     /**
     240                 :             :      * This mutex needs to be locked when accessing `mapTx` or other members
     241                 :             :      * that are guarded by it.
     242                 :             :      *
     243                 :             :      * @par Consistency guarantees
     244                 :             :      * By design, it is guaranteed that:
     245                 :             :      * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
     246                 :             :      *    that is consistent with current chain tip (`ActiveChain()` and
     247                 :             :      *    `CoinsTip()`) and is fully populated. Fully populated means that if the
     248                 :             :      *    current active chain is missing transactions that were present in a
     249                 :             :      *    previously active chain, all the missing transactions will have been
     250                 :             :      *    re-added to the mempool and should be present if they meet size and
     251                 :             :      *    consistency constraints.
     252                 :             :      * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
     253                 :             :      *    consistent with some chain that was active since `cs_main` was last
     254                 :             :      *    locked, and that is fully populated as described above. It is ok for
     255                 :             :      *    code that only needs to query or remove transactions from the mempool
     256                 :             :      *    to lock just `mempool.cs` without `cs_main`.
     257                 :             :      *
     258                 :             :      * To provide these guarantees, it is necessary to lock both `cs_main` and
     259                 :             :      * `mempool.cs` whenever adding transactions to the mempool and whenever
     260                 :             :      * changing the chain tip. It's necessary to keep both mutexes locked until
     261                 :             :      * the mempool is consistent with the new chain tip and fully populated.
     262                 :             :      */
     263                 :             :     mutable RecursiveMutex cs;
     264                 :             :     std::unique_ptr<TxGraph> m_txgraph GUARDED_BY(cs);
     265                 :             :     mutable std::unique_ptr<TxGraph::BlockBuilder> m_builder GUARDED_BY(cs);
     266                 :             :     indexed_transaction_set mapTx GUARDED_BY(cs);
     267                 :             : 
     268                 :             :     using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
     269                 :             :     std::vector<std::pair<Wtxid, txiter>> txns_randomized GUARDED_BY(cs); //!< All transactions in mapTx with their wtxids, in arbitrary order
     270                 :             : 
     271                 :             :     typedef std::set<txiter, CompareIteratorByHash> setEntries;
     272                 :             : 
     273                 :             :     using Limits = kernel::MemPoolLimits;
     274                 :             : 
     275                 :             :     std::tuple<size_t, size_t, CAmount> CalculateAncestorData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     276                 :             :     std::tuple<size_t, size_t, CAmount> CalculateDescendantData(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     277   [ -  +  +  - ]:           1 :     int64_t GetDescendantCount(txiter it) const { LOCK(cs); return m_txgraph->GetDescendants(*it, TxGraph::Level::MAIN).size(); }
     278   [ -  +  +  - ]:          11 :     int64_t GetDescendantCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetDescendants(e, TxGraph::Level::MAIN).size(); }
     279   [ -  +  +  - ]:          12 :     int64_t GetAncestorCount(const CTxMemPoolEntry &e) const { LOCK(cs); return m_txgraph->GetAncestors(e, TxGraph::Level::MAIN).size(); }
     280                 :             :     std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetChildren(const CTxMemPoolEntry &entry) const;
     281                 :             :     std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> GetParents(const CTxMemPoolEntry &entry) const;
     282                 :             : 
     283                 :             : private:
     284                 :             :     std::vector<indexed_transaction_set::const_iterator> GetSortedScoreWithTopology() const EXCLUSIVE_LOCKS_REQUIRED(cs);
     285                 :             : 
     286                 :             :     /**
     287                 :             :      * Track locally submitted transactions to periodically retry initial broadcast.
     288                 :             :      */
     289                 :             :     std::set<Txid> m_unbroadcast_txids GUARDED_BY(cs);
     290                 :             : 
     291                 :           0 :     static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
     292                 :             :     {
     293   [ #  #  #  #  :           0 :         return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
                   #  # ]
     294                 :             :     }
     295                 :             : 
     296                 :             :     // Helper to remove all transactions that conflict with a given
     297                 :             :     // transaction (used for transactions appearing in a block).
     298                 :             :     void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
     299                 :             : 
     300                 :             : public:
     301                 :             :     indirectmap<COutPoint, txiter> mapNextTx GUARDED_BY(cs);
     302                 :             :     std::map<Txid, CAmount> mapDeltas GUARDED_BY(cs);
     303                 :             : 
     304                 :             :     using Options = kernel::MemPoolOptions;
     305                 :             : 
     306                 :             :     const Options m_opts;
     307                 :             : 
     308                 :             :     /** Create a new CTxMemPool.
     309                 :             :      * Sanity checks will be off by default for performance, because otherwise
     310                 :             :      * accepting transactions becomes O(N^2) where N is the number of transactions
     311                 :             :      * in the pool.
     312                 :             :      */
     313                 :             :     explicit CTxMemPool(Options opts, bilingual_str& error);
     314                 :             : 
     315                 :             :     /**
     316                 :             :      * If sanity-checking is turned on, check makes sure the pool is
     317                 :             :      * consistent (does not contain two transactions that spend the same inputs,
     318                 :             :      * all inputs are in the mapNextTx array). If sanity-checking is turned off,
     319                 :             :      * check does nothing.
     320                 :             :      */
     321                 :             :     void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     322                 :             : 
     323                 :             :     /**
     324                 :             :      * Remove a transaction from the mempool along with any descendants.
     325                 :             :      * If the transaction is not already in the mempool, find any descendants
     326                 :             :      * and remove them.
     327                 :             :      */
     328                 :             :     void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     329                 :             :     /** After reorg, filter the entries that would no longer be valid in the next block, and update
     330                 :             :      * the entries' cached LockPoints if needed.  The mempool does not have any knowledge of
     331                 :             :      * consensus rules. It just applies the callable function and removes the ones for which it
     332                 :             :      * returns true.
     333                 :             :      * @param[in]   filter_final_and_mature   Predicate that checks the relevant validation rules
     334                 :             :      *                                        and updates an entry's LockPoints.
     335                 :             :      * */
     336                 :             :     void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
     337                 :             :     void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
     338                 :             : 
     339                 :             :     bool CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const;
     340                 :             :     bool isSpent(const COutPoint& outpoint) const;
     341                 :             :     unsigned int GetTransactionsUpdated() const;
     342                 :             :     void AddTransactionsUpdated(unsigned int n);
     343                 :             :     /**
     344                 :             :      * Check that none of this transactions inputs are in the mempool, and thus
     345                 :             :      * the tx is not dependent on other mempool transactions to be included in a block.
     346                 :             :      */
     347                 :             :     bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     348                 :             : 
     349                 :             :     /** Affect CreateNewBlock prioritisation of transactions */
     350                 :             :     void PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta);
     351                 :             :     void ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     352                 :             :     void ClearPrioritisation(const Txid& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
     353                 :             : 
     354                 :             :     struct delta_info {
     355                 :             :         /** Whether this transaction is in the mempool. */
     356                 :             :         const bool in_mempool;
     357                 :             :         /** The fee delta added using PrioritiseTransaction(). */
     358                 :             :         const CAmount delta;
     359                 :             :         /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
     360                 :             :         std::optional<CAmount> modified_fee;
     361                 :             :         /** The prioritised transaction's txid. */
     362                 :             :         const Txid txid;
     363                 :             :     };
     364                 :             :     /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
     365                 :             :     std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
     366                 :             : 
     367                 :             :     /** Get the transaction in the pool that spends the same prevout */
     368                 :             :     const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     369                 :             : 
     370                 :             :     /** Returns an iterator to the given hash, if found */
     371                 :             :     std::optional<txiter> GetIter(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     372                 :             :     std::optional<txiter> GetIter(const Wtxid& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     373                 :             : 
     374                 :             :     /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
     375                 :             :      * Does not require that all of the hashes correspond to actual transactions in the mempool,
     376                 :             :      * only returns the ones that exist. */
     377                 :             :     setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     378                 :             : 
     379                 :             :     /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
     380                 :             :      * The nth element in txids becomes the nth element in the returned vector. If any of the txids
     381                 :             :      * don't actually exist in the mempool, returns an empty vector. */
     382                 :             :     std::vector<txiter> GetIterVec(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     383                 :             : 
     384                 :             :     /** UpdateTransactionsFromBlock is called when adding transactions from a
     385                 :             :      * disconnected block back to the mempool, new mempool entries may have
     386                 :             :      * children in the mempool (which is generally not the case when otherwise
     387                 :             :      * adding transactions).
     388                 :             :      *  @post updated descendant state for descendants of each transaction in
     389                 :             :      *        vHashesToUpdate (excluding any child transactions present in
     390                 :             :      *        vHashesToUpdate, which are already accounted for). Updated state
     391                 :             :      *        includes add fee/size information for such descendants to the
     392                 :             :      *        parent and updated ancestor state to include the parent.
     393                 :             :      *
     394                 :             :      * @param[in] vHashesToUpdate          The set of txids from the
     395                 :             :      *     disconnected block that have been accepted back into the mempool.
     396                 :             :      */
     397                 :             :     void UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
     398                 :             : 
     399                 :             :     std::vector<FeePerWeight> GetFeerateDiagram() const EXCLUSIVE_LOCKS_REQUIRED(cs);
     400                 :           0 :     FeePerWeight GetMainChunkFeerate(const CTxMemPoolEntry& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     401                 :           0 :         return m_txgraph->GetMainChunkFeerate(tx);
     402                 :             :     }
     403                 :           0 :     std::vector<const CTxMemPoolEntry*> GetCluster(Txid txid) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     404                 :           0 :         auto tx = GetIter(txid);
     405         [ #  # ]:           0 :         if (!tx) return {};
     406                 :           0 :         auto cluster = m_txgraph->GetCluster(**tx, TxGraph::Level::MAIN);
     407                 :           0 :         std::vector<const CTxMemPoolEntry*> ret;
     408   [ #  #  #  # ]:           0 :         ret.reserve(cluster.size());
     409         [ #  # ]:           0 :         for (const auto& tx : cluster) {
     410         [ #  # ]:           0 :             ret.emplace_back(static_cast<const CTxMemPoolEntry*>(tx));
     411                 :             :         }
     412                 :           0 :         return ret;
     413                 :           0 :     }
     414                 :             : 
     415                 :             : 
     416                 :          13 :     size_t GetUniqueClusterCount(const setEntries& iters_conflicting) const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     417                 :          13 :         std::vector<const TxGraph::Ref *> entries;
     418         [ +  - ]:          13 :         entries.reserve(iters_conflicting.size());
     419         [ +  + ]:         329 :         for (auto it : iters_conflicting) {
     420         [ +  - ]:         316 :             entries.emplace_back(&*it);
     421                 :             :         }
     422         [ -  + ]:          13 :         Assume(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
     423         [ -  + ]:          13 :         return m_txgraph->CountDistinctClusters(entries, TxGraph::Level::MAIN);
     424                 :          13 :     }
     425                 :             : 
     426                 :             :     /**
     427                 :             :      * Calculate all in-mempool ancestors of entry (not including the tx itself)
     428                 :             :      *
     429                 :             :      * @param[in]   entry               CTxMemPoolEntry of which all in-mempool ancestors are calculated
     430                 :             :      *
     431                 :             :      * @return all in-mempool ancestors
     432                 :             :      */
     433                 :             :     setEntries CalculateMemPoolAncestors(const CTxMemPoolEntry& entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     434                 :             : 
     435                 :             :     bool HasDescendants(const Txid& txid) const;
     436                 :             : 
     437                 :             :     /** Collect the entire cluster of connected transactions for each transaction in txids.
     438                 :             :      * All txids must correspond to transaction entries in the mempool, otherwise this returns an
     439                 :             :      * empty vector. This call will also exit early and return an empty vector if it collects 500 or
     440                 :             :      * more transactions as a DoS protection. */
     441                 :             :     std::vector<txiter> GatherClusters(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     442                 :             : 
     443                 :             :     /** Populate setDescendants with all in-mempool descendants of given transaction.
     444                 :             :      *  Assumes that setDescendants includes all in-mempool descendants of anything
     445                 :             :      *  already in it.  */
     446                 :             :     void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     447                 :             :     CTxMemPool::txiter CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     448                 :             : 
     449                 :             :     /** The minimum fee to get into the mempool, which may itself not be enough
     450                 :             :      *  for larger-sized transactions.
     451                 :             :      *  The m_incremental_relay_feerate policy variable is used to bound the time it
     452                 :             :      *  takes the fee rate to go back down all the way to 0. When the feerate
     453                 :             :      *  would otherwise be half of this, it is set to 0 instead.
     454                 :             :      */
     455                 :         134 :     CFeeRate GetMinFee() const {
     456 [ +  - ][ +  -  :         134 :         return GetMinFee(m_opts.max_size_bytes);
          +  -  +  -  +  
                      - ]
     457                 :             :     }
     458                 :             : 
     459                 :             :     /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
     460                 :             :       *  pvNoSpendsRemaining, if set, will be populated with the list of outpoints
     461                 :             :       *  which are not in mempool which no longer have any spends in this mempool.
     462                 :             :       */
     463                 :             :     void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
     464                 :             : 
     465                 :             :     /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
     466                 :             :     int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
     467                 :             : 
     468                 :             :     /**
     469                 :             :      * Calculate the ancestor and cluster count for the given transaction.
     470                 :             :      * The counts include the transaction itself.
     471                 :             :      * When ancestors is non-zero (ie, the transaction itself is in the mempool),
     472                 :             :      * ancestorsize and ancestorfees will also be set to the appropriate values.
     473                 :             :      */
     474                 :             :     void GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
     475                 :             : 
     476                 :             :     /**
     477                 :             :      * @returns true if an initial attempt to load the persisted mempool was made, regardless of
     478                 :             :      *          whether the attempt was successful or not
     479                 :             :      */
     480                 :             :     bool GetLoadTried() const;
     481                 :             : 
     482                 :             :     /**
     483                 :             :      * Set whether or not an initial attempt to load the persisted mempool was made (regardless
     484                 :             :      * of whether the attempt was successful or not)
     485                 :             :      */
     486                 :             :     void SetLoadTried(bool load_tried);
     487                 :             : 
     488                 :     3590968 :     unsigned long size() const
     489                 :             :     {
     490                 :     3590968 :         LOCK(cs);
     491         [ +  - ]:     3590968 :         return mapTx.size();
     492                 :     3590968 :     }
     493                 :             : 
     494                 :           0 :     uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
     495                 :             :     {
     496                 :           0 :         AssertLockHeld(cs);
     497         [ #  # ]:           0 :         return totalTxSize;
     498                 :             :     }
     499                 :             : 
     500                 :           0 :     CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
     501                 :             :     {
     502                 :           0 :         AssertLockHeld(cs);
     503         [ #  # ]:           0 :         return m_total_fee;
     504                 :             :     }
     505                 :             : 
     506                 :         960 :     bool exists(const Txid& txid) const
     507                 :             :     {
     508                 :         960 :         LOCK(cs);
     509   [ +  -  +  - ]:         960 :         return (mapTx.count(txid) != 0);
     510                 :         960 :     }
     511                 :             : 
     512                 :         232 :     bool exists(const Wtxid& wtxid) const
     513                 :             :     {
     514                 :         232 :         LOCK(cs);
     515   [ +  -  +  - ]:         232 :         return (mapTx.get<index_by_wtxid>().count(wtxid) != 0);
     516                 :         232 :     }
     517                 :             : 
     518                 :             :     const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs);
     519                 :             : 
     520                 :             :     CTransactionRef get(const Txid& hash) const;
     521                 :             : 
     522                 :             :     template <TxidOrWtxid T>
     523                 :           0 :     TxMempoolInfo info(const T& id) const
     524                 :             :     {
     525                 :           0 :         LOCK(cs);
     526         [ #  # ]:           0 :         auto i{GetIter(id)};
     527   [ #  #  #  # ]:           0 :         return i.has_value() ? GetInfo(*i) : TxMempoolInfo{};
     528                 :           0 :     }
     529                 :             : 
     530                 :             :     /** Returns info for a transaction if its entry_sequence < last_sequence */
     531                 :             :     template <TxidOrWtxid T>
     532                 :           0 :     TxMempoolInfo info_for_relay(const T& id, uint64_t last_sequence) const
     533                 :             :     {
     534                 :           0 :         LOCK(cs);
     535         [ #  # ]:           0 :         auto i{GetIter(id)};
     536   [ #  #  #  #  :           0 :         return (i.has_value() && i.value()->GetSequence() < last_sequence) ? GetInfo(*i) : TxMempoolInfo{};
                   #  # ]
     537                 :           0 :     }
     538                 :             : 
     539                 :             :     std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
     540                 :             :     std::vector<TxMempoolInfo> infoAll() const;
     541                 :             : 
     542                 :             :     size_t DynamicMemoryUsage() const;
     543                 :             : 
     544                 :             :     /** Adds a transaction to the unbroadcast set */
     545                 :           0 :     void AddUnbroadcastTx(const Txid& txid)
     546                 :             :     {
     547                 :           0 :         LOCK(cs);
     548                 :             :         // Sanity check the transaction is in the mempool & insert into
     549                 :             :         // unbroadcast set.
     550   [ #  #  #  #  :           0 :         if (exists(txid)) m_unbroadcast_txids.insert(txid);
                   #  # ]
     551                 :           0 :     };
     552                 :             : 
     553                 :             :     bool CheckPolicyLimits(const CTransactionRef& tx);
     554                 :             : 
     555                 :             :     /** Removes a transaction from the unbroadcast set */
     556                 :             :     void RemoveUnbroadcastTx(const Txid& txid, const bool unchecked = false);
     557                 :             : 
     558                 :             :     /** Returns transactions in unbroadcast set */
     559                 :           1 :     std::set<Txid> GetUnbroadcastTxs() const
     560                 :             :     {
     561                 :           1 :         LOCK(cs);
     562   [ +  -  +  - ]:           1 :         return m_unbroadcast_txids;
     563                 :           1 :     }
     564                 :             : 
     565                 :             :     /** Returns whether a txid is in the unbroadcast set */
     566                 :           0 :     bool IsUnbroadcastTx(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
     567                 :             :     {
     568                 :           0 :         AssertLockHeld(cs);
     569         [ #  # ]:           0 :         return m_unbroadcast_txids.count(txid) != 0;
     570                 :             :     }
     571                 :             : 
     572                 :             :     /** Guards this internal counter for external reporting */
     573                 :       49418 :     uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     574   [ +  +  #  # ]:       49418 :         return m_sequence_number++;
           [ +  -  +  - ]
           [ +  -  +  -  
                   +  - ]
     575                 :             :     }
     576                 :             : 
     577                 :         136 :     uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     578         [ +  - ]:         136 :         return m_sequence_number;
     579                 :             :     }
     580                 :             : 
     581                 :             : private:
     582                 :             :     /** Remove a set of transactions from the mempool.
     583                 :             :      *  If a transaction is in this set, then all in-mempool descendants must
     584                 :             :      *  also be in the set, unless this transaction is being removed for being
     585                 :             :      *  in a block.
     586                 :             :      */
     587                 :             :     void RemoveStaged(setEntries& stage, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     588                 :             : 
     589                 :             :     /* Helper for the public removeRecursive() */
     590                 :             :     void removeRecursive(txiter to_remove, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     591                 :             : 
     592                 :             :     /** Before calling removeUnchecked for a given transaction,
     593                 :             :      *  UpdateForRemoveFromMempool must be called on the entire (dependent) set
     594                 :             :      *  of transactions being removed at the same time.  We use each
     595                 :             :      *  CTxMemPoolEntry's m_parents in order to walk ancestors of a
     596                 :             :      *  given transaction that is removed, so we can't remove intermediate
     597                 :             :      *  transactions in a chain before we've updated all the state for the
     598                 :             :      *  removal.
     599                 :             :      */
     600                 :             :     void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     601                 :             : public:
     602                 :             :     /** visited marks a CTxMemPoolEntry as having been traversed
     603                 :             :      * during the lifetime of the most recently created Epoch::Guard
     604                 :             :      * and returns false if we are the first visitor, true otherwise.
     605                 :             :      *
     606                 :             :      * An Epoch::Guard must be held when visited is called or an assert will be
     607                 :             :      * triggered.
     608                 :             :      *
     609                 :             :      */
     610                 :           7 :     bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
     611                 :             :     {
     612                 :           7 :         return m_epoch.visited(it->m_epoch_marker);
     613                 :             :     }
     614                 :             : 
     615                 :             :     bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
     616                 :             :     {
     617                 :             :         assert(m_epoch.guarded()); // verify guard even when it==nullopt
     618                 :             :         return !it || visited(*it);
     619                 :             :     }
     620                 :             : 
     621                 :             :     /*
     622                 :             :      * CTxMemPool::ChangeSet:
     623                 :             :      *
     624                 :             :      * This class is used for all mempool additions and associated removals (eg
     625                 :             :      * due to rbf). Removals that don't need to be evaluated for acceptance,
     626                 :             :      * such as removing transactions that appear in a block, or due to reorg,
     627                 :             :      * or removals related to mempool limiting or expiry do not need to use
     628                 :             :      * this.
     629                 :             :      *
     630                 :             :      * Callers can interleave calls to StageAddition()/StageRemoval(), and
     631                 :             :      * removals may be invoked in any order, but additions must be done in a
     632                 :             :      * topological order in the case of transaction packages (ie, parents must
     633                 :             :      * be added before children).
     634                 :             :      *
     635                 :             :      * CalculateChunksForRBF() can be used to calculate the feerate diagram of
     636                 :             :      * the proposed set of new transactions and compare with the existing
     637                 :             :      * mempool.
     638                 :             :      *
     639                 :             :      * CalculateMemPoolAncestors() calculates the in-mempool (not including
     640                 :             :      * what is in the change set itself) ancestors of a given transaction.
     641                 :             :      *
     642                 :             :      * Apply() will apply the removals and additions that are staged into the
     643                 :             :      * mempool.
     644                 :             :      *
     645                 :             :      * Only one changeset may exist at a time. While a changeset is
     646                 :             :      * outstanding, no removals or additions may be made directly to the
     647                 :             :      * mempool.
     648                 :             :      */
     649                 :             :     class ChangeSet {
     650                 :             :     public:
     651                 :       26731 :         explicit ChangeSet(CTxMemPool* pool) : m_pool(pool) { m_pool->m_txgraph->StartStaging(); }
     652                 :       26731 :         ~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool->cs) {
     653                 :       26731 :             AssertLockHeld(m_pool->cs);
     654         [ +  + ]:       26731 :             if (m_pool->m_txgraph->HaveStaging()) {
     655                 :          43 :                 m_pool->m_txgraph->AbortStaging();
     656                 :             :             }
     657                 :       26731 :             m_pool->m_have_changeset = false;
     658                 :       26731 :         }
     659                 :             : 
     660                 :             :         ChangeSet(const ChangeSet&) = delete;
     661                 :             :         ChangeSet& operator=(const ChangeSet&) = delete;
     662                 :             : 
     663                 :             :         using TxHandle = CTxMemPool::txiter;
     664                 :             : 
     665                 :             :         TxHandle StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp);
     666                 :             : 
     667                 :             :         void StageRemoval(CTxMemPool::txiter it);
     668                 :             : 
     669         [ +  + ]:         109 :         const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; }
     670                 :             : 
     671                 :             :         /** Check if any cluster limits are exceeded. Returns true if pass, false if fail. */
     672                 :             :         bool CheckMemPoolPolicyLimits();
     673                 :             : 
     674                 :           2 :         CTxMemPool::setEntries CalculateMemPoolAncestors(TxHandle tx)
     675                 :             :         {
     676                 :             :             // Look up transaction in our cache first
     677                 :           2 :             auto it = m_ancestors.find(tx);
     678         [ -  + ]:           2 :             if (it != m_ancestors.end()) return it->second;
     679                 :             : 
     680                 :             :             // If not found, try to have the mempool calculate it, and cache
     681                 :             :             // for later.
     682                 :           2 :             LOCK(m_pool->cs);
     683         [ +  - ]:           2 :             auto ret = m_pool->CalculateMemPoolAncestors(*tx);
     684         [ +  - ]:           2 :             m_ancestors.try_emplace(tx, ret);
     685                 :           2 :             return ret;
     686         [ +  - ]:           4 :         }
     687                 :             : 
     688                 :           4 :         std::vector<CTransactionRef> GetAddedTxns() const {
     689                 :           4 :             std::vector<CTransactionRef> ret;
     690   [ -  +  +  - ]:           4 :             ret.reserve(m_entry_vec.size());
     691         [ +  + ]:          12 :             for (const auto& entry : m_entry_vec) {
     692   [ +  -  +  - ]:          24 :                 ret.emplace_back(entry->GetSharedTx());
     693                 :             :             }
     694                 :           4 :             return ret;
     695                 :           0 :         }
     696                 :             : 
     697                 :             :         /**
     698                 :             :          * Calculate the sorted chunks for the old and new mempool relating to the
     699                 :             :          * clusters that would be affected by a potential replacement transaction.
     700                 :             :          *
     701                 :             :          * @return old and new diagram pair respectively, or an error string if the conflicts don't match a calculable topology
     702                 :             :          */
     703                 :             :         util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CalculateChunksForRBF();
     704                 :             : 
     705   [ -  +  +  +  :          11 :         size_t GetTxCount() const { return m_entry_vec.size(); }
             -  +  +  - ]
     706   [ +  -  +  - ]:           3 :         const CTransaction& GetAddedTxn(size_t index) const { return m_entry_vec.at(index)->GetTx(); }
     707                 :             : 
     708                 :             :         void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
     709                 :             : 
     710                 :             :     private:
     711                 :             :         void ProcessDependencies();
     712                 :             : 
     713                 :             :         CTxMemPool* m_pool;
     714                 :             :         CTxMemPool::indexed_transaction_set m_to_add;
     715                 :             :         std::vector<CTxMemPool::txiter> m_entry_vec; // track the added transactions' insertion order
     716                 :             :         // map from the m_to_add index to the ancestors for the transaction
     717                 :             :         std::map<CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash> m_ancestors;
     718                 :             :         CTxMemPool::setEntries m_to_remove;
     719                 :             :         bool m_dependencies_processed{false};
     720                 :             : 
     721                 :             :         friend class CTxMemPool;
     722                 :             :     };
     723                 :             : 
     724                 :       26731 :     std::unique_ptr<ChangeSet> GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs) {
     725                 :       26731 :         Assume(!m_have_changeset);
     726                 :       26731 :         m_have_changeset = true;
     727                 :       26731 :         return std::make_unique<ChangeSet>(this);
     728                 :             :     }
     729                 :             : 
     730                 :             :     bool m_have_changeset GUARDED_BY(cs){false};
     731                 :             : 
     732                 :             :     friend class CTxMemPool::ChangeSet;
     733                 :             : 
     734                 :             : private:
     735                 :             :     // Apply the given changeset to the mempool, by removing transactions in
     736                 :             :     // the to_remove set and adding transactions in the to_add set.
     737                 :             :     void Apply(CTxMemPool::ChangeSet* changeset) EXCLUSIVE_LOCKS_REQUIRED(cs);
     738                 :             : 
     739                 :             :     // addNewTransaction must update state for all ancestors of a given transaction,
     740                 :             :     // to track size/count of descendant transactions.  First version of
     741                 :             :     // addNewTransaction can be used to have it call CalculateMemPoolAncestors(), and
     742                 :             :     // then invoke the second version.
     743                 :             :     // Note that addNewTransaction is ONLY called (via Apply()) from ATMP
     744                 :             :     // outside of tests and any other callers may break wallet's in-mempool
     745                 :             :     // tracking (due to lack of CValidationInterface::TransactionAddedToMempool
     746                 :             :     // callbacks).
     747                 :             :     void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs);
     748                 :             : public:
     749         [ -  + ]:        8209 :     void StartBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { assert(!m_builder); m_builder = m_txgraph->GetBlockBuilder(); }
     750                 :        9159 :     FeePerWeight GetBlockBuilderChunk(std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef>& entries) const EXCLUSIVE_LOCKS_REQUIRED(cs)
     751                 :             :     {
     752         [ -  + ]:        9159 :         if (!m_builder) { return {}; }
     753                 :             : 
     754                 :        9159 :         auto res = m_builder->GetCurrentChunk();
     755         [ +  + ]:        9159 :         if (!res) { return {}; }
     756                 :             : 
     757         [ +  - ]:         953 :         auto [chunk_entries, chunk_feerate] = *res;
     758         [ +  + ]:        1976 :         for (TxGraph::Ref* ref : chunk_entries) {
     759         [ +  - ]:        1023 :             entries.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref));
     760                 :             :         }
     761                 :         953 :         return chunk_feerate;
     762                 :       10112 :     }
     763                 :         946 :     void IncludeBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Include(); }
     764                 :           4 :     void SkipBuilderChunk() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder->Skip(); }
     765         [ +  - ]:        8209 :     void StopBlockBuilding() const EXCLUSIVE_LOCKS_REQUIRED(cs) { m_builder.reset(); }
     766                 :             : };
     767                 :             : 
     768                 :             : /**
     769                 :             :  * CCoinsView that brings transactions from a mempool into view.
     770                 :             :  * It does not check for spendings by memory pool transactions.
     771                 :             :  * Instead, it provides access to all Coins which are either unspent in the
     772                 :             :  * base CCoinsView, are outputs from any mempool transaction, or are
     773                 :             :  * tracked temporarily to allow transaction dependencies in package validation.
     774                 :             :  * This allows transaction replacement to work as expected, as you want to
     775                 :             :  * have all inputs "available" to check signatures, and any cycles in the
     776                 :             :  * dependency graph are checked directly in AcceptToMemoryPool.
     777                 :             :  * It also allows you to sign a double-spend directly in
     778                 :             :  * signrawtransactionwithkey and signrawtransactionwithwallet,
     779                 :             :  * as long as the conflicting transaction is not yet confirmed.
     780                 :             :  */
     781                 :             : class CCoinsViewMemPool : public CCoinsViewBacked
     782                 :             : {
     783                 :             :     /**
     784                 :             :     * Coins made available by transactions being validated. Tracking these allows for package
     785                 :             :     * validation, since we can access transaction outputs without submitting them to mempool.
     786                 :             :     */
     787                 :             :     std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
     788                 :             : 
     789                 :             :     /**
     790                 :             :      * Set of all coins that have been fetched from mempool or created using PackageAddTransaction
     791                 :             :      * (not base). Used to track the origin of a coin, see GetNonBaseCoins().
     792                 :             :      */
     793                 :             :     mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
     794                 :             : protected:
     795                 :             :     const CTxMemPool& mempool;
     796                 :             : 
     797                 :             : public:
     798                 :             :     CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
     799                 :             :     /** GetCoin, returning whether it exists and is not spent. Also updates m_non_base_coins if the
     800                 :             :      * coin is not fetched from base. */
     801                 :             :     std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
     802                 :             :     /** Add the coins created by this transaction. These coins are only temporarily stored in
     803                 :             :      * m_temp_added and cannot be flushed to the back end. Only used for package validation. */
     804                 :             :     void PackageAddTransaction(const CTransactionRef& tx);
     805                 :             :     /** Get all coins in m_non_base_coins. */
     806                 :         246 :     const std::unordered_set<COutPoint, SaltedOutpointHasher>& GetNonBaseCoins() const { return m_non_base_coins; }
     807                 :             :     /** Clear m_temp_added and m_non_base_coins. */
     808                 :             :     void Reset();
     809                 :             : };
     810                 :             : #endif // BITCOIN_TXMEMPOOL_H
        

Generated by: LCOV version 2.0-1