LCOV - code coverage report
Current view: top level - src - txmempool.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 85 792 10.7 %
Date: 2023-10-05 12:38:51 Functions: 11 75 14.7 %
Branches: 48 1402 3.4 %

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

Generated by: LCOV version 1.14