LCOV - code coverage report
Current view: top level - src - txmempool.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 85 92 92.4 %
Date: 2024-05-24 08:22:33 Functions: 26 29 89.7 %
Branches: 18 32 56.2 %

           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 <sync.h>
      21                 :            : #include <util/epochguard.h>
      22                 :            : #include <util/hasher.h>
      23                 :            : #include <util/result.h>
      24                 :            : #include <util/feefrac.h>
      25                 :            : 
      26                 :            : #include <boost/multi_index/hashed_index.hpp>
      27                 :            : #include <boost/multi_index/identity.hpp>
      28                 :            : #include <boost/multi_index/indexed_by.hpp>
      29                 :            : #include <boost/multi_index/ordered_index.hpp>
      30                 :            : #include <boost/multi_index/sequenced_index.hpp>
      31                 :            : #include <boost/multi_index/tag.hpp>
      32                 :            : #include <boost/multi_index_container.hpp>
      33                 :            : 
      34                 :            : #include <atomic>
      35                 :            : #include <map>
      36                 :            : #include <optional>
      37                 :            : #include <set>
      38                 :            : #include <string>
      39                 :            : #include <string_view>
      40                 :            : #include <utility>
      41                 :            : #include <vector>
      42                 :            : 
      43                 :            : class CChain;
      44                 :            : class ValidationSignals;
      45                 :            : 
      46                 :            : /** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
      47                 :            : static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
      48                 :            : 
      49                 :            : /**
      50                 :            :  * Test whether the LockPoints height and time are still valid on the current chain
      51                 :            :  */
      52                 :            : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
      53                 :            : 
      54                 :            : // extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
      55                 :            : struct mempoolentry_txid
      56                 :            : {
      57                 :            :     typedef uint256 result_type;
      58                 :   58877439 :     result_type operator() (const CTxMemPoolEntry &entry) const
      59                 :            :     {
      60                 :   58877439 :         return entry.GetTx().GetHash();
      61                 :            :     }
      62                 :            : 
      63                 :            :     result_type operator() (const CTransactionRef& tx) const
      64                 :            :     {
      65                 :            :         return tx->GetHash();
      66                 :            :     }
      67                 :            : };
      68                 :            : 
      69                 :            : // extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
      70                 :            : struct mempoolentry_wtxid
      71                 :            : {
      72                 :            :     typedef uint256 result_type;
      73                 :   43301669 :     result_type operator() (const CTxMemPoolEntry &entry) const
      74                 :            :     {
      75                 :   43301669 :         return entry.GetTx().GetWitnessHash();
      76                 :            :     }
      77                 :            : 
      78                 :            :     result_type operator() (const CTransactionRef& tx) const
      79                 :            :     {
      80                 :            :         return tx->GetWitnessHash();
      81                 :            :     }
      82                 :            : };
      83                 :            : 
      84                 :            : 
      85                 :            : /** \class CompareTxMemPoolEntryByDescendantScore
      86                 :            :  *
      87                 :            :  *  Sort an entry by max(score/size of entry's tx, score/size with all descendants).
      88                 :            :  */
      89                 :            : class CompareTxMemPoolEntryByDescendantScore
      90                 :            : {
      91                 :            : public:
      92                 :  151579730 :     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
      93                 :            :     {
      94                 :  151579730 :         double a_mod_fee, a_size, b_mod_fee, b_size;
      95                 :            : 
      96                 :  151579730 :         GetModFeeAndSize(a, a_mod_fee, a_size);
      97                 :  151579730 :         GetModFeeAndSize(b, b_mod_fee, b_size);
      98                 :            : 
      99                 :            :         // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
     100                 :  151579730 :         double f1 = a_mod_fee * b_size;
     101                 :  151579730 :         double f2 = a_size * b_mod_fee;
     102                 :            : 
     103         [ +  + ]:  151579730 :         if (f1 == f2) {
     104                 :   77382426 :             return a.GetTime() >= b.GetTime();
     105                 :            :         }
     106                 :   74197304 :         return f1 < f2;
     107                 :  151579730 :     }
     108                 :            : 
     109                 :            :     // Return the fee/size we're using for sorting this entry.
     110                 :  303159460 :     void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
     111                 :            :     {
     112                 :            :         // Compare feerate with descendants to feerate of the transaction, and
     113                 :            :         // return the fee/size for the max.
     114                 :  303159460 :         double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
     115                 :  303159460 :         double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
     116                 :            : 
     117         [ +  + ]:  303159460 :         if (f2 > f1) {
     118                 :   95296260 :             mod_fee = a.GetModFeesWithDescendants();
     119                 :   95296260 :             size = a.GetSizeWithDescendants();
     120                 :   95296260 :         } else {
     121                 :  207863200 :             mod_fee = a.GetModifiedFee();
     122                 :  207863200 :             size = a.GetTxSize();
     123                 :            :         }
     124                 :  303159460 :     }
     125                 :            : };
     126                 :            : 
     127                 :            : /** \class CompareTxMemPoolEntryByScore
     128                 :            :  *
     129                 :            :  *  Sort by feerate of entry (fee/size) in descending order
     130                 :            :  *  This is only used for transaction relay, so we use GetFee()
     131                 :            :  *  instead of GetModifiedFee() to avoid leaking prioritization
     132                 :            :  *  information via the sort order.
     133                 :            :  */
     134                 :            : class CompareTxMemPoolEntryByScore
     135                 :            : {
     136                 :            : public:
     137                 :    4349437 :     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
     138                 :            :     {
     139                 :    4349437 :         double f1 = (double)a.GetFee() * b.GetTxSize();
     140                 :    4349437 :         double f2 = (double)b.GetFee() * a.GetTxSize();
     141         [ +  + ]:    4349437 :         if (f1 == f2) {
     142                 :    2488885 :             return b.GetTx().GetHash() < a.GetTx().GetHash();
     143                 :            :         }
     144                 :    1860552 :         return f1 > f2;
     145                 :    4349437 :     }
     146                 :            : };
     147                 :            : 
     148                 :            : class CompareTxMemPoolEntryByEntryTime
     149                 :            : {
     150                 :            : public:
     151                 :   37285679 :     bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
     152                 :            :     {
     153                 :   37285679 :         return a.GetTime() < b.GetTime();
     154                 :            :     }
     155                 :            : };
     156                 :            : 
     157                 :            : /** \class CompareTxMemPoolEntryByAncestorScore
     158                 :            :  *
     159                 :            :  *  Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
     160                 :            :  */
     161                 :            : class CompareTxMemPoolEntryByAncestorFee
     162                 :            : {
     163                 :            : public:
     164                 :            :     template<typename T>
     165                 :   38014951 :     bool operator()(const T& a, const T& b) const
     166                 :            :     {
     167                 :   38014951 :         double a_mod_fee, a_size, b_mod_fee, b_size;
     168                 :            : 
     169                 :   38014951 :         GetModFeeAndSize(a, a_mod_fee, a_size);
     170                 :   38014951 :         GetModFeeAndSize(b, b_mod_fee, b_size);
     171                 :            : 
     172                 :            :         // Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
     173                 :   38014951 :         double f1 = a_mod_fee * b_size;
     174                 :   38014951 :         double f2 = a_size * b_mod_fee;
     175                 :            : 
     176         [ +  + ]:   38014951 :         if (f1 == f2) {
     177                 :   15188719 :             return a.GetTx().GetHash() < b.GetTx().GetHash();
     178                 :            :         }
     179                 :   22826232 :         return f1 > f2;
     180                 :   38014951 :     }
     181                 :            : 
     182                 :            :     // Return the fee/size we're using for sorting this entry.
     183                 :            :     template <typename T>
     184                 :   76029902 :     void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
     185                 :            :     {
     186                 :            :         // Compare feerate with ancestors to feerate of the transaction, and
     187                 :            :         // return the fee/size for the min.
     188                 :   76029902 :         double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
     189                 :   76029902 :         double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
     190                 :            : 
     191         [ +  + ]:   76029902 :         if (f1 > f2) {
     192                 :   38110792 :             mod_fee = a.GetModFeesWithAncestors();
     193                 :   38110792 :             size = a.GetSizeWithAncestors();
     194                 :   38110792 :         } else {
     195                 :   37919110 :             mod_fee = a.GetModifiedFee();
     196                 :   37919110 :             size = a.GetTxSize();
     197                 :            :         }
     198                 :   76029902 :     }
     199                 :            : };
     200                 :            : 
     201                 :            : // Multi_index tag names
     202                 :            : struct descendant_score {};
     203                 :            : struct entry_time {};
     204                 :            : struct ancestor_score {};
     205                 :            : struct index_by_wtxid {};
     206                 :            : 
     207                 :            : /**
     208                 :            :  * Information about a mempool transaction.
     209                 :            :  */
     210                 :            : struct TxMempoolInfo
     211                 :            : {
     212                 :            :     /** The transaction itself */
     213                 :            :     CTransactionRef tx;
     214                 :            : 
     215                 :            :     /** Time the transaction entered the mempool. */
     216                 :            :     std::chrono::seconds m_time;
     217                 :            : 
     218                 :            :     /** Fee of the transaction. */
     219                 :            :     CAmount fee;
     220                 :            : 
     221                 :            :     /** Virtual size of the transaction. */
     222                 :            :     int32_t vsize;
     223                 :            : 
     224                 :            :     /** The fee delta. */
     225                 :            :     int64_t nFeeDelta;
     226                 :            : };
     227                 :            : 
     228                 :            : /**
     229                 :            :  * CTxMemPool stores valid-according-to-the-current-best-chain transactions
     230                 :            :  * that may be included in the next block.
     231                 :            :  *
     232                 :            :  * Transactions are added when they are seen on the network (or created by the
     233                 :            :  * local node), but not all transactions seen are added to the pool. For
     234                 :            :  * example, the following new transactions will not be added to the mempool:
     235                 :            :  * - a transaction which doesn't meet the minimum fee requirements.
     236                 :            :  * - a new transaction that double-spends an input of a transaction already in
     237                 :            :  * the pool where the new transaction does not meet the Replace-By-Fee
     238                 :            :  * requirements as defined in doc/policy/mempool-replacements.md.
     239                 :            :  * - a non-standard transaction.
     240                 :            :  *
     241                 :            :  * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
     242                 :            :  *
     243                 :            :  * mapTx is a boost::multi_index that sorts the mempool on 5 criteria:
     244                 :            :  * - transaction hash (txid)
     245                 :            :  * - witness-transaction hash (wtxid)
     246                 :            :  * - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)]
     247                 :            :  * - time in mempool
     248                 :            :  * - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)]
     249                 :            :  *
     250                 :            :  * Note: the term "descendant" refers to in-mempool transactions that depend on
     251                 :            :  * this one, while "ancestor" refers to in-mempool transactions that a given
     252                 :            :  * transaction depends on.
     253                 :            :  *
     254                 :            :  * In order for the feerate sort to remain correct, we must update transactions
     255                 :            :  * in the mempool when new descendants arrive.  To facilitate this, we track
     256                 :            :  * the set of in-mempool direct parents and direct children in mapLinks.  Within
     257                 :            :  * each CTxMemPoolEntry, we track the size and fees of all descendants.
     258                 :            :  *
     259                 :            :  * Usually when a new transaction is added to the mempool, it has no in-mempool
     260                 :            :  * children (because any such children would be an orphan).  So in
     261                 :            :  * addUnchecked(), we:
     262                 :            :  * - update a new entry's setMemPoolParents to include all in-mempool parents
     263                 :            :  * - update the new entry's direct parents to include the new tx as a child
     264                 :            :  * - update all ancestors of the transaction to include the new tx's size/fee
     265                 :            :  *
     266                 :            :  * When a transaction is removed from the mempool, we must:
     267                 :            :  * - update all in-mempool parents to not track the tx in setMemPoolChildren
     268                 :            :  * - update all ancestors to not include the tx's size/fees in descendant state
     269                 :            :  * - update all in-mempool children to not include it as a parent
     270                 :            :  *
     271                 :            :  * These happen in UpdateForRemoveFromMempool().  (Note that when removing a
     272                 :            :  * transaction along with its descendants, we must calculate that set of
     273                 :            :  * transactions to be removed before doing the removal, or else the mempool can
     274                 :            :  * be in an inconsistent state where it's impossible to walk the ancestors of
     275                 :            :  * a transaction.)
     276                 :            :  *
     277                 :            :  * In the event of a reorg, the assumption that a newly added tx has no
     278                 :            :  * in-mempool children is false.  In particular, the mempool is in an
     279                 :            :  * inconsistent state while new transactions are being added, because there may
     280                 :            :  * be descendant transactions of a tx coming from a disconnected block that are
     281                 :            :  * unreachable from just looking at transactions in the mempool (the linking
     282                 :            :  * transactions may also be in the disconnected block, waiting to be added).
     283                 :            :  * Because of this, there's not much benefit in trying to search for in-mempool
     284                 :            :  * children in addUnchecked().  Instead, in the special case of transactions
     285                 :            :  * being added from a disconnected block, we require the caller to clean up the
     286                 :            :  * state, to account for in-mempool, out-of-block descendants for all the
     287                 :            :  * in-block transactions by calling UpdateTransactionsFromBlock().  Note that
     288                 :            :  * until this is called, the mempool state is not consistent, and in particular
     289                 :            :  * mapLinks may not be correct (and therefore functions like
     290                 :            :  * CalculateMemPoolAncestors() and CalculateDescendants() that rely
     291                 :            :  * on them to walk the mempool are not generally safe to use).
     292                 :            :  *
     293                 :            :  * Computational limits:
     294                 :            :  *
     295                 :            :  * Updating all in-mempool ancestors of a newly added transaction can be slow,
     296                 :            :  * if no bound exists on how many in-mempool ancestors there may be.
     297                 :            :  * CalculateMemPoolAncestors() takes configurable limits that are designed to
     298                 :            :  * prevent these calculations from being too CPU intensive.
     299                 :            :  *
     300                 :            :  */
     301                 :            : class CTxMemPool
     302                 :            : {
     303                 :            : protected:
     304                 :            :     std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
     305                 :            : 
     306                 :            :     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.
     307                 :            :     CAmount m_total_fee GUARDED_BY(cs){0};       //!< sum of all mempool tx's fees (NOT modified fee)
     308                 :            :     uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
     309                 :            : 
     310                 :            :     mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
     311                 :            :     mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
     312                 :            :     mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially
     313                 :            :     mutable Epoch m_epoch GUARDED_BY(cs){};
     314                 :            : 
     315                 :            :     // In-memory counter for external mempool tracking purposes.
     316                 :            :     // This number is incremented once every time a transaction
     317                 :            :     // is added or removed from the mempool for any reason.
     318                 :            :     mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
     319                 :            : 
     320                 :            :     void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
     321                 :            : 
     322                 :            :     bool m_load_tried GUARDED_BY(cs){false};
     323                 :            : 
     324                 :            :     CFeeRate GetMinFee(size_t sizelimit) const;
     325                 :            : 
     326                 :            : public:
     327                 :            : 
     328                 :            :     static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
     329                 :            : 
     330                 :            :     typedef boost::multi_index_container<
     331                 :            :         CTxMemPoolEntry,
     332                 :            :         boost::multi_index::indexed_by<
     333                 :            :             // sorted by txid
     334                 :            :             boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
     335                 :            :             // sorted by wtxid
     336                 :            :             boost::multi_index::hashed_unique<
     337                 :            :                 boost::multi_index::tag<index_by_wtxid>,
     338                 :            :                 mempoolentry_wtxid,
     339                 :            :                 SaltedTxidHasher
     340                 :            :             >,
     341                 :            :             // sorted by fee rate
     342                 :            :             boost::multi_index::ordered_non_unique<
     343                 :            :                 boost::multi_index::tag<descendant_score>,
     344                 :            :                 boost::multi_index::identity<CTxMemPoolEntry>,
     345                 :            :                 CompareTxMemPoolEntryByDescendantScore
     346                 :            :             >,
     347                 :            :             // sorted by entry time
     348                 :            :             boost::multi_index::ordered_non_unique<
     349                 :            :                 boost::multi_index::tag<entry_time>,
     350                 :            :                 boost::multi_index::identity<CTxMemPoolEntry>,
     351                 :            :                 CompareTxMemPoolEntryByEntryTime
     352                 :            :             >,
     353                 :            :             // sorted by fee rate with ancestors
     354                 :            :             boost::multi_index::ordered_non_unique<
     355                 :            :                 boost::multi_index::tag<ancestor_score>,
     356                 :            :                 boost::multi_index::identity<CTxMemPoolEntry>,
     357                 :            :                 CompareTxMemPoolEntryByAncestorFee
     358                 :            :             >
     359                 :            :         >
     360                 :            :     > indexed_transaction_set;
     361                 :            : 
     362                 :            :     /**
     363                 :            :      * This mutex needs to be locked when accessing `mapTx` or other members
     364                 :            :      * that are guarded by it.
     365                 :            :      *
     366                 :            :      * @par Consistency guarantees
     367                 :            :      *
     368                 :            :      * By design, it is guaranteed that:
     369                 :            :      *
     370                 :            :      * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
     371                 :            :      *    that is consistent with current chain tip (`ActiveChain()` and
     372                 :            :      *    `CoinsTip()`) and is fully populated. Fully populated means that if the
     373                 :            :      *    current active chain is missing transactions that were present in a
     374                 :            :      *    previously active chain, all the missing transactions will have been
     375                 :            :      *    re-added to the mempool and should be present if they meet size and
     376                 :            :      *    consistency constraints.
     377                 :            :      *
     378                 :            :      * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
     379                 :            :      *    consistent with some chain that was active since `cs_main` was last
     380                 :            :      *    locked, and that is fully populated as described above. It is ok for
     381                 :            :      *    code that only needs to query or remove transactions from the mempool
     382                 :            :      *    to lock just `mempool.cs` without `cs_main`.
     383                 :            :      *
     384                 :            :      * To provide these guarantees, it is necessary to lock both `cs_main` and
     385                 :            :      * `mempool.cs` whenever adding transactions to the mempool and whenever
     386                 :            :      * changing the chain tip. It's necessary to keep both mutexes locked until
     387                 :            :      * the mempool is consistent with the new chain tip and fully populated.
     388                 :            :      */
     389                 :            :     mutable RecursiveMutex cs;
     390                 :            :     indexed_transaction_set mapTx GUARDED_BY(cs);
     391                 :            : 
     392                 :            :     using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
     393                 :            :     std::vector<CTransactionRef> txns_randomized GUARDED_BY(cs); //!< All transactions in mapTx, in random order
     394                 :            : 
     395                 :            :     typedef std::set<txiter, CompareIteratorByHash> setEntries;
     396                 :            : 
     397                 :            :     using Limits = kernel::MemPoolLimits;
     398                 :            : 
     399                 :            :     uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     400                 :            : private:
     401                 :            :     typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
     402                 :            : 
     403                 :            : 
     404                 :            :     void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
     405                 :            :     void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
     406                 :            : 
     407                 :            :     std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
     408                 :            : 
     409                 :            :     /**
     410                 :            :      * Track locally submitted transactions to periodically retry initial broadcast.
     411                 :            :      */
     412                 :            :     std::set<uint256> m_unbroadcast_txids GUARDED_BY(cs);
     413                 :            : 
     414                 :            : 
     415                 :            :     /**
     416                 :            :      * Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor
     417                 :            :      * and descendant limits (including staged_ancestors themselves, entry_size and entry_count).
     418                 :            :      *
     419                 :            :      * @param[in]   entry_size          Virtual size to include in the limits.
     420                 :            :      * @param[in]   entry_count         How many entries to include in the limits.
     421                 :            :      * @param[in]   staged_ancestors    Should contain entries in the mempool.
     422                 :            :      * @param[in]   limits              Maximum number and size of ancestors and descendants
     423                 :            :      *
     424                 :            :      * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit
     425                 :            :      */
     426                 :            :     util::Result<setEntries> CalculateAncestorsAndCheckLimits(int64_t entry_size,
     427                 :            :                                                               size_t entry_count,
     428                 :            :                                                               CTxMemPoolEntry::Parents &staged_ancestors,
     429                 :            :                                                               const Limits& limits
     430                 :            :                                                               ) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     431                 :            : 
     432                 :            : public:
     433                 :            :     indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
     434                 :            :     std::map<uint256, CAmount> mapDeltas GUARDED_BY(cs);
     435                 :            : 
     436                 :            :     using Options = kernel::MemPoolOptions;
     437                 :            : 
     438                 :            :     const Options m_opts;
     439                 :            : 
     440                 :            :     /** Create a new CTxMemPool.
     441                 :            :      * Sanity checks will be off by default for performance, because otherwise
     442                 :            :      * accepting transactions becomes O(N^2) where N is the number of transactions
     443                 :            :      * in the pool.
     444                 :            :      */
     445                 :            :     explicit CTxMemPool(const Options& opts);
     446                 :            : 
     447                 :            :     /**
     448                 :            :      * If sanity-checking is turned on, check makes sure the pool is
     449                 :            :      * consistent (does not contain two transactions that spend the same inputs,
     450                 :            :      * all inputs are in the mapNextTx array). If sanity-checking is turned off,
     451                 :            :      * check does nothing.
     452                 :            :      */
     453                 :            :     void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
     454                 :            : 
     455                 :            :     // addUnchecked must updated state for all ancestors of a given transaction,
     456                 :            :     // to track size/count of descendant transactions.  First version of
     457                 :            :     // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
     458                 :            :     // then invoke the second version.
     459                 :            :     // Note that addUnchecked is ONLY called from ATMP outside of tests
     460                 :            :     // and any other callers may break wallet's in-mempool tracking (due to
     461                 :            :     // lack of CValidationInterface::TransactionAddedToMempool callbacks).
     462                 :            :     void addUnchecked(const CTxMemPoolEntry& entry) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
     463                 :            :     void addUnchecked(const CTxMemPoolEntry& entry, setEntries& setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
     464                 :            : 
     465                 :            :     void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     466                 :            :     /** After reorg, filter the entries that would no longer be valid in the next block, and update
     467                 :            :      * the entries' cached LockPoints if needed.  The mempool does not have any knowledge of
     468                 :            :      * consensus rules. It just applies the callable function and removes the ones for which it
     469                 :            :      * returns true.
     470                 :            :      * @param[in]   filter_final_and_mature   Predicate that checks the relevant validation rules
     471                 :            :      *                                        and updates an entry's LockPoints.
     472                 :            :      * */
     473                 :            :     void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
     474                 :            :     void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
     475                 :            :     void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
     476                 :            : 
     477                 :            :     bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid=false);
     478                 :            :     bool isSpent(const COutPoint& outpoint) const;
     479                 :            :     unsigned int GetTransactionsUpdated() const;
     480                 :            :     void AddTransactionsUpdated(unsigned int n);
     481                 :            :     /**
     482                 :            :      * Check that none of this transactions inputs are in the mempool, and thus
     483                 :            :      * the tx is not dependent on other mempool transactions to be included in a block.
     484                 :            :      */
     485                 :            :     bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     486                 :            : 
     487                 :            :     /** Affect CreateNewBlock prioritisation of transactions */
     488                 :            :     void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
     489                 :            :     void ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     490                 :            :     void ClearPrioritisation(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
     491                 :            : 
     492                 :            :     struct delta_info {
     493                 :            :         /** Whether this transaction is in the mempool. */
     494                 :            :         const bool in_mempool;
     495                 :            :         /** The fee delta added using PrioritiseTransaction(). */
     496                 :            :         const CAmount delta;
     497                 :            :         /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
     498                 :            :         std::optional<CAmount> modified_fee;
     499                 :            :         /** The prioritised transaction's txid. */
     500                 :            :         const uint256 txid;
     501                 :            :     };
     502                 :            :     /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
     503                 :            :     std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
     504                 :            : 
     505                 :            :     /** Get the transaction in the pool that spends the same prevout */
     506                 :            :     const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     507                 :            : 
     508                 :            :     /** Returns an iterator to the given hash, if found */
     509                 :            :     std::optional<txiter> GetIter(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     510                 :            : 
     511                 :            :     /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
     512                 :            :      * Does not require that all of the hashes correspond to actual transactions in the mempool,
     513                 :            :      * only returns the ones that exist. */
     514                 :            :     setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     515                 :            : 
     516                 :            :     /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
     517                 :            :      * The nth element in txids becomes the nth element in the returned vector. If any of the txids
     518                 :            :      * don't actually exist in the mempool, returns an empty vector. */
     519                 :            :     std::vector<txiter> GetIterVec(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     520                 :            : 
     521                 :            :     /** Remove a set of transactions from the mempool.
     522                 :            :      *  If a transaction is in this set, then all in-mempool descendants must
     523                 :            :      *  also be in the set, unless this transaction is being removed for being
     524                 :            :      *  in a block.
     525                 :            :      *  Set updateDescendants to true when removing a tx that was in a block, so
     526                 :            :      *  that any in-mempool descendants have their ancestor state updated.
     527                 :            :      */
     528                 :            :     void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     529                 :            : 
     530                 :            :     /** UpdateTransactionsFromBlock is called when adding transactions from a
     531                 :            :      * disconnected block back to the mempool, new mempool entries may have
     532                 :            :      * children in the mempool (which is generally not the case when otherwise
     533                 :            :      * adding transactions).
     534                 :            :      *  @post updated descendant state for descendants of each transaction in
     535                 :            :      *        vHashesToUpdate (excluding any child transactions present in
     536                 :            :      *        vHashesToUpdate, which are already accounted for). Updated state
     537                 :            :      *        includes add fee/size information for such descendants to the
     538                 :            :      *        parent and updated ancestor state to include the parent.
     539                 :            :      *
     540                 :            :      * @param[in] vHashesToUpdate          The set of txids from the
     541                 :            :      *     disconnected block that have been accepted back into the mempool.
     542                 :            :      */
     543                 :            :     void UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
     544                 :            : 
     545                 :            :     /**
     546                 :            :      * Try to calculate all in-mempool ancestors of entry.
     547                 :            :      * (these are all calculated including the tx itself)
     548                 :            :      *
     549                 :            :      * @param[in]   entry               CTxMemPoolEntry of which all in-mempool ancestors are calculated
     550                 :            :      * @param[in]   limits              Maximum number and size of ancestors and descendants
     551                 :            :      * @param[in]   fSearchForParents   Whether to search a tx's vin for in-mempool parents, or look
     552                 :            :      *                                  up parents from mapLinks. Must be true for entries not in
     553                 :            :      *                                  the mempool
     554                 :            :      *
     555                 :            :      * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit
     556                 :            :      */
     557                 :            :     util::Result<setEntries> CalculateMemPoolAncestors(const CTxMemPoolEntry& entry,
     558                 :            :                                    const Limits& limits,
     559                 :            :                                    bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     560                 :            : 
     561                 :            :     /**
     562                 :            :      * Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
     563                 :            :      * Should only be used when it is assumed CalculateMemPoolAncestors would not fail. If
     564                 :            :      * CalculateMemPoolAncestors does unexpectedly fail, an empty setEntries is returned and the
     565                 :            :      * error is logged to BCLog::MEMPOOL with level BCLog::Level::Error. In debug builds, failure
     566                 :            :      * of CalculateMemPoolAncestors will lead to shutdown due to assertion failure.
     567                 :            :      *
     568                 :            :      * @param[in]   calling_fn_name     Name of calling function so we can properly log the call site
     569                 :            :      *
     570                 :            :      * @return a setEntries corresponding to the result of CalculateMemPoolAncestors or an empty
     571                 :            :      *         setEntries if it failed
     572                 :            :      *
     573                 :            :      * @see CTXMemPool::CalculateMemPoolAncestors()
     574                 :            :      */
     575                 :            :     setEntries AssumeCalculateMemPoolAncestors(
     576                 :            :         std::string_view calling_fn_name,
     577                 :            :         const CTxMemPoolEntry &entry,
     578                 :            :         const Limits& limits,
     579                 :            :         bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     580                 :            : 
     581                 :            :     /** Collect the entire cluster of connected transactions for each transaction in txids.
     582                 :            :      * All txids must correspond to transaction entries in the mempool, otherwise this returns an
     583                 :            :      * empty vector. This call will also exit early and return an empty vector if it collects 500 or
     584                 :            :      * more transactions as a DoS protection. */
     585                 :            :     std::vector<txiter> GatherClusters(const std::vector<uint256>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     586                 :            : 
     587                 :            :     /** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and
     588                 :            :      * check ancestor and descendant limits. Heuristics are used to estimate the ancestor and
     589                 :            :      * descendant count of all entries if the package were to be added to the mempool.  The limits
     590                 :            :      * are applied to the union of all package transactions. For example, if the package has 3
     591                 :            :      * transactions and limits.ancestor_count = 25, the union of all 3 sets of ancestors (including the
     592                 :            :      * transactions themselves) must be <= 22.
     593                 :            :      * @param[in]       package                 Transaction package being evaluated for acceptance
     594                 :            :      *                                          to mempool. The transactions need not be direct
     595                 :            :      *                                          ancestors/descendants of each other.
     596                 :            :      * @param[in]       total_vsize             Sum of virtual sizes for all transactions in package.
     597                 :            :      * @returns {} or the error reason if a limit is hit.
     598                 :            :      */
     599                 :            :     util::Result<void> CheckPackageLimits(const Package& package,
     600                 :            :                                           int64_t total_vsize) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     601                 :            : 
     602                 :            :     /** Populate setDescendants with all in-mempool descendants of hash.
     603                 :            :      *  Assumes that setDescendants includes all in-mempool descendants of anything
     604                 :            :      *  already in it.  */
     605                 :            :     void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
     606                 :            : 
     607                 :            :     /** The minimum fee to get into the mempool, which may itself not be enough
     608                 :            :      *  for larger-sized transactions.
     609                 :            :      *  The m_incremental_relay_feerate policy variable is used to bound the time it
     610                 :            :      *  takes the fee rate to go back down all the way to 0. When the feerate
     611                 :            :      *  would otherwise be half of this, it is set to 0 instead.
     612                 :            :      */
     613                 :     447883 :     CFeeRate GetMinFee() const {
     614                 :     447883 :         return GetMinFee(m_opts.max_size_bytes);
     615                 :            :     }
     616                 :            : 
     617                 :            :     /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
     618                 :            :       *  pvNoSpendsRemaining, if set, will be populated with the list of outpoints
     619                 :            :       *  which are not in mempool which no longer have any spends in this mempool.
     620                 :            :       */
     621                 :            :     void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
     622                 :            : 
     623                 :            :     /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
     624                 :            :     int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
     625                 :            : 
     626                 :            :     /**
     627                 :            :      * Calculate the ancestor and descendant count for the given transaction.
     628                 :            :      * The counts include the transaction itself.
     629                 :            :      * When ancestors is non-zero (ie, the transaction itself is in the mempool),
     630                 :            :      * ancestorsize and ancestorfees will also be set to the appropriate values.
     631                 :            :      */
     632                 :            :     void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
     633                 :            : 
     634                 :            :     /**
     635                 :            :      * @returns true if an initial attempt to load the persisted mempool was made, regardless of
     636                 :            :      *          whether the attempt was successful or not
     637                 :            :      */
     638                 :            :     bool GetLoadTried() const;
     639                 :            : 
     640                 :            :     /**
     641                 :            :      * Set whether or not an initial attempt to load the persisted mempool was made (regardless
     642                 :            :      * of whether the attempt was successful or not)
     643                 :            :      */
     644                 :            :     void SetLoadTried(bool load_tried);
     645                 :            : 
     646                 :       4150 :     unsigned long size() const
     647                 :            :     {
     648                 :       4150 :         LOCK(cs);
     649                 :       4150 :         return mapTx.size();
     650                 :       4150 :     }
     651                 :            : 
     652                 :      43911 :     uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
     653                 :            :     {
     654                 :      43911 :         AssertLockHeld(cs);
     655                 :      43911 :         return totalTxSize;
     656                 :            :     }
     657                 :            : 
     658                 :     139507 :     CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
     659                 :            :     {
     660                 :     139507 :         AssertLockHeld(cs);
     661                 :     139507 :         return m_total_fee;
     662                 :            :     }
     663                 :            : 
     664                 :    6533576 :     bool exists(const GenTxid& gtxid) const
     665                 :            :     {
     666                 :    6533576 :         LOCK(cs);
     667   [ +  -  +  + ]:    6533576 :         if (gtxid.IsWtxid()) {
     668   [ +  -  +  - ]:     540275 :             return (mapTx.get<index_by_wtxid>().count(gtxid.GetHash()) != 0);
     669                 :            :         }
     670   [ +  -  +  - ]:    5993301 :         return (mapTx.count(gtxid.GetHash()) != 0);
     671                 :    6533576 :     }
     672                 :            : 
     673                 :            :     const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs);
     674                 :            : 
     675                 :            :     CTransactionRef get(const uint256& hash) const;
     676                 :       4674 :     txiter get_iter_from_wtxid(const uint256& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
     677                 :            :     {
     678                 :       4674 :         AssertLockHeld(cs);
     679                 :       4674 :         return mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid));
     680                 :            :     }
     681                 :            :     TxMempoolInfo info(const GenTxid& gtxid) const;
     682                 :            : 
     683                 :            :     /** Returns info for a transaction if its entry_sequence < last_sequence */
     684                 :            :     TxMempoolInfo info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const;
     685                 :            : 
     686                 :            :     std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
     687                 :            :     std::vector<TxMempoolInfo> infoAll() const;
     688                 :            : 
     689                 :            :     size_t DynamicMemoryUsage() const;
     690                 :            : 
     691                 :            :     /** Adds a transaction to the unbroadcast set */
     692                 :          0 :     void AddUnbroadcastTx(const uint256& txid)
     693                 :            :     {
     694                 :          0 :         LOCK(cs);
     695                 :            :         // Sanity check the transaction is in the mempool & insert into
     696                 :            :         // unbroadcast set.
     697   [ #  #  #  #  :          0 :         if (exists(GenTxid::Txid(txid))) m_unbroadcast_txids.insert(txid);
             #  #  #  # ]
     698                 :          0 :     };
     699                 :            : 
     700                 :            :     /** Removes a transaction from the unbroadcast set */
     701                 :            :     void RemoveUnbroadcastTx(const uint256& txid, const bool unchecked = false);
     702                 :            : 
     703                 :            :     /** Returns transactions in unbroadcast set */
     704                 :       1285 :     std::set<uint256> GetUnbroadcastTxs() const
     705                 :            :     {
     706                 :       1285 :         LOCK(cs);
     707         [ +  - ]:       1285 :         return m_unbroadcast_txids;
     708                 :       1285 :     }
     709                 :            : 
     710                 :            :     /** Returns whether a txid is in the unbroadcast set */
     711                 :          0 :     bool IsUnbroadcastTx(const uint256& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
     712                 :            :     {
     713                 :          0 :         AssertLockHeld(cs);
     714                 :          0 :         return m_unbroadcast_txids.count(txid) != 0;
     715                 :            :     }
     716                 :            : 
     717                 :            :     /** Guards this internal counter for external reporting */
     718                 :     109845 :     uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     719                 :     109845 :         return m_sequence_number++;
     720                 :            :     }
     721                 :            : 
     722                 :     149724 :     uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
     723                 :     149724 :         return m_sequence_number;
     724                 :            :     }
     725                 :            : 
     726                 :            :     /**
     727                 :            :      * Calculate the sorted chunks for the old and new mempool relating to the
     728                 :            :      * clusters that would be affected by a potential replacement transaction.
     729                 :            :      * (replacement_fees, replacement_vsize) values are gathered from a
     730                 :            :      * proposed set of replacement transactions that are considered as a single
     731                 :            :      * chunk, and represent their complete cluster. In other words, they have no
     732                 :            :      * in-mempool ancestors.
     733                 :            :      *
     734                 :            :      * @param[in] replacement_fees    Package fees
     735                 :            :      * @param[in] replacement_vsize   Package size (must be greater than 0)
     736                 :            :      * @param[in] direct_conflicts    All transactions that would be removed directly by
     737                 :            :      *                                having a conflicting input with a proposed transaction
     738                 :            :      * @param[in] all_conflicts       All transactions that would be removed
     739                 :            :      * @return old and new diagram pair respectively, or an error string if the conflicts don't match a calculable topology
     740                 :            :      */
     741                 :            :     util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CalculateChunksForRBF(CAmount replacement_fees, int64_t replacement_vsize, const setEntries& direct_conflicts, const setEntries& all_conflicts) EXCLUSIVE_LOCKS_REQUIRED(cs);
     742                 :            : 
     743                 :            :     /* Check that all direct conflicts are in a cluster size of two or less. Each
     744                 :            :      * direct conflict may be in a separate cluster.
     745                 :            :      */
     746                 :            :     std::optional<std::string> CheckConflictTopology(const setEntries& direct_conflicts);
     747                 :            : 
     748                 :            : private:
     749                 :            :     /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
     750                 :            :      *  the descendants for a single transaction that has been added to the
     751                 :            :      *  mempool but may have child transactions in the mempool, eg during a
     752                 :            :      *  chain reorg.
     753                 :            :      *
     754                 :            :      * @pre CTxMemPoolEntry::m_children is correct for the given tx and all
     755                 :            :      *      descendants.
     756                 :            :      * @pre cachedDescendants is an accurate cache where each entry has all
     757                 :            :      *      descendants of the corresponding key, including those that should
     758                 :            :      *      be removed for violation of ancestor limits.
     759                 :            :      * @post if updateIt has any non-excluded descendants, cachedDescendants has
     760                 :            :      *       a new cache line for updateIt.
     761                 :            :      * @post descendants_to_remove has a new entry for any descendant which exceeded
     762                 :            :      *       ancestor limits relative to updateIt.
     763                 :            :      *
     764                 :            :      * @param[in] updateIt the entry to update for its descendants
     765                 :            :      * @param[in,out] cachedDescendants a cache where each line corresponds to all
     766                 :            :      *     descendants. It will be updated with the descendants of the transaction
     767                 :            :      *     being updated, so that future invocations don't need to walk the same
     768                 :            :      *     transaction again, if encountered in another transaction chain.
     769                 :            :      * @param[in] setExclude the set of descendant transactions in the mempool
     770                 :            :      *     that must not be accounted for (because any descendants in setExclude
     771                 :            :      *     were added to the mempool after the transaction being updated and hence
     772                 :            :      *     their state is already reflected in the parent state).
     773                 :            :      * @param[out] descendants_to_remove Populated with the txids of entries that
     774                 :            :      *     exceed ancestor limits. It's the responsibility of the caller to
     775                 :            :      *     removeRecursive them.
     776                 :            :      */
     777                 :            :     void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
     778                 :            :                               const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs);
     779                 :            :     /** Update ancestors of hash to add/remove it as a descendant transaction. */
     780                 :            :     void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
     781                 :            :     /** Set ancestor state for an entry */
     782                 :            :     void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
     783                 :            :     /** For each transaction being removed, update ancestors and any direct children.
     784                 :            :       * If updateDescendants is true, then also update in-mempool descendants'
     785                 :            :       * ancestor state. */
     786                 :            :     void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
     787                 :            :     /** Sever link between specified transaction and direct children. */
     788                 :            :     void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs);
     789                 :            : 
     790                 :            :     /** Before calling removeUnchecked for a given transaction,
     791                 :            :      *  UpdateForRemoveFromMempool must be called on the entire (dependent) set
     792                 :            :      *  of transactions being removed at the same time.  We use each
     793                 :            :      *  CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
     794                 :            :      *  given transaction that is removed, so we can't remove intermediate
     795                 :            :      *  transactions in a chain before we've updated all the state for the
     796                 :            :      *  removal.
     797                 :            :      */
     798                 :            :     void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
     799                 :            : public:
     800                 :            :     /** visited marks a CTxMemPoolEntry as having been traversed
     801                 :            :      * during the lifetime of the most recently created Epoch::Guard
     802                 :            :      * and returns false if we are the first visitor, true otherwise.
     803                 :            :      *
     804                 :            :      * An Epoch::Guard must be held when visited is called or an assert will be
     805                 :            :      * triggered.
     806                 :            :      *
     807                 :            :      */
     808                 :     842706 :     bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
     809                 :            :     {
     810                 :     842706 :         return m_epoch.visited(it->m_epoch_marker);
     811                 :            :     }
     812                 :            : 
     813                 :            :     bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
     814                 :            :     {
     815                 :            :         assert(m_epoch.guarded()); // verify guard even when it==nullopt
     816                 :            :         return !it || visited(*it);
     817                 :            :     }
     818                 :            : };
     819                 :            : 
     820                 :            : /**
     821                 :            :  * CCoinsView that brings transactions from a mempool into view.
     822                 :            :  * It does not check for spendings by memory pool transactions.
     823                 :            :  * Instead, it provides access to all Coins which are either unspent in the
     824                 :            :  * base CCoinsView, are outputs from any mempool transaction, or are
     825                 :            :  * tracked temporarily to allow transaction dependencies in package validation.
     826                 :            :  * This allows transaction replacement to work as expected, as you want to
     827                 :            :  * have all inputs "available" to check signatures, and any cycles in the
     828                 :            :  * dependency graph are checked directly in AcceptToMemoryPool.
     829                 :            :  * It also allows you to sign a double-spend directly in
     830                 :            :  * signrawtransactionwithkey and signrawtransactionwithwallet,
     831                 :            :  * as long as the conflicting transaction is not yet confirmed.
     832                 :            :  */
     833                 :            : class CCoinsViewMemPool : public CCoinsViewBacked
     834                 :            : {
     835                 :            :     /**
     836                 :            :     * Coins made available by transactions being validated. Tracking these allows for package
     837                 :            :     * validation, since we can access transaction outputs without submitting them to mempool.
     838                 :            :     */
     839                 :            :     std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
     840                 :            : 
     841                 :            :     /**
     842                 :            :      * Set of all coins that have been fetched from mempool or created using PackageAddTransaction
     843                 :            :      * (not base). Used to track the origin of a coin, see GetNonBaseCoins().
     844                 :            :      */
     845                 :            :     mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
     846                 :            : protected:
     847                 :            :     const CTxMemPool& mempool;
     848                 :            : 
     849                 :            : public:
     850                 :            :     CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
     851                 :            :     /** GetCoin, returning whether it exists and is not spent. Also updates m_non_base_coins if the
     852                 :            :      * coin is not fetched from base. */
     853                 :            :     bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
     854                 :            :     /** Add the coins created by this transaction. These coins are only temporarily stored in
     855                 :            :      * m_temp_added and cannot be flushed to the back end. Only used for package validation. */
     856                 :            :     void PackageAddTransaction(const CTransactionRef& tx);
     857                 :            :     /** Get all coins in m_non_base_coins. */
     858                 :      15966 :     std::unordered_set<COutPoint, SaltedOutpointHasher> GetNonBaseCoins() const { return m_non_base_coins; }
     859                 :            :     /** Clear m_temp_added and m_non_base_coins. */
     860                 :            :     void Reset();
     861                 :            : };
     862                 :            : #endif // BITCOIN_TXMEMPOOL_H

Generated by: LCOV version 1.16