LCOV - code coverage report
Current view: top level - src - txmempool.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 109 876 12.4 %
Date: 2024-05-24 10:43:37 Functions: 16 76 21.1 %
Branches: 69 1626 4.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                 :            : #include <txmempool.h>
       7                 :            : 
       8                 :            : #include <chain.h>
       9                 :            : #include <coins.h>
      10                 :            : #include <common/system.h>
      11                 :            : #include <consensus/consensus.h>
      12                 :            : #include <consensus/tx_verify.h>
      13                 :            : #include <consensus/validation.h>
      14                 :            : #include <logging.h>
      15                 :            : #include <policy/policy.h>
      16                 :            : #include <policy/settings.h>
      17                 :            : #include <random.h>
      18                 :            : #include <reverse_iterator.h>
      19                 :            : #include <util/check.h>
      20                 :            : #include <util/feefrac.h>
      21                 :            : #include <util/moneystr.h>
      22                 :            : #include <util/overflow.h>
      23                 :            : #include <util/result.h>
      24                 :            : #include <util/time.h>
      25                 :            : #include <util/trace.h>
      26                 :            : #include <util/translation.h>
      27                 :            : #include <validationinterface.h>
      28                 :            : 
      29                 :            : #include <cmath>
      30                 :            : #include <numeric>
      31                 :            : #include <optional>
      32                 :            : #include <string_view>
      33                 :            : #include <utility>
      34                 :            : 
      35                 :          0 : bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
      36                 :            : {
      37                 :          0 :     AssertLockHeld(cs_main);
      38                 :            :     // If there are relative lock times then the maxInputBlock will be set
      39                 :            :     // If there are no relative lock times, the LockPoints don't depend on the chain
      40         [ #  # ]:          0 :     if (lp.maxInputBlock) {
      41                 :            :         // Check whether active_chain is an extension of the block at which the LockPoints
      42                 :            :         // calculation was valid.  If not LockPoints are no longer valid
      43         [ #  # ]:          0 :         if (!active_chain.Contains(lp.maxInputBlock)) {
      44                 :          0 :             return false;
      45                 :            :         }
      46                 :          0 :     }
      47                 :            : 
      48                 :            :     // LockPoints still valid
      49                 :          0 :     return true;
      50                 :          0 : }
      51                 :            : 
      52                 :          0 : void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
      53                 :            :                                       const std::set<uint256>& setExclude, std::set<uint256>& descendants_to_remove)
      54                 :            : {
      55                 :          0 :     CTxMemPoolEntry::Children stageEntries, descendants;
      56   [ #  #  #  #  :          0 :     stageEntries = updateIt->GetMemPoolChildrenConst();
                   #  # ]
      57                 :            : 
      58         [ #  # ]:          0 :     while (!stageEntries.empty()) {
      59                 :          0 :         const CTxMemPoolEntry& descendant = *stageEntries.begin();
      60         [ #  # ]:          0 :         descendants.insert(descendant);
      61         [ #  # ]:          0 :         stageEntries.erase(descendant);
      62         [ #  # ]:          0 :         const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
      63         [ #  # ]:          0 :         for (const CTxMemPoolEntry& childEntry : children) {
      64   [ #  #  #  # ]:          0 :             cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
      65         [ #  # ]:          0 :             if (cacheIt != cachedDescendants.end()) {
      66                 :            :                 // We've already calculated this one, just add the entries for this set
      67                 :            :                 // but don't traverse again.
      68         [ #  # ]:          0 :                 for (txiter cacheEntry : cacheIt->second) {
      69   [ #  #  #  # ]:          0 :                     descendants.insert(*cacheEntry);
      70                 :          0 :                 }
      71   [ #  #  #  # ]:          0 :             } else if (!descendants.count(childEntry)) {
      72                 :            :                 // Schedule for later processing
      73         [ #  # ]:          0 :                 stageEntries.insert(childEntry);
      74                 :          3 :             }
      75                 :          0 :         }
      76                 :          0 :     }
      77                 :            :     // descendants now contains all in-mempool descendants of updateIt.
      78                 :            :     // Update and add to cached descendant map
      79                 :          0 :     int32_t modifySize = 0;
      80                 :          0 :     CAmount modifyFee = 0;
      81                 :          0 :     int64_t modifyCount = 0;
      82         [ #  # ]:          0 :     for (const CTxMemPoolEntry& descendant : descendants) {
      83   [ #  #  #  #  :          0 :         if (!setExclude.count(descendant.GetTx().GetHash())) {
          #  #  #  #  #  
                      # ]
      84         [ #  # ]:          0 :             modifySize += descendant.GetTxSize();
      85         [ #  # ]:          0 :             modifyFee += descendant.GetModifiedFee();
      86                 :          0 :             modifyCount++;
      87   [ #  #  #  #  :          0 :             cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
                   #  # ]
      88                 :            :             // Update ancestor state for each descendant
      89   [ #  #  #  # ]:          0 :             mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
      90                 :          0 :               e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
      91                 :          0 :             });
      92                 :            :             // Don't directly remove the transaction here -- doing so would
      93                 :            :             // invalidate iterators in cachedDescendants. Mark it for removal
      94                 :            :             // by inserting into descendants_to_remove.
      95   [ #  #  #  #  :          0 :             if (descendant.GetCountWithAncestors() > uint64_t(m_opts.limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_opts.limits.ancestor_size_vbytes) {
             #  #  #  # ]
      96   [ #  #  #  #  :          0 :                 descendants_to_remove.insert(descendant.GetTx().GetHash());
             #  #  #  # ]
      97                 :          0 :             }
      98                 :          0 :         }
      99                 :          0 :     }
     100         [ #  # ]:          0 :     mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
     101                 :          0 : }
     102                 :            : 
     103                 :          0 : void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<uint256>& vHashesToUpdate)
     104                 :            : {
     105                 :          0 :     AssertLockHeld(cs);
     106                 :            :     // For each entry in vHashesToUpdate, store the set of in-mempool, but not
     107                 :            :     // in-vHashesToUpdate transactions, so that we don't have to recalculate
     108                 :            :     // descendants when we come across a previously seen entry.
     109                 :          0 :     cacheMap mapMemPoolDescendantsToUpdate;
     110                 :            : 
     111                 :            :     // Use a set for lookups into vHashesToUpdate (these entries are already
     112                 :            :     // accounted for in the state of their ancestors)
     113         [ #  # ]:          0 :     std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
     114                 :            : 
     115                 :          0 :     std::set<uint256> descendants_to_remove;
     116                 :            : 
     117                 :            :     // Iterate in reverse, so that whenever we are looking at a transaction
     118                 :            :     // we are sure that all in-mempool descendants have already been processed.
     119                 :            :     // This maximizes the benefit of the descendant cache and guarantees that
     120                 :            :     // CTxMemPoolEntry::m_children will be updated, an assumption made in
     121                 :            :     // UpdateForDescendants.
     122   [ #  #  #  #  :          0 :     for (const uint256 &hash : reverse_iterate(vHashesToUpdate)) {
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     123                 :            :         // calculate children from mapNextTx
     124         [ #  # ]:          0 :         txiter it = mapTx.find(hash);
     125   [ #  #  #  # ]:          0 :         if (it == mapTx.end()) {
     126                 :          0 :             continue;
     127                 :            :         }
     128   [ #  #  #  #  :          0 :         auto iter = mapNextTx.lower_bound(COutPoint(Txid::FromUint256(hash), 0));
                   #  # ]
     129                 :            :         // First calculate the children, and update CTxMemPoolEntry::m_children to
     130                 :            :         // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
     131                 :            :         // we cache the in-mempool children to avoid duplicate updates
     132                 :            :         {
     133         [ #  # ]:          0 :             WITH_FRESH_EPOCH(m_epoch);
     134   [ #  #  #  #  :          0 :             for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
             #  #  #  # ]
     135   [ #  #  #  # ]:          0 :                 const uint256 &childHash = iter->second->GetHash();
     136         [ #  # ]:          0 :                 txiter childIter = mapTx.find(childHash);
     137   [ #  #  #  # ]:          0 :                 assert(childIter != mapTx.end());
     138                 :            :                 // We can skip updating entries we've encountered before or that
     139                 :            :                 // are in the block (which are already accounted for).
     140   [ #  #  #  #  :          0 :                 if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
             #  #  #  # ]
     141         [ #  # ]:          0 :                     UpdateChild(it, childIter, true);
     142         [ #  # ]:          0 :                     UpdateParent(childIter, it, true);
     143                 :          0 :                 }
     144                 :          0 :             }
     145                 :          0 :         } // release epoch guard for UpdateForDescendants
     146         [ #  # ]:          0 :         UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
     147   [ #  #  #  #  :          0 :     }
                      # ]
     148                 :            : 
     149         [ #  # ]:          0 :     for (const auto& txid : descendants_to_remove) {
     150                 :            :         // This txid may have been removed already in a prior call to removeRecursive.
     151                 :            :         // Therefore we ensure it is not yet removed already.
     152   [ #  #  #  # ]:          0 :         if (const std::optional<txiter> txiter = GetIter(txid)) {
     153   [ #  #  #  #  :          0 :             removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
                   #  # ]
     154                 :          0 :         }
     155                 :          0 :     }
     156                 :          0 : }
     157                 :            : 
     158                 :          0 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateAncestorsAndCheckLimits(
     159                 :            :     int64_t entry_size,
     160                 :            :     size_t entry_count,
     161                 :            :     CTxMemPoolEntry::Parents& staged_ancestors,
     162                 :            :     const Limits& limits) const
     163                 :            : {
     164                 :          0 :     int64_t totalSizeWithAncestors = entry_size;
     165                 :          0 :     setEntries ancestors;
     166                 :            : 
     167         [ #  # ]:          0 :     while (!staged_ancestors.empty()) {
     168                 :          0 :         const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
     169         [ #  # ]:          0 :         txiter stageit = mapTx.iterator_to(stage);
     170                 :            : 
     171         [ #  # ]:          0 :         ancestors.insert(stageit);
     172         [ #  # ]:          0 :         staged_ancestors.erase(stage);
     173   [ #  #  #  # ]:          0 :         totalSizeWithAncestors += stageit->GetTxSize();
     174                 :            : 
     175   [ #  #  #  #  :          0 :         if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
                   #  # ]
     176   [ #  #  #  #  :          0 :             return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     177   [ #  #  #  #  :          0 :         } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
                   #  # ]
     178   [ #  #  #  #  :          0 :             return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     179         [ #  # ]:          0 :         } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
     180   [ #  #  #  #  :          0 :             return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
                   #  # ]
     181                 :            :         }
     182                 :            : 
     183   [ #  #  #  # ]:          0 :         const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
     184   [ #  #  #  # ]:          0 :         for (const CTxMemPoolEntry& parent : parents) {
     185         [ #  # ]:          0 :             txiter parent_it = mapTx.iterator_to(parent);
     186                 :            : 
     187                 :            :             // If this is a new ancestor, add it.
     188   [ #  #  #  # ]:          0 :             if (ancestors.count(parent_it) == 0) {
     189         [ #  # ]:          0 :                 staged_ancestors.insert(parent);
     190                 :          0 :             }
     191         [ #  # ]:          0 :             if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
     192   [ #  #  #  #  :          0 :                 return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
                   #  # ]
     193                 :            :             }
     194   [ #  #  #  # ]:          0 :         }
     195         [ #  # ]:          0 :     }
     196                 :            : 
     197         [ #  # ]:          0 :     return ancestors;
     198                 :          0 : }
     199                 :            : 
     200                 :          0 : util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
     201                 :            :                                                   const int64_t total_vsize) const
     202                 :            : {
     203                 :          0 :     size_t pack_count = package.size();
     204                 :            : 
     205                 :            :     // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
     206         [ #  # ]:          0 :     if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
     207   [ #  #  #  # ]:          0 :         return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
     208         [ #  # ]:          0 :     } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
     209   [ #  #  #  # ]:          0 :         return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
     210         [ #  # ]:          0 :     } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
     211   [ #  #  #  # ]:          0 :         return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
     212         [ #  # ]:          0 :     } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
     213   [ #  #  #  # ]:          0 :         return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_opts.limits.descendant_size_vbytes))};
     214                 :            :     }
     215                 :            : 
     216                 :          0 :     CTxMemPoolEntry::Parents staged_ancestors;
     217   [ #  #  #  # ]:          0 :     for (const auto& tx : package) {
     218   [ #  #  #  # ]:          0 :         for (const auto& input : tx->vin) {
     219   [ #  #  #  # ]:          0 :             std::optional<txiter> piter = GetIter(input.prevout.hash);
     220         [ #  # ]:          0 :             if (piter) {
     221   [ #  #  #  # ]:          0 :                 staged_ancestors.insert(**piter);
     222         [ #  # ]:          0 :                 if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
     223   [ #  #  #  #  :          0 :                     return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_opts.limits.ancestor_count))};
                   #  # ]
     224                 :            :                 }
     225                 :          0 :             }
     226   [ #  #  #  # ]:          0 :         }
     227         [ #  # ]:          0 :     }
     228                 :            :     // When multiple transactions are passed in, the ancestors and descendants of all transactions
     229                 :            :     // considered together must be within limits even if they are not interdependent. This may be
     230                 :            :     // stricter than the limits for each individual transaction.
     231   [ #  #  #  # ]:          0 :     const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
     232                 :          0 :                                                           staged_ancestors, m_opts.limits)};
     233                 :            :     // It's possible to overestimate the ancestor/descendant totals.
     234   [ #  #  #  #  :          0 :     if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
          #  #  #  #  #  
                      # ]
     235         [ #  # ]:          0 :     return {};
     236                 :          0 : }
     237                 :            : 
     238                 :          0 : util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
     239                 :            :     const CTxMemPoolEntry &entry,
     240                 :            :     const Limits& limits,
     241                 :            :     bool fSearchForParents /* = true */) const
     242                 :            : {
     243                 :          0 :     CTxMemPoolEntry::Parents staged_ancestors;
     244         [ #  # ]:          0 :     const CTransaction &tx = entry.GetTx();
     245                 :            : 
     246         [ #  # ]:          0 :     if (fSearchForParents) {
     247                 :            :         // Get parents of this transaction that are in the mempool
     248                 :            :         // GetMemPoolParents() is only valid for entries in the mempool, so we
     249                 :            :         // iterate mapTx to find parents.
     250   [ #  #  #  # ]:          0 :         for (unsigned int i = 0; i < tx.vin.size(); i++) {
     251   [ #  #  #  # ]:          0 :             std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
     252         [ #  # ]:          0 :             if (piter) {
     253   [ #  #  #  # ]:          0 :                 staged_ancestors.insert(**piter);
     254         [ #  # ]:          0 :                 if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
     255   [ #  #  #  #  :          0 :                     return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
                   #  # ]
     256                 :            :                 }
     257                 :          0 :             }
     258         [ #  # ]:          0 :         }
     259                 :          0 :     } else {
     260                 :            :         // If we're not searching for parents, we require this to already be an
     261                 :            :         // entry in the mempool and use the entry's cached parents.
     262         [ #  # ]:          0 :         txiter it = mapTx.iterator_to(entry);
     263   [ #  #  #  #  :          0 :         staged_ancestors = it->GetMemPoolParentsConst();
                   #  # ]
     264                 :          0 :     }
     265                 :            : 
     266   [ #  #  #  #  :          0 :     return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
                   #  # ]
     267                 :          0 :                                             limits);
     268                 :          0 : }
     269                 :            : 
     270                 :          0 : CTxMemPool::setEntries CTxMemPool::AssumeCalculateMemPoolAncestors(
     271                 :            :     std::string_view calling_fn_name,
     272                 :            :     const CTxMemPoolEntry &entry,
     273                 :            :     const Limits& limits,
     274                 :            :     bool fSearchForParents /* = true */) const
     275                 :            : {
     276                 :          0 :     auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
     277   [ #  #  #  # ]:          0 :     if (!Assume(result)) {
     278   [ #  #  #  #  :          0 :         LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
          #  #  #  #  #  
                #  #  # ]
     279                 :            :                       calling_fn_name, util::ErrorString(result).original);
     280                 :          0 :     }
     281         [ #  # ]:          0 :     return std::move(result).value_or(CTxMemPool::setEntries{});
     282                 :          0 : }
     283                 :            : 
     284                 :          0 : void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
     285                 :            : {
     286                 :          0 :     const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
     287                 :            :     // add or remove this tx as a child of each parent
     288         [ #  # ]:          0 :     for (const CTxMemPoolEntry& parent : parents) {
     289                 :          0 :         UpdateChild(mapTx.iterator_to(parent), it, add);
     290                 :          0 :     }
     291                 :          0 :     const int32_t updateCount = (add ? 1 : -1);
     292                 :          0 :     const int32_t updateSize{updateCount * it->GetTxSize()};
     293                 :          0 :     const CAmount updateFee = updateCount * it->GetModifiedFee();
     294         [ #  # ]:          0 :     for (txiter ancestorIt : setAncestors) {
     295                 :          0 :         mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
     296                 :          0 :     }
     297                 :          0 : }
     298                 :            : 
     299                 :          0 : void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
     300                 :            : {
     301                 :          0 :     int64_t updateCount = setAncestors.size();
     302                 :          0 :     int64_t updateSize = 0;
     303                 :          0 :     CAmount updateFee = 0;
     304                 :          2 :     int64_t updateSigOpsCost = 0;
     305         [ #  # ]:          0 :     for (txiter ancestorIt : setAncestors) {
     306                 :          2 :         updateSize += ancestorIt->GetTxSize();
     307                 :          2 :         updateFee += ancestorIt->GetModifiedFee();
     308                 :          2 :         updateSigOpsCost += ancestorIt->GetSigOpCost();
     309                 :          0 :     }
     310                 :          2 :     mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
     311                 :          2 : }
     312                 :          2 : 
     313                 :          2 : void CTxMemPool::UpdateChildrenForRemoval(txiter it)
     314                 :            : {
     315                 :          0 :     const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
     316         [ #  # ]:          0 :     for (const CTxMemPoolEntry& updateIt : children) {
     317                 :          0 :         UpdateParent(mapTx.iterator_to(updateIt), it, false);
     318                 :          2 :     }
     319                 :          0 : }
     320                 :            : 
     321                 :          0 : void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
     322                 :          2 : {
     323                 :            :     // For each entry, walk back all ancestors and decrement size associated with this
     324                 :            :     // transaction
     325         [ #  # ]:          0 :     if (updateDescendants) {
     326                 :            :         // updateDescendants should be true whenever we're not recursively
     327                 :            :         // removing a tx and all its descendants, eg when a transaction is
     328                 :            :         // confirmed in a block.
     329                 :            :         // Here we only update statistics and not data in CTxMemPool::Parents
     330                 :            :         // and CTxMemPoolEntry::Children (which we need to preserve until we're
     331                 :            :         // finished with all operations that need to traverse the mempool).
     332         [ #  # ]:          0 :         for (txiter removeIt : entriesToRemove) {
     333                 :          0 :             setEntries setDescendants;
     334         [ #  # ]:          0 :             CalculateDescendants(removeIt, setDescendants);
     335         [ #  # ]:          0 :             setDescendants.erase(removeIt); // don't update state for self
     336   [ #  #  #  # ]:          0 :             int32_t modifySize = -removeIt->GetTxSize();
     337   [ #  #  #  # ]:          0 :             CAmount modifyFee = -removeIt->GetModifiedFee();
     338   [ #  #  #  # ]:          0 :             int modifySigOps = -removeIt->GetSigOpCost();
     339         [ #  # ]:          0 :             for (txiter dit : setDescendants) {
     340         [ #  # ]:          0 :                 mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
     341                 :          0 :             }
     342                 :          0 :         }
     343                 :          0 :     }
     344         [ #  # ]:          0 :     for (txiter removeIt : entriesToRemove) {
     345                 :          0 :         const CTxMemPoolEntry &entry = *removeIt;
     346                 :            :         // Since this is a tx that is already in the mempool, we can call CMPA
     347                 :            :         // with fSearchForParents = false.  If the mempool is in a consistent
     348                 :            :         // state, then using true or false should both be correct, though false
     349                 :            :         // should be a bit faster.
     350                 :            :         // However, if we happen to be in the middle of processing a reorg, then
     351                 :            :         // the mempool can be in an inconsistent state.  In this case, the set
     352                 :            :         // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
     353                 :            :         // will be the same as the set of ancestors whose packages include this
     354                 :            :         // transaction, because when we add a new transaction to the mempool in
     355                 :            :         // addUnchecked(), we assume it has no children, and in the case of a
     356                 :            :         // reorg where that assumption is false, the in-mempool children aren't
     357                 :            :         // linked to the in-block tx's until UpdateTransactionsFromBlock() is
     358                 :            :         // called.
     359                 :            :         // So if we're being called during a reorg, ie before
     360                 :            :         // UpdateTransactionsFromBlock() has been called, then
     361                 :            :         // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
     362                 :            :         // mempool parents we'd calculate by searching, and it's important that
     363                 :            :         // we use the cached notion of ancestor transactions as the set of
     364                 :            :         // things to update for removal.
     365                 :          0 :         auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
     366                 :            :         // Note that UpdateAncestorsOf severs the child links that point to
     367                 :            :         // removeIt in the entries for the parents of removeIt.
     368         [ #  # ]:          0 :         UpdateAncestorsOf(false, removeIt, ancestors);
     369                 :          0 :     }
     370                 :            :     // After updating all the ancestor sizes, we can now sever the link between each
     371                 :            :     // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
     372                 :            :     // for each direct child of a transaction being removed).
     373         [ #  # ]:          0 :     for (txiter removeIt : entriesToRemove) {
     374                 :          0 :         UpdateChildrenForRemoval(removeIt);
     375                 :          0 :     }
     376                 :          0 : }
     377                 :            : 
     378                 :          0 : void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
     379                 :            : {
     380                 :          0 :     nSizeWithDescendants += modifySize;
     381         [ #  # ]:          0 :     assert(nSizeWithDescendants > 0);
     382                 :          0 :     nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
     383                 :          0 :     m_count_with_descendants += modifyCount;
     384         [ #  # ]:          0 :     assert(m_count_with_descendants > 0);
     385                 :          0 : }
     386                 :            : 
     387                 :          0 : void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
     388                 :            : {
     389                 :          0 :     nSizeWithAncestors += modifySize;
     390         [ #  # ]:          0 :     assert(nSizeWithAncestors > 0);
     391                 :          0 :     nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
     392                 :          0 :     m_count_with_ancestors += modifyCount;
     393         [ #  # ]:          0 :     assert(m_count_with_ancestors > 0);
     394                 :          0 :     nSigOpCostWithAncestors += modifySigOps;
     395         [ #  # ]:          0 :     assert(int(nSigOpCostWithAncestors) >= 0);
     396                 :          0 : }
     397                 :            : 
     398   [ +  -  +  - ]:          4 : CTxMemPool::CTxMemPool(const Options& opts)
     399                 :          2 :     : m_opts{opts}
     400                 :            : {
     401                 :          2 : }
     402                 :            : 
     403                 :          0 : bool CTxMemPool::isSpent(const COutPoint& outpoint) const
     404                 :            : {
     405                 :          0 :     LOCK(cs);
     406         [ #  # ]:          0 :     return mapNextTx.count(outpoint);
     407                 :          0 : }
     408                 :            : 
     409                 :          0 : unsigned int CTxMemPool::GetTransactionsUpdated() const
     410                 :            : {
     411                 :          0 :     return nTransactionsUpdated;
     412                 :            : }
     413                 :            : 
     414                 :        402 : void CTxMemPool::AddTransactionsUpdated(unsigned int n)
     415                 :            : {
     416                 :        402 :     nTransactionsUpdated += n;
     417                 :        402 : }
     418                 :            : 
     419                 :          0 : void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry, setEntries &setAncestors)
     420                 :            : {
     421                 :            :     // Add to memory pool without checking anything.
     422                 :            :     // Used by AcceptToMemoryPool(), which DOES do
     423                 :            :     // all the appropriate checks.
     424                 :          0 :     indexed_transaction_set::iterator newit = mapTx.emplace(CTxMemPoolEntry::ExplicitCopy, entry).first;
     425                 :            : 
     426                 :            :     // Update transaction for any feeDelta created by PrioritiseTransaction
     427                 :          0 :     CAmount delta{0};
     428                 :          0 :     ApplyDelta(entry.GetTx().GetHash(), delta);
     429                 :            :     // The following call to UpdateModifiedFee assumes no previous fee modifications
     430                 :          0 :     Assume(entry.GetFee() == entry.GetModifiedFee());
     431         [ #  # ]:          0 :     if (delta) {
     432                 :          0 :         mapTx.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
     433                 :          0 :     }
     434                 :            : 
     435                 :            :     // Update cachedInnerUsage to include contained transaction's usage.
     436                 :            :     // (When we update the entry for in-mempool parents, memory usage will be
     437                 :            :     // further updated.)
     438                 :          0 :     cachedInnerUsage += entry.DynamicMemoryUsage();
     439                 :            : 
     440                 :          0 :     const CTransaction& tx = newit->GetTx();
     441                 :          0 :     std::set<Txid> setParentTransactions;
     442         [ #  # ]:          0 :     for (unsigned int i = 0; i < tx.vin.size(); i++) {
     443   [ #  #  #  # ]:          0 :         mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
     444         [ #  # ]:          0 :         setParentTransactions.insert(tx.vin[i].prevout.hash);
     445                 :          0 :     }
     446                 :            :     // Don't bother worrying about child transactions of this one.
     447                 :            :     // Normal case of a new transaction arriving is that there can't be any
     448                 :            :     // children, because such children would be orphans.
     449                 :            :     // An exception to that is if a transaction enters that used to be in a block.
     450                 :            :     // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
     451                 :            :     // to clean up the mess we're leaving here.
     452                 :            : 
     453                 :            :     // Update ancestors with information about this tx
     454   [ #  #  #  # ]:          0 :     for (const auto& pit : GetIterSet(setParentTransactions)) {
     455         [ #  # ]:          0 :             UpdateParent(newit, pit, true);
     456                 :          0 :     }
     457         [ #  # ]:          0 :     UpdateAncestorsOf(true, newit, setAncestors);
     458         [ #  # ]:          0 :     UpdateEntryForAncestors(newit, setAncestors);
     459                 :            : 
     460                 :          0 :     nTransactionsUpdated++;
     461         [ #  # ]:          0 :     totalTxSize += entry.GetTxSize();
     462         [ #  # ]:          0 :     m_total_fee += entry.GetFee();
     463                 :            : 
     464   [ #  #  #  #  :          0 :     txns_randomized.emplace_back(newit->GetSharedTx());
                   #  # ]
     465         [ #  # ]:          0 :     newit->idx_randomized = txns_randomized.size() - 1;
     466                 :            : 
     467                 :            :     TRACE3(mempool, added,
     468                 :            :         entry.GetTx().GetHash().data(),
     469                 :            :         entry.GetTxSize(),
     470                 :            :         entry.GetFee()
     471                 :            :     );
     472                 :          0 : }
     473                 :            : 
     474                 :          0 : void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
     475                 :            : {
     476                 :            :     // We increment mempool sequence value no matter removal reason
     477                 :            :     // even if not directly reported below.
     478                 :          0 :     uint64_t mempool_sequence = GetAndIncrementSequence();
     479                 :            : 
     480   [ #  #  #  # ]:          0 :     if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
     481                 :            :         // Notify clients that a transaction has been removed from the mempool
     482                 :            :         // for any reason except being included in a block. Clients interested
     483                 :            :         // in transactions included in blocks can subscribe to the BlockConnected
     484                 :            :         // notification.
     485         [ #  # ]:          0 :         m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
     486                 :          0 :     }
     487                 :            :     TRACE5(mempool, removed,
     488                 :            :         it->GetTx().GetHash().data(),
     489                 :            :         RemovalReasonToString(reason).c_str(),
     490                 :            :         it->GetTxSize(),
     491                 :            :         it->GetFee(),
     492                 :            :         std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
     493                 :            :     );
     494                 :            : 
     495         [ #  # ]:          0 :     for (const CTxIn& txin : it->GetTx().vin)
     496                 :          0 :         mapNextTx.erase(txin.prevout);
     497                 :            : 
     498                 :          0 :     RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
     499                 :            : 
     500         [ #  # ]:          0 :     if (txns_randomized.size() > 1) {
     501                 :            :         // Update idx_randomized of the to-be-moved entry.
     502                 :          0 :         Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized;
     503                 :            :         // Remove entry from txns_randomized by replacing it with the back and deleting the back.
     504                 :          0 :         txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
     505                 :          0 :         txns_randomized.pop_back();
     506         [ #  # ]:          0 :         if (txns_randomized.size() * 2 < txns_randomized.capacity())
     507                 :          0 :             txns_randomized.shrink_to_fit();
     508                 :          0 :     } else
     509                 :          0 :         txns_randomized.clear();
     510                 :            : 
     511                 :          0 :     totalTxSize -= it->GetTxSize();
     512                 :          0 :     m_total_fee -= it->GetFee();
     513                 :          0 :     cachedInnerUsage -= it->DynamicMemoryUsage();
     514                 :          0 :     cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
     515                 :          0 :     mapTx.erase(it);
     516                 :          0 :     nTransactionsUpdated++;
     517                 :          0 : }
     518                 :            : 
     519                 :            : // Calculates descendants of entry that are not already in setDescendants, and adds to
     520                 :            : // setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
     521                 :            : // is correct for tx and all descendants.
     522                 :            : // Also assumes that if an entry is in setDescendants already, then all
     523                 :            : // in-mempool descendants of it are already in setDescendants as well, so that we
     524                 :            : // can save time by not iterating over those entries.
     525                 :          0 : void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
     526                 :            : {
     527                 :          0 :     setEntries stage;
     528   [ #  #  #  # ]:          0 :     if (setDescendants.count(entryit) == 0) {
     529         [ #  # ]:          0 :         stage.insert(entryit);
     530                 :          0 :     }
     531                 :            :     // Traverse down the children of entry, only adding children that are not
     532                 :            :     // accounted for in setDescendants already (because those children have either
     533                 :            :     // already been walked, or will be walked in this iteration).
     534         [ #  # ]:          0 :     while (!stage.empty()) {
     535                 :          0 :         txiter it = *stage.begin();
     536         [ #  # ]:          0 :         setDescendants.insert(it);
     537         [ #  # ]:          0 :         stage.erase(it);
     538                 :            : 
     539   [ #  #  #  # ]:          0 :         const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
     540         [ #  # ]:          0 :         for (const CTxMemPoolEntry& child : children) {
     541         [ #  # ]:          0 :             txiter childiter = mapTx.iterator_to(child);
     542   [ #  #  #  # ]:          0 :             if (!setDescendants.count(childiter)) {
     543         [ #  # ]:          0 :                 stage.insert(childiter);
     544                 :          0 :             }
     545                 :          0 :         }
     546                 :          0 :     }
     547                 :          0 : }
     548                 :            : 
     549                 :          0 : void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
     550                 :            : {
     551                 :            :     // Remove transaction from memory pool
     552                 :          0 :     AssertLockHeld(cs);
     553                 :          0 :         setEntries txToRemove;
     554   [ #  #  #  # ]:          0 :         txiter origit = mapTx.find(origTx.GetHash());
     555   [ #  #  #  # ]:          0 :         if (origit != mapTx.end()) {
     556         [ #  # ]:          0 :             txToRemove.insert(origit);
     557                 :          0 :         } else {
     558                 :            :             // When recursively removing but origTx isn't in the mempool
     559                 :            :             // be sure to remove any children that are in the pool. This can
     560                 :            :             // happen during chain re-orgs if origTx isn't re-accepted into
     561                 :            :             // the mempool for any reason.
     562         [ #  # ]:          0 :             for (unsigned int i = 0; i < origTx.vout.size(); i++) {
     563   [ #  #  #  #  :          0 :                 auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
                   #  # ]
     564   [ #  #  #  # ]:          0 :                 if (it == mapNextTx.end())
     565                 :          0 :                     continue;
     566   [ #  #  #  # ]:          0 :                 txiter nextit = mapTx.find(it->second->GetHash());
     567   [ #  #  #  # ]:          0 :                 assert(nextit != mapTx.end());
     568         [ #  # ]:          0 :                 txToRemove.insert(nextit);
     569      [ #  #  # ]:          0 :             }
     570                 :            :         }
     571                 :          0 :         setEntries setAllRemoves;
     572         [ #  # ]:          0 :         for (txiter it : txToRemove) {
     573         [ #  # ]:          0 :             CalculateDescendants(it, setAllRemoves);
     574                 :          0 :         }
     575                 :            : 
     576         [ #  # ]:          0 :         RemoveStaged(setAllRemoves, false, reason);
     577                 :          0 : }
     578                 :            : 
     579                 :          0 : void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
     580                 :            : {
     581                 :            :     // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
     582                 :          0 :     AssertLockHeld(cs);
     583                 :          0 :     AssertLockHeld(::cs_main);
     584                 :            : 
     585                 :          0 :     setEntries txToRemove;
     586   [ #  #  #  #  :          0 :     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
                   #  # ]
     587   [ #  #  #  #  :          0 :         if (check_final_and_mature(it)) txToRemove.insert(it);
                   #  # ]
     588                 :          0 :     }
     589                 :          0 :     setEntries setAllRemoves;
     590         [ #  # ]:          0 :     for (txiter it : txToRemove) {
     591         [ #  # ]:          0 :         CalculateDescendants(it, setAllRemoves);
     592                 :          0 :     }
     593         [ #  # ]:          0 :     RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
     594   [ #  #  #  #  :          0 :     for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
                   #  # ]
     595   [ #  #  #  #  :          0 :         assert(TestLockPointValidity(chain, it->GetLockPoints()));
             #  #  #  # ]
     596                 :          0 :     }
     597                 :          0 : }
     598                 :            : 
     599                 :        402 : void CTxMemPool::removeConflicts(const CTransaction &tx)
     600                 :            : {
     601                 :            :     // Remove transactions which depend on inputs of tx, recursively
     602                 :        402 :     AssertLockHeld(cs);
     603         [ +  + ]:        804 :     for (const CTxIn &txin : tx.vin) {
     604                 :        402 :         auto it = mapNextTx.find(txin.prevout);
     605         [ +  - ]:        402 :         if (it != mapNextTx.end()) {
     606                 :          0 :             const CTransaction &txConflict = *it->second;
     607         [ #  # ]:          0 :             if (txConflict != tx)
     608                 :            :             {
     609                 :          0 :                 ClearPrioritisation(txConflict.GetHash());
     610                 :          0 :                 removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
     611                 :          0 :             }
     612                 :          0 :         }
     613                 :        402 :     }
     614                 :        402 : }
     615                 :            : 
     616                 :            : /**
     617                 :            :  * Called when a block is connected. Removes from mempool.
     618                 :            :  */
     619                 :        402 : void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
     620                 :            : {
     621                 :        402 :     AssertLockHeld(cs);
     622                 :        402 :     std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
     623         [ +  - ]:        402 :     txs_removed_for_block.reserve(vtx.size());
     624         [ +  + ]:        804 :     for (const auto& tx : vtx)
     625                 :            :     {
     626   [ +  -  +  - ]:        402 :         txiter it = mapTx.find(tx->GetHash());
     627   [ +  -  +  - ]:        402 :         if (it != mapTx.end()) {
     628                 :          0 :             setEntries stage;
     629         [ #  # ]:          0 :             stage.insert(it);
     630   [ #  #  #  # ]:          0 :             txs_removed_for_block.emplace_back(*it);
     631         [ #  # ]:          0 :             RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
     632                 :          0 :         }
     633         [ +  - ]:        402 :         removeConflicts(*tx);
     634   [ +  -  +  -  :        402 :         ClearPrioritisation(tx->GetHash());
                   +  - ]
     635                 :        402 :     }
     636         [ +  - ]:        402 :     if (m_opts.signals) {
     637         [ +  - ]:        402 :         m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
     638                 :        402 :     }
     639         [ +  - ]:        402 :     lastRollingFeeUpdate = GetTime();
     640                 :        402 :     blockSinceLastRollingFeeBump = true;
     641                 :        402 : }
     642                 :            : 
     643                 :       3122 : void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
     644                 :            : {
     645         [ +  - ]:       3122 :     if (m_opts.check_ratio == 0) return;
     646                 :            : 
     647         [ -  + ]:       3122 :     if (GetRand(m_opts.check_ratio) >= 1) return;
     648                 :            : 
     649                 :       3122 :     AssertLockHeld(::cs_main);
     650                 :       3122 :     LOCK(cs);
     651   [ +  -  +  -  :       3122 :     LogPrint(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
          #  #  #  #  #  
                #  #  # ]
     652                 :            : 
     653                 :       3122 :     uint64_t checkTotal = 0;
     654                 :       3122 :     CAmount check_total_fee{0};
     655                 :       3122 :     uint64_t innerUsage = 0;
     656                 :       3122 :     uint64_t prev_ancestor_count{0};
     657                 :            : 
     658         [ +  - ]:       3122 :     CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
     659                 :            : 
     660   [ +  -  -  + ]:       3122 :     for (const auto& it : GetSortedDepthAndScore()) {
     661   [ #  #  #  # ]:          0 :         checkTotal += it->GetTxSize();
     662   [ #  #  #  # ]:          0 :         check_total_fee += it->GetFee();
     663   [ #  #  #  # ]:          0 :         innerUsage += it->DynamicMemoryUsage();
     664   [ #  #  #  # ]:          0 :         const CTransaction& tx = it->GetTx();
     665   [ #  #  #  #  :          0 :         innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
          #  #  #  #  #  
                #  #  # ]
     666                 :          0 :         CTxMemPoolEntry::Parents setParentCheck;
     667         [ #  # ]:          0 :         for (const CTxIn &txin : tx.vin) {
     668                 :            :             // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
     669         [ #  # ]:          0 :             indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
     670   [ #  #  #  # ]:          0 :             if (it2 != mapTx.end()) {
     671   [ #  #  #  # ]:          0 :                 const CTransaction& tx2 = it2->GetTx();
     672   [ #  #  #  #  :          0 :                 assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
                   #  # ]
     673   [ #  #  #  # ]:          0 :                 setParentCheck.insert(*it2);
     674                 :          0 :             }
     675                 :            :             // We are iterating through the mempool entries sorted in order by ancestor count.
     676                 :            :             // All parents must have been checked before their children and their coins added to
     677                 :            :             // the mempoolDuplicate coins cache.
     678   [ #  #  #  # ]:          0 :             assert(mempoolDuplicate.HaveCoin(txin.prevout));
     679                 :            :             // Check whether its inputs are marked in mapNextTx.
     680         [ #  # ]:          0 :             auto it3 = mapNextTx.find(txin.prevout);
     681   [ #  #  #  # ]:          0 :             assert(it3 != mapNextTx.end());
     682         [ #  # ]:          0 :             assert(it3->first == &txin.prevout);
     683         [ #  # ]:          0 :             assert(it3->second == &tx);
     684                 :          0 :         }
     685                 :          0 :         auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
     686                 :          0 :             return a.GetTx().GetHash() == b.GetTx().GetHash();
     687                 :            :         };
     688   [ #  #  #  #  :          0 :         assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
                   #  # ]
     689   [ #  #  #  #  :          0 :         assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
             #  #  #  # ]
     690                 :            :         // Verify ancestor state is correct.
     691   [ #  #  #  #  :          0 :         auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
                   #  # ]
     692                 :          0 :         uint64_t nCountCheck = ancestors.size() + 1;
     693   [ #  #  #  # ]:          0 :         int32_t nSizeCheck = it->GetTxSize();
     694   [ #  #  #  # ]:          0 :         CAmount nFeesCheck = it->GetModifiedFee();
     695   [ #  #  #  # ]:          0 :         int64_t nSigOpCheck = it->GetSigOpCost();
     696                 :            : 
     697         [ #  # ]:          0 :         for (txiter ancestorIt : ancestors) {
     698   [ #  #  #  # ]:          0 :             nSizeCheck += ancestorIt->GetTxSize();
     699   [ #  #  #  # ]:          0 :             nFeesCheck += ancestorIt->GetModifiedFee();
     700   [ #  #  #  # ]:          0 :             nSigOpCheck += ancestorIt->GetSigOpCost();
     701                 :          0 :         }
     702                 :            : 
     703   [ #  #  #  #  :          0 :         assert(it->GetCountWithAncestors() == nCountCheck);
                   #  # ]
     704   [ #  #  #  #  :          0 :         assert(it->GetSizeWithAncestors() == nSizeCheck);
                   #  # ]
     705   [ #  #  #  #  :          0 :         assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
                   #  # ]
     706   [ #  #  #  #  :          0 :         assert(it->GetModFeesWithAncestors() == nFeesCheck);
                   #  # ]
     707                 :            :         // Sanity check: we are walking in ascending ancestor count order.
     708   [ #  #  #  #  :          0 :         assert(prev_ancestor_count <= it->GetCountWithAncestors());
                   #  # ]
     709   [ #  #  #  # ]:          0 :         prev_ancestor_count = it->GetCountWithAncestors();
     710                 :            : 
     711                 :            :         // Check children against mapNextTx
     712                 :          0 :         CTxMemPoolEntry::Children setChildrenCheck;
     713   [ #  #  #  #  :          0 :         auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
          #  #  #  #  #  
                      # ]
     714                 :          0 :         int32_t child_sizes{0};
     715   [ #  #  #  #  :          0 :         for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     716   [ #  #  #  # ]:          0 :             txiter childit = mapTx.find(iter->second->GetHash());
     717   [ #  #  #  # ]:          0 :             assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
     718   [ #  #  #  #  :          0 :             if (setChildrenCheck.insert(*childit).second) {
                   #  # ]
     719   [ #  #  #  # ]:          0 :                 child_sizes += childit->GetTxSize();
     720                 :          0 :             }
     721                 :          0 :         }
     722   [ #  #  #  #  :          0 :         assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
                   #  # ]
     723   [ #  #  #  #  :          0 :         assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
             #  #  #  # ]
     724                 :            :         // Also check to make sure size is greater than sum with immediate children.
     725                 :            :         // just a sanity check, not definitive that this calc is correct...
     726   [ #  #  #  #  :          0 :         assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
          #  #  #  #  #  
                      # ]
     727                 :            : 
     728                 :          0 :         TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
     729                 :          0 :         CAmount txfee = 0;
     730   [ #  #  #  # ]:          0 :         assert(!tx.IsCoinBase());
     731   [ #  #  #  # ]:          0 :         assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
     732   [ #  #  #  # ]:          0 :         for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
     733         [ #  # ]:          0 :         AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
     734                 :          0 :     }
     735   [ +  -  +  -  :       3122 :     for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
                   -  + ]
     736   [ #  #  #  # ]:          0 :         uint256 hash = it->second->GetHash();
     737         [ #  # ]:          0 :         indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
     738   [ #  #  #  # ]:          0 :         const CTransaction& tx = it2->GetTx();
     739   [ #  #  #  # ]:          0 :         assert(it2 != mapTx.end());
     740         [ #  # ]:          0 :         assert(&tx == it->second);
     741                 :          0 :     }
     742                 :            : 
     743         [ +  - ]:       3122 :     assert(totalTxSize == checkTotal);
     744         [ +  - ]:       3122 :     assert(m_total_fee == check_total_fee);
     745         [ +  - ]:       3122 :     assert(innerUsage == cachedInnerUsage);
     746                 :       3122 : }
     747                 :            : 
     748                 :          0 : bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid)
     749                 :            : {
     750                 :            :     /* Return `true` if hasha should be considered sooner than hashb. Namely when:
     751                 :            :      *   a is not in the mempool, but b is
     752                 :            :      *   both are in the mempool and a has fewer ancestors than b
     753                 :            :      *   both are in the mempool and a has a higher score than b
     754                 :            :      */
     755                 :          0 :     LOCK(cs);
     756   [ #  #  #  #  :          0 :     indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb);
                   #  # ]
     757   [ #  #  #  # ]:          0 :     if (j == mapTx.end()) return false;
     758   [ #  #  #  #  :          0 :     indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha);
                   #  # ]
     759   [ #  #  #  # ]:          0 :     if (i == mapTx.end()) return true;
     760   [ #  #  #  # ]:          0 :     uint64_t counta = i->GetCountWithAncestors();
     761   [ #  #  #  # ]:          0 :     uint64_t countb = j->GetCountWithAncestors();
     762         [ #  # ]:          0 :     if (counta == countb) {
     763   [ #  #  #  #  :          0 :         return CompareTxMemPoolEntryByScore()(*i, *j);
                   #  # ]
     764                 :            :     }
     765                 :          0 :     return counta < countb;
     766                 :          0 : }
     767                 :            : 
     768                 :            : namespace {
     769                 :            : class DepthAndScoreComparator
     770                 :            : {
     771                 :            : public:
     772                 :          0 :     bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
     773                 :            :     {
     774                 :          0 :         uint64_t counta = a->GetCountWithAncestors();
     775                 :          0 :         uint64_t countb = b->GetCountWithAncestors();
     776         [ #  # ]:          0 :         if (counta == countb) {
     777                 :          0 :             return CompareTxMemPoolEntryByScore()(*a, *b);
     778                 :            :         }
     779                 :          0 :         return counta < countb;
     780                 :          0 :     }
     781                 :            : };
     782                 :            : } // namespace
     783                 :            : 
     784                 :       3178 : std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
     785                 :            : {
     786                 :       3178 :     std::vector<indexed_transaction_set::const_iterator> iters;
     787         [ +  - ]:       3178 :     AssertLockHeld(cs);
     788                 :            : 
     789         [ +  - ]:       3178 :     iters.reserve(mapTx.size());
     790                 :            : 
     791   [ +  -  -  +  :       3178 :     for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
                   #  # ]
     792         [ #  # ]:          0 :         iters.push_back(mi);
     793                 :          0 :     }
     794         [ +  - ]:       3178 :     std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
     795                 :       3178 :     return iters;
     796         [ +  - ]:       3178 : }
     797                 :            : 
     798                 :          0 : static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
     799   [ #  #  #  #  :          0 :     return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     800                 :          0 : }
     801                 :            : 
     802                 :          0 : std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
     803                 :            : {
     804                 :          0 :     AssertLockHeld(cs);
     805                 :            : 
     806                 :          0 :     std::vector<CTxMemPoolEntryRef> ret;
     807         [ #  # ]:          0 :     ret.reserve(mapTx.size());
     808   [ #  #  #  # ]:          0 :     for (const auto& it : GetSortedDepthAndScore()) {
     809   [ #  #  #  # ]:          0 :         ret.emplace_back(*it);
     810                 :          0 :     }
     811                 :          0 :     return ret;
     812         [ #  # ]:          0 : }
     813                 :            : 
     814                 :         56 : std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
     815                 :            : {
     816                 :         56 :     LOCK(cs);
     817         [ +  - ]:         56 :     auto iters = GetSortedDepthAndScore();
     818                 :            : 
     819                 :         56 :     std::vector<TxMempoolInfo> ret;
     820         [ -  + ]:         56 :     ret.reserve(mapTx.size());
     821         [ -  + ]:         56 :     for (auto it : iters) {
     822   [ #  #  #  # ]:          0 :         ret.push_back(GetInfo(it));
     823                 :          0 :     }
     824                 :            : 
     825                 :         56 :     return ret;
     826         [ +  - ]:         56 : }
     827                 :            : 
     828                 :          0 : const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
     829                 :            : {
     830                 :          0 :     AssertLockHeld(cs);
     831                 :          0 :     const auto i = mapTx.find(txid);
     832         [ #  # ]:          0 :     return i == mapTx.end() ? nullptr : &(*i);
     833                 :          0 : }
     834                 :            : 
     835                 :       2414 : CTransactionRef CTxMemPool::get(const uint256& hash) const
     836                 :            : {
     837                 :       2414 :     LOCK(cs);
     838         [ +  - ]:       2414 :     indexed_transaction_set::const_iterator i = mapTx.find(hash);
     839   [ +  -  -  + ]:       2414 :     if (i == mapTx.end())
     840                 :       2414 :         return nullptr;
     841   [ #  #  #  # ]:          0 :     return i->GetSharedTx();
     842                 :       2414 : }
     843                 :            : 
     844                 :          0 : TxMempoolInfo CTxMemPool::info(const GenTxid& gtxid) const
     845                 :            : {
     846                 :          0 :     LOCK(cs);
     847   [ #  #  #  #  :          0 :     indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
          #  #  #  #  #  
                #  #  # ]
     848   [ #  #  #  # ]:          0 :     if (i == mapTx.end())
     849                 :          0 :         return TxMempoolInfo();
     850         [ #  # ]:          0 :     return GetInfo(i);
     851                 :          0 : }
     852                 :            : 
     853                 :        528 : TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const
     854                 :            : {
     855                 :        528 :     LOCK(cs);
     856   [ +  -  +  +  :        528 :     indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
          +  -  +  -  +  
                -  +  - ]
     857   [ +  -  -  +  :        528 :     if (i != mapTx.end() && i->GetSequence() < last_sequence) {
          #  #  #  #  -  
                      + ]
     858         [ #  # ]:          0 :         return GetInfo(i);
     859                 :            :     } else {
     860                 :        528 :         return TxMempoolInfo();
     861                 :            :     }
     862                 :        528 : }
     863                 :            : 
     864                 :          0 : void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
     865                 :            : {
     866                 :            :     {
     867                 :          0 :         LOCK(cs);
     868         [ #  # ]:          0 :         CAmount &delta = mapDeltas[hash];
     869                 :          0 :         delta = SaturatingAdd(delta, nFeeDelta);
     870         [ #  # ]:          0 :         txiter it = mapTx.find(hash);
     871   [ #  #  #  # ]:          0 :         if (it != mapTx.end()) {
     872         [ #  # ]:          0 :             mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
     873                 :            :             // Now update all ancestors' modified fees with descendants
     874   [ #  #  #  #  :          0 :             auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
                   #  # ]
     875         [ #  # ]:          0 :             for (txiter ancestorIt : ancestors) {
     876         [ #  # ]:          0 :                 mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
     877                 :          0 :             }
     878                 :            :             // Now update all descendants' modified fees with ancestors
     879                 :          0 :             setEntries setDescendants;
     880         [ #  # ]:          0 :             CalculateDescendants(it, setDescendants);
     881         [ #  # ]:          0 :             setDescendants.erase(it);
     882         [ #  # ]:          0 :             for (txiter descendantIt : setDescendants) {
     883         [ #  # ]:          0 :                 mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
     884                 :          0 :             }
     885                 :          0 :             ++nTransactionsUpdated;
     886                 :          0 :         }
     887         [ #  # ]:          0 :         if (delta == 0) {
     888         [ #  # ]:          0 :             mapDeltas.erase(hash);
     889   [ #  #  #  #  :          0 :             LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
          #  #  #  #  #  
                      # ]
     890                 :          0 :         } else {
     891   [ #  #  #  #  :          0 :             LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
          #  #  #  #  #  
             #  #  #  #  
                      # ]
     892                 :            :                       hash.ToString(),
     893                 :            :                       it == mapTx.end() ? "not " : "",
     894                 :            :                       FormatMoney(nFeeDelta),
     895                 :            :                       FormatMoney(delta));
     896                 :            :         }
     897                 :          0 :     }
     898                 :          0 : }
     899                 :            : 
     900                 :          0 : void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
     901                 :            : {
     902                 :          0 :     AssertLockHeld(cs);
     903                 :          0 :     std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
     904         [ #  # ]:          0 :     if (pos == mapDeltas.end())
     905                 :          0 :         return;
     906                 :          0 :     const CAmount &delta = pos->second;
     907                 :          0 :     nFeeDelta += delta;
     908         [ #  # ]:          0 : }
     909                 :            : 
     910                 :        402 : void CTxMemPool::ClearPrioritisation(const uint256& hash)
     911                 :            : {
     912                 :        402 :     AssertLockHeld(cs);
     913                 :        402 :     mapDeltas.erase(hash);
     914                 :        402 : }
     915                 :            : 
     916                 :          0 : std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
     917                 :            : {
     918                 :          0 :     AssertLockNotHeld(cs);
     919                 :          0 :     LOCK(cs);
     920                 :          0 :     std::vector<delta_info> result;
     921         [ #  # ]:          0 :     result.reserve(mapDeltas.size());
     922         [ #  # ]:          0 :     for (const auto& [txid, delta] : mapDeltas) {
     923   [ #  #  #  # ]:          0 :         const auto iter{mapTx.find(txid)};
     924         [ #  # ]:          0 :         const bool in_mempool{iter != mapTx.end()};
     925                 :          0 :         std::optional<CAmount> modified_fee;
     926   [ #  #  #  #  :          0 :         if (in_mempool) modified_fee = iter->GetModifiedFee();
                   #  # ]
     927   [ #  #  #  #  :          0 :         result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
                   #  # ]
     928                 :          0 :     }
     929                 :          0 :     return result;
     930         [ #  # ]:          0 : }
     931                 :            : 
     932                 :      13385 : const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
     933                 :            : {
     934                 :      13385 :     const auto it = mapNextTx.find(prevout);
     935         [ +  - ]:      13385 :     return it == mapNextTx.end() ? nullptr : it->second;
     936                 :      13385 : }
     937                 :            : 
     938                 :          0 : std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const
     939                 :            : {
     940                 :          0 :     auto it = mapTx.find(txid);
     941         [ #  # ]:          0 :     if (it != mapTx.end()) return it;
     942                 :          0 :     return std::nullopt;
     943                 :          0 : }
     944                 :            : 
     945                 :          0 : CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
     946                 :            : {
     947                 :          0 :     CTxMemPool::setEntries ret;
     948         [ #  # ]:          0 :     for (const auto& h : hashes) {
     949   [ #  #  #  # ]:          0 :         const auto mi = GetIter(h);
     950   [ #  #  #  # ]:          0 :         if (mi) ret.insert(*mi);
     951                 :          0 :     }
     952                 :          0 :     return ret;
     953         [ #  # ]:          0 : }
     954                 :            : 
     955                 :          0 : std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
     956                 :            : {
     957                 :          0 :     AssertLockHeld(cs);
     958                 :          0 :     std::vector<txiter> ret;
     959         [ #  # ]:          0 :     ret.reserve(txids.size());
     960   [ #  #  #  # ]:          0 :     for (const auto& txid : txids) {
     961         [ #  # ]:          0 :         const auto it{GetIter(txid)};
     962         [ #  # ]:          0 :         if (!it) return {};
     963         [ #  # ]:          0 :         ret.push_back(*it);
     964   [ #  #  #  # ]:          0 :     }
     965                 :          0 :     return ret;
     966                 :          0 : }
     967                 :            : 
     968                 :          0 : bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
     969                 :            : {
     970   [ #  #  #  #  :          0 :     for (unsigned int i = 0; i < tx.vin.size(); i++)
                      # ]
     971         [ #  # ]:          0 :         if (exists(GenTxid::Txid(tx.vin[i].prevout.hash)))
     972                 :          0 :             return false;
     973                 :          0 :     return true;
     974                 :          0 : }
     975                 :            : 
     976   [ +  -  -  + ]:       2720 : CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
     977                 :            : 
     978                 :       2414 : bool CCoinsViewMemPool::GetCoin(const COutPoint &outpoint, Coin &coin) const {
     979                 :            :     // Check to see if the inputs are made available by another tx in the package.
     980                 :            :     // These Coins would not be available in the underlying CoinsView.
     981   [ -  +  -  -  :       2414 :     if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
                      + ]
     982                 :          0 :         coin = it->second;
     983                 :          0 :         return true;
     984                 :            :     }
     985                 :            : 
     986                 :            :     // If an entry in the mempool exists, always return that one, as it's guaranteed to never
     987                 :            :     // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
     988                 :            :     // transactions. First checking the underlying cache risks returning a pruned entry instead.
     989                 :       2414 :     CTransactionRef ptx = mempool.get(outpoint.hash);
     990         [ -  + ]:       2414 :     if (ptx) {
     991         [ #  # ]:          0 :         if (outpoint.n < ptx->vout.size()) {
     992         [ #  # ]:          0 :             coin = Coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
     993         [ #  # ]:          0 :             m_non_base_coins.emplace(outpoint);
     994                 :          0 :             return true;
     995                 :            :         } else {
     996                 :          0 :             return false;
     997                 :            :         }
     998                 :            :     }
     999         [ +  - ]:       2414 :     return base->GetCoin(outpoint, coin);
    1000                 :       2414 : }
    1001                 :            : 
    1002                 :          0 : void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
    1003                 :            : {
    1004         [ #  # ]:          0 :     for (unsigned int n = 0; n < tx->vout.size(); ++n) {
    1005         [ #  # ]:          0 :         m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
    1006                 :          0 :         m_non_base_coins.emplace(tx->GetHash(), n);
    1007                 :          0 :     }
    1008                 :          0 : }
    1009                 :          0 : void CCoinsViewMemPool::Reset()
    1010                 :            : {
    1011                 :          0 :     m_temp_added.clear();
    1012                 :          0 :     m_non_base_coins.clear();
    1013                 :          0 : }
    1014                 :            : 
    1015                 :       3926 : size_t CTxMemPool::DynamicMemoryUsage() const {
    1016                 :       3926 :     LOCK(cs);
    1017                 :            :     // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
    1018   [ +  -  +  -  :       3926 :     return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
             +  -  +  - ]
    1019                 :       3926 : }
    1020                 :            : 
    1021                 :          0 : void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
    1022                 :          0 :     LOCK(cs);
    1023                 :            : 
    1024   [ #  #  #  # ]:          0 :     if (m_unbroadcast_txids.erase(txid))
    1025                 :            :     {
    1026   [ #  #  #  #  :          0 :         LogPrint(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
          #  #  #  #  #  
                #  #  # ]
    1027                 :          0 :     }
    1028                 :          0 : }
    1029                 :            : 
    1030                 :          0 : void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
    1031                 :          0 :     AssertLockHeld(cs);
    1032                 :          0 :     UpdateForRemoveFromMempool(stage, updateDescendants);
    1033         [ #  # ]:          0 :     for (txiter it : stage) {
    1034                 :          0 :         removeUnchecked(it, reason);
    1035                 :          0 :     }
    1036                 :          0 : }
    1037                 :            : 
    1038                 :          0 : int CTxMemPool::Expire(std::chrono::seconds time)
    1039                 :            : {
    1040                 :          0 :     AssertLockHeld(cs);
    1041                 :          0 :     indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
    1042                 :          0 :     setEntries toremove;
    1043   [ #  #  #  #  :          0 :     while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
          #  #  #  #  #  
                #  #  # ]
    1044   [ #  #  #  # ]:          0 :         toremove.insert(mapTx.project<0>(it));
    1045         [ #  # ]:          0 :         it++;
    1046                 :            :     }
    1047                 :          0 :     setEntries stage;
    1048         [ #  # ]:          0 :     for (txiter removeit : toremove) {
    1049         [ #  # ]:          0 :         CalculateDescendants(removeit, stage);
    1050                 :          0 :     }
    1051         [ #  # ]:          0 :     RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
    1052                 :          0 :     return stage.size();
    1053                 :          0 : }
    1054                 :            : 
    1055                 :          0 : void CTxMemPool::addUnchecked(const CTxMemPoolEntry &entry)
    1056                 :            : {
    1057                 :          0 :     auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits())};
    1058         [ #  # ]:          0 :     return addUnchecked(entry, ancestors);
    1059                 :          0 : }
    1060                 :            : 
    1061                 :          0 : void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
    1062                 :            : {
    1063                 :          0 :     AssertLockHeld(cs);
    1064                 :          0 :     CTxMemPoolEntry::Children s;
    1065   [ #  #  #  #  :          0 :     if (add && entry->GetMemPoolChildren().insert(*child).second) {
          #  #  #  #  #  
                #  #  # ]
    1066         [ #  # ]:          0 :         cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
    1067   [ #  #  #  #  :          0 :     } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
          #  #  #  #  #  
                #  #  # ]
    1068         [ #  # ]:          0 :         cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
    1069                 :          0 :     }
    1070                 :          0 : }
    1071                 :            : 
    1072                 :          0 : void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
    1073                 :            : {
    1074                 :          0 :     AssertLockHeld(cs);
    1075                 :          0 :     CTxMemPoolEntry::Parents s;
    1076   [ #  #  #  #  :          0 :     if (add && entry->GetMemPoolParents().insert(*parent).second) {
          #  #  #  #  #  
                #  #  # ]
    1077         [ #  # ]:          0 :         cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
    1078   [ #  #  #  #  :          0 :     } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
          #  #  #  #  #  
                #  #  # ]
    1079         [ #  # ]:          0 :         cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
    1080                 :          0 :     }
    1081                 :          0 : }
    1082                 :            : 
    1083                 :      38899 : CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
    1084                 :      38899 :     LOCK(cs);
    1085   [ +  -  +  - ]:      38899 :     if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
    1086         [ +  - ]:      38899 :         return CFeeRate(llround(rollingMinimumFeeRate));
    1087                 :            : 
    1088         [ #  # ]:          0 :     int64_t time = GetTime();
    1089         [ #  # ]:          0 :     if (time > lastRollingFeeUpdate + 10) {
    1090                 :          0 :         double halflife = ROLLING_FEE_HALFLIFE;
    1091   [ #  #  #  # ]:          0 :         if (DynamicMemoryUsage() < sizelimit / 4)
    1092                 :          0 :             halflife /= 4;
    1093   [ #  #  #  # ]:          0 :         else if (DynamicMemoryUsage() < sizelimit / 2)
    1094                 :          0 :             halflife /= 2;
    1095                 :            : 
    1096                 :          0 :         rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
    1097                 :          0 :         lastRollingFeeUpdate = time;
    1098                 :            : 
    1099   [ #  #  #  # ]:          0 :         if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
    1100                 :          0 :             rollingMinimumFeeRate = 0;
    1101         [ #  # ]:          0 :             return CFeeRate(0);
    1102                 :            :         }
    1103         [ #  # ]:          0 :     }
    1104   [ #  #  #  # ]:          0 :     return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
    1105                 :      38899 : }
    1106                 :            : 
    1107                 :          0 : void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
    1108                 :          0 :     AssertLockHeld(cs);
    1109         [ #  # ]:          0 :     if (rate.GetFeePerK() > rollingMinimumFeeRate) {
    1110                 :          0 :         rollingMinimumFeeRate = rate.GetFeePerK();
    1111                 :          0 :         blockSinceLastRollingFeeBump = false;
    1112                 :          0 :     }
    1113                 :          0 : }
    1114                 :            : 
    1115                 :          0 : void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
    1116                 :          0 :     AssertLockHeld(cs);
    1117                 :            : 
    1118                 :          0 :     unsigned nTxnRemoved = 0;
    1119                 :          0 :     CFeeRate maxFeeRateRemoved(0);
    1120   [ #  #  #  # ]:          0 :     while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
    1121                 :          0 :         indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
    1122                 :            : 
    1123                 :            :         // We set the new mempool min fee to the feerate of the removed set, plus the
    1124                 :            :         // "minimum reasonable fee rate" (ie some value under which we consider txn
    1125                 :            :         // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
    1126                 :            :         // equal to txn which were removed with no block in between.
    1127                 :          0 :         CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
    1128                 :          0 :         removed += m_opts.incremental_relay_feerate;
    1129                 :          0 :         trackPackageRemoved(removed);
    1130                 :          0 :         maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
    1131                 :            : 
    1132                 :          0 :         setEntries stage;
    1133   [ #  #  #  # ]:          0 :         CalculateDescendants(mapTx.project<0>(it), stage);
    1134                 :          0 :         nTxnRemoved += stage.size();
    1135                 :            : 
    1136                 :          0 :         std::vector<CTransaction> txn;
    1137         [ #  # ]:          0 :         if (pvNoSpendsRemaining) {
    1138         [ #  # ]:          0 :             txn.reserve(stage.size());
    1139         [ #  # ]:          0 :             for (txiter iter : stage)
    1140   [ #  #  #  #  :          0 :                 txn.push_back(iter->GetTx());
                   #  # ]
    1141                 :          0 :         }
    1142         [ #  # ]:          0 :         RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
    1143         [ #  # ]:          0 :         if (pvNoSpendsRemaining) {
    1144         [ #  # ]:          0 :             for (const CTransaction& tx : txn) {
    1145         [ #  # ]:          0 :                 for (const CTxIn& txin : tx.vin) {
    1146   [ #  #  #  #  :          0 :                     if (exists(GenTxid::Txid(txin.prevout.hash))) continue;
             #  #  #  # ]
    1147         [ #  # ]:          0 :                     pvNoSpendsRemaining->push_back(txin.prevout);
    1148      [ #  #  # ]:          0 :                 }
    1149                 :          0 :             }
    1150                 :          0 :         }
    1151                 :          0 :     }
    1152                 :            : 
    1153         [ #  # ]:          0 :     if (maxFeeRateRemoved > CFeeRate(0)) {
    1154   [ #  #  #  #  :          0 :         LogPrint(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
          #  #  #  #  #  
                      # ]
    1155                 :          0 :     }
    1156                 :          0 : }
    1157                 :            : 
    1158                 :          0 : uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
    1159                 :            :     // find parent with highest descendant count
    1160                 :          0 :     std::vector<txiter> candidates;
    1161                 :          0 :     setEntries counted;
    1162         [ #  # ]:          0 :     candidates.push_back(entry);
    1163                 :          0 :     uint64_t maximum = 0;
    1164         [ #  # ]:          0 :     while (candidates.size()) {
    1165                 :          0 :         txiter candidate = candidates.back();
    1166                 :          0 :         candidates.pop_back();
    1167   [ #  #  #  # ]:          0 :         if (!counted.insert(candidate).second) continue;
    1168   [ #  #  #  # ]:          0 :         const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
    1169         [ #  # ]:          0 :         if (parents.size() == 0) {
    1170   [ #  #  #  #  :          0 :             maximum = std::max(maximum, candidate->GetCountWithDescendants());
                   #  # ]
    1171                 :          0 :         } else {
    1172         [ #  # ]:          0 :             for (const CTxMemPoolEntry& i : parents) {
    1173   [ #  #  #  # ]:          0 :                 candidates.push_back(mapTx.iterator_to(i));
    1174                 :          0 :             }
    1175                 :            :         }
    1176      [ #  #  # ]:          0 :     }
    1177                 :          0 :     return maximum;
    1178                 :          0 : }
    1179                 :            : 
    1180                 :          0 : void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
    1181                 :          0 :     LOCK(cs);
    1182         [ #  # ]:          0 :     auto it = mapTx.find(txid);
    1183                 :          0 :     ancestors = descendants = 0;
    1184   [ #  #  #  # ]:          0 :     if (it != mapTx.end()) {
    1185   [ #  #  #  # ]:          0 :         ancestors = it->GetCountWithAncestors();
    1186   [ #  #  #  #  :          0 :         if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
                   #  # ]
    1187   [ #  #  #  #  :          0 :         if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
                   #  # ]
    1188         [ #  # ]:          0 :         descendants = CalculateDescendantMaximum(it);
    1189                 :          0 :     }
    1190                 :          0 : }
    1191                 :            : 
    1192                 :          0 : bool CTxMemPool::GetLoadTried() const
    1193                 :            : {
    1194                 :          0 :     LOCK(cs);
    1195                 :          0 :     return m_load_tried;
    1196                 :          0 : }
    1197                 :            : 
    1198                 :          0 : void CTxMemPool::SetLoadTried(bool load_tried)
    1199                 :            : {
    1200                 :          0 :     LOCK(cs);
    1201                 :          0 :     m_load_tried = load_tried;
    1202                 :          0 : }
    1203                 :            : 
    1204                 :          0 : std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
    1205                 :            : {
    1206                 :          0 :     AssertLockHeld(cs);
    1207                 :          0 :     std::vector<txiter> clustered_txs{GetIterVec(txids)};
    1208                 :            :     // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
    1209                 :            :     // necessarily mean the entry has been processed.
    1210         [ #  # ]:          0 :     WITH_FRESH_EPOCH(m_epoch);
    1211         [ #  # ]:          0 :     for (const auto& it : clustered_txs) {
    1212         [ #  # ]:          0 :         visited(it);
    1213                 :          0 :     }
    1214                 :            :     // i = index of where the list of entries to process starts
    1215   [ #  #  #  # ]:          0 :     for (size_t i{0}; i < clustered_txs.size(); ++i) {
    1216                 :            :         // DoS protection: if there are 500 or more entries to process, just quit.
    1217         [ #  # ]:          0 :         if (clustered_txs.size() > 500) return {};
    1218         [ #  # ]:          0 :         const txiter& tx_iter = clustered_txs.at(i);
    1219   [ #  #  #  #  :          0 :         for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
          #  #  #  #  #  
             #  #  #  #  
                      # ]
    1220         [ #  # ]:          0 :             for (const CTxMemPoolEntry& entry : entries) {
    1221         [ #  # ]:          0 :                 const auto entry_it = mapTx.iterator_to(entry);
    1222   [ #  #  #  # ]:          0 :                 if (!visited(entry_it)) {
    1223         [ #  # ]:          0 :                     clustered_txs.push_back(entry_it);
    1224                 :          0 :                 }
    1225                 :          0 :             }
    1226                 :          0 :         }
    1227                 :          0 :     }
    1228                 :          0 :     return clustered_txs;
    1229                 :          0 : }
    1230                 :            : 
    1231                 :          0 : std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
    1232                 :            : {
    1233   [ #  #  #  #  :          0 :     for (const auto& direct_conflict : direct_conflicts) {
                      # ]
    1234                 :            :         // Ancestor and descendant counts are inclusive of the tx itself.
    1235                 :          0 :         const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
    1236                 :          0 :         const auto descendant_count{direct_conflict->GetCountWithDescendants()};
    1237                 :          0 :         const bool has_ancestor{ancestor_count > 1};
    1238                 :          0 :         const bool has_descendant{descendant_count > 1};
    1239   [ #  #  #  # ]:          0 :         const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
    1240                 :            :         // The only allowed configurations are:
    1241                 :            :         // 1 ancestor and 0 descendant
    1242                 :            :         // 0 ancestor and 1 descendant
    1243                 :            :         // 0 ancestor and 0 descendant
    1244         [ #  # ]:          0 :         if (ancestor_count > 2) {
    1245         [ #  # ]:          0 :             return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
    1246         [ #  # ]:          0 :         } else if (descendant_count > 2) {
    1247         [ #  # ]:          0 :             return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
    1248   [ #  #  #  # ]:          0 :         } else if (has_ancestor && has_descendant) {
    1249         [ #  # ]:          0 :             return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
    1250                 :            :         }
    1251                 :            :         // Additionally enforce that:
    1252                 :            :         // If we have a child,  we are its only parent.
    1253                 :            :         // If we have a parent, we are its only child.
    1254         [ #  # ]:          0 :         if (has_descendant) {
    1255   [ #  #  #  # ]:          0 :             const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
    1256   [ #  #  #  # ]:          0 :             if (our_child->get().GetCountWithAncestors() > 2) {
    1257         [ #  # ]:          0 :                 return strprintf("%s is not the only parent of child %s",
    1258   [ #  #  #  #  :          0 :                                  txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
                   #  # ]
    1259                 :            :             }
    1260   [ #  #  #  # ]:          0 :         } else if (has_ancestor) {
    1261   [ #  #  #  # ]:          0 :             const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
    1262   [ #  #  #  # ]:          0 :             if (our_parent->get().GetCountWithDescendants() > 2) {
    1263         [ #  # ]:          0 :                 return strprintf("%s is not the only child of parent %s",
    1264   [ #  #  #  #  :          0 :                                  txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
                   #  # ]
    1265                 :            :             }
    1266         [ #  # ]:          0 :         }
    1267   [ #  #  #  # ]:          0 :     }
    1268                 :          0 :     return std::nullopt;
    1269                 :          0 : }
    1270                 :            : 
    1271                 :          0 : util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::CalculateChunksForRBF(CAmount replacement_fees, int64_t replacement_vsize, const setEntries& direct_conflicts, const setEntries& all_conflicts)
    1272                 :            : {
    1273                 :          0 :     Assume(replacement_vsize > 0);
    1274                 :            : 
    1275                 :          0 :     auto err_string{CheckConflictTopology(direct_conflicts)};
    1276         [ #  # ]:          0 :     if (err_string.has_value()) {
    1277                 :            :         // Unsupported topology for calculating a feerate diagram
    1278   [ #  #  #  #  :          0 :         return util::Error{Untranslated(err_string.value())};
             #  #  #  # ]
    1279                 :            :     }
    1280                 :            : 
    1281                 :            :     // new diagram will have chunks that consist of each ancestor of
    1282                 :            :     // direct_conflicts that is at its own fee/size, along with the replacement
    1283                 :            :     // tx/package at its own fee/size
    1284                 :            : 
    1285                 :            :     // old diagram will consist of the ancestors and descendants of each element of
    1286                 :            :     // all_conflicts.  every such transaction will either be at its own feerate (followed
    1287                 :            :     // by any descendant at its own feerate), or as a single chunk at the descendant's
    1288                 :            :     // ancestor feerate.
    1289                 :            : 
    1290                 :          0 :     std::vector<FeeFrac> old_chunks;
    1291                 :            :     // Step 1: build the old diagram.
    1292                 :            : 
    1293                 :            :     // The above clusters are all trivially linearized;
    1294                 :            :     // they have a strict topology of 1 or two connected transactions.
    1295                 :            : 
    1296                 :            :     // OLD: Compute existing chunks from all affected clusters
    1297         [ #  # ]:          0 :     for (auto txiter : all_conflicts) {
    1298                 :            :         // Does this transaction have descendants?
    1299   [ #  #  #  #  :          0 :         if (txiter->GetCountWithDescendants() > 1) {
                   #  # ]
    1300                 :            :             // Consider this tx when we consider the descendant.
    1301                 :          0 :             continue;
    1302                 :            :         }
    1303                 :            :         // Does this transaction have ancestors?
    1304   [ #  #  #  #  :          0 :         FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
             #  #  #  # ]
    1305   [ #  #  #  #  :          0 :         if (txiter->GetCountWithAncestors() > 1) {
                   #  # ]
    1306                 :            :             // We'll add chunks for either the ancestor by itself and this tx
    1307                 :            :             // by itself, or for a combined package.
    1308   [ #  #  #  #  :          0 :             FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
             #  #  #  # ]
    1309         [ #  # ]:          0 :             if (individual >> package) {
    1310                 :            :                 // The individual feerate is higher than the package, and
    1311                 :            :                 // therefore higher than the parent's fee. Chunk these
    1312                 :            :                 // together.
    1313         [ #  # ]:          0 :                 old_chunks.emplace_back(package);
    1314                 :          0 :             } else {
    1315                 :            :                 // Add two points, one for the parent and one for this child.
    1316         [ #  # ]:          0 :                 old_chunks.emplace_back(package - individual);
    1317         [ #  # ]:          0 :                 old_chunks.emplace_back(individual);
    1318                 :            :             }
    1319                 :          0 :         } else {
    1320         [ #  # ]:          0 :             old_chunks.emplace_back(individual);
    1321                 :            :         }
    1322      [ #  #  # ]:          0 :     }
    1323                 :            : 
    1324                 :            :     // No topology restrictions post-chunking; sort
    1325         [ #  # ]:          0 :     std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
    1326                 :            : 
    1327                 :          0 :     std::vector<FeeFrac> new_chunks;
    1328                 :            : 
    1329                 :            :     /* Step 2: build the NEW diagram
    1330                 :            :      * CON = Conflicts of proposed chunk
    1331                 :            :      * CNK = Proposed chunk
    1332                 :            :      * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
    1333                 :            :      * the conflicts, plus the proposed chunk
    1334                 :            :      */
    1335                 :            : 
    1336                 :            :     // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
    1337         [ #  # ]:          0 :     for (auto direct_conflict : direct_conflicts) {
    1338                 :            :         // If a direct conflict has an ancestor that is not in all_conflicts,
    1339                 :            :         // it can be affected by the replacement of the child.
    1340   [ #  #  #  #  :          0 :         if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
                   #  # ]
    1341                 :            :             // Grab the parent.
    1342   [ #  #  #  # ]:          0 :             const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
    1343   [ #  #  #  #  :          0 :             if (!all_conflicts.count(mapTx.iterator_to(parent))) {
                   #  # ]
    1344                 :            :                 // This transaction would be left over, so add to the NEW
    1345                 :            :                 // diagram.
    1346   [ #  #  #  #  :          0 :                 new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
                   #  # ]
    1347                 :          0 :             }
    1348                 :          0 :         }
    1349                 :          0 :     }
    1350                 :            :     // + CNK: Add the proposed chunk itself
    1351         [ #  # ]:          0 :     new_chunks.emplace_back(replacement_fees, int32_t(replacement_vsize));
    1352                 :            : 
    1353                 :            :     // No topology restrictions post-chunking; sort
    1354         [ #  # ]:          0 :     std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
    1355   [ #  #  #  # ]:          0 :     return std::make_pair(old_chunks, new_chunks);
    1356                 :          0 : }

Generated by: LCOV version 1.16