LCOV - code coverage report
Current view: top level - src - txmempool.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 80.8 % 777 628
Test Date: 2024-08-28 04:44:32 Functions: 81.9 % 72 59
Branches: 48.6 % 998 485

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

Generated by: LCOV version 2.0-1