LCOV - code coverage report
Current view: top level - src - txmempool.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 0 789 0.0 %
Date: 2024-01-03 14:57:27 Functions: 0 74 0.0 %
Branches: 0 1432 0.0 %

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

Generated by: LCOV version 1.14