LCOV - code coverage report
Current view: top level - src - txmempool.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 0.0 % 112 0
Test Date: 2024-11-22 13:43:01 Functions: 0.0 % 18 0
Branches: 0.0 % 136 0

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

Generated by: LCOV version 2.0-1