LCOV - code coverage report
Current view: top level - src/node - mini_miner.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 83.6 % 213 178
Test Date: 2024-12-04 04:00:22 Functions: 81.8 % 11 9
Branches: 56.9 % 288 164

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2023 The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <node/mini_miner.h>
       6                 :             : 
       7                 :             : #include <boost/multi_index/detail/hash_index_iterator.hpp>
       8                 :             : #include <boost/operators.hpp>
       9                 :             : #include <consensus/amount.h>
      10                 :             : #include <policy/feerate.h>
      11                 :             : #include <primitives/transaction.h>
      12                 :             : #include <sync.h>
      13                 :             : #include <txmempool.h>
      14                 :             : #include <uint256.h>
      15                 :             : #include <util/check.h>
      16                 :             : 
      17                 :             : #include <algorithm>
      18                 :             : #include <numeric>
      19                 :             : #include <utility>
      20                 :             : 
      21                 :             : namespace node {
      22                 :             : 
      23         [ +  - ]:      202668 : MiniMiner::MiniMiner(const CTxMemPool& mempool, const std::vector<COutPoint>& outpoints)
      24                 :             : {
      25         [ +  - ]:      202668 :     LOCK(mempool.cs);
      26                 :             :     // Find which outpoints to calculate bump fees for.
      27                 :             :     // Anything that's spent by the mempool is to-be-replaced
      28                 :             :     // Anything otherwise unavailable just has a bump fee of 0
      29         [ +  + ]:     1881148 :     for (const auto& outpoint : outpoints) {
      30   [ +  -  +  + ]:     1678480 :         if (!mempool.exists(GenTxid::Txid(outpoint.hash))) {
      31                 :             :             // This UTXO is either confirmed or not yet submitted to mempool.
      32                 :             :             // If it's confirmed, no bump fee is required.
      33                 :             :             // If it's not yet submitted, we have no information, so return 0.
      34         [ +  - ]:     1476656 :             m_bump_fees.emplace(outpoint, 0);
      35                 :     1476656 :             continue;
      36                 :             :         }
      37                 :             : 
      38                 :             :         // UXTO is created by transaction in mempool, add to map.
      39                 :             :         // Note: This will either create a missing entry or add the outpoint to an existing entry
      40   [ +  -  +  - ]:      201824 :         m_requested_outpoints_by_txid[outpoint.hash].push_back(outpoint);
      41                 :             : 
      42   [ +  -  +  + ]:      201824 :         if (const auto ptx{mempool.GetConflictTx(outpoint)}) {
      43                 :             :             // This outpoint is already being spent by another transaction in the mempool. We
      44                 :             :             // assume that the caller wants to replace this transaction and its descendants. It
      45                 :             :             // would be unusual for the transaction to have descendants as the wallet won’t normally
      46                 :             :             // attempt to replace transactions with descendants. If the outpoint is from a mempool
      47                 :             :             // transaction, we still need to calculate its ancestors bump fees (added to
      48                 :             :             // m_requested_outpoints_by_txid below), but after removing the to-be-replaced entries.
      49                 :             :             //
      50                 :             :             // Note that the descendants of a transaction include the transaction itself. Also note,
      51                 :             :             // that this is only calculating bump fees. RBF fee rules should be handled separately.
      52         [ +  - ]:       23890 :             CTxMemPool::setEntries descendants;
      53   [ +  -  +  - ]:       47780 :             mempool.CalculateDescendants(mempool.GetIter(ptx->GetHash()).value(), descendants);
      54         [ +  + ]:     2350054 :             for (const auto& desc_txiter : descendants) {
      55         [ +  - ]:     2326164 :                 m_to_be_replaced.insert(desc_txiter->GetTx().GetHash());
      56                 :             :             }
      57                 :       23890 :         }
      58                 :             :     }
      59                 :             : 
      60                 :             :     // No unconfirmed UTXOs, so nothing mempool-related needs to be calculated.
      61         [ +  + ]:      202668 :     if (m_requested_outpoints_by_txid.empty()) return;
      62                 :             : 
      63                 :             :     // Calculate the cluster and construct the entry map.
      64                 :        1953 :     std::vector<uint256> txids_needed;
      65         [ +  - ]:        1953 :     txids_needed.reserve(m_requested_outpoints_by_txid.size());
      66   [ +  -  +  + ]:      169375 :     for (const auto& [txid, _]: m_requested_outpoints_by_txid) {
      67         [ +  - ]:      167422 :         txids_needed.push_back(txid);
      68                 :             :     }
      69         [ +  - ]:        1953 :     const auto cluster = mempool.GatherClusters(txids_needed);
      70         [ -  + ]:        1953 :     if (cluster.empty()) {
      71                 :             :         // An empty cluster means that at least one of the transactions is missing from the mempool
      72                 :             :         // (should not be possible given processing above) or DoS limit was hit.
      73                 :           0 :         m_ready_to_calculate = false;
      74                 :           0 :         return;
      75                 :             :     }
      76                 :             : 
      77                 :             :     // Add every entry to m_entries_by_txid and m_entries, except the ones that will be replaced.
      78         [ +  + ]:      250217 :     for (const auto& txiter : cluster) {
      79         [ +  + ]:      248264 :         if (!m_to_be_replaced.count(txiter->GetTx().GetHash())) {
      80   [ +  -  +  -  :      352192 :             auto [mapiter, success] = m_entries_by_txid.emplace(txiter->GetTx().GetHash(),
                   +  - ]
      81   [ +  -  +  -  :      704384 :                 MiniMinerMempoolEntry{/*tx_in=*/txiter->GetSharedTx(),
             +  -  +  - ]
      82         [ +  - ]:      176096 :                                       /*vsize_self=*/txiter->GetTxSize(),
      83                 :             :                                       /*vsize_ancestor=*/txiter->GetSizeWithAncestors(),
      84                 :             :                                       /*fee_self=*/txiter->GetModifiedFee(),
      85   [ +  -  +  - ]:      352192 :                                       /*fee_ancestor=*/txiter->GetModFeesWithAncestors()});
      86         [ +  - ]:      176096 :             m_entries.push_back(mapiter);
      87                 :             :         } else {
      88                 :       72168 :             auto outpoints_it = m_requested_outpoints_by_txid.find(txiter->GetTx().GetHash());
      89         [ +  + ]:       72168 :             if (outpoints_it != m_requested_outpoints_by_txid.end()) {
      90                 :             :                 // This UTXO is the output of a to-be-replaced transaction. Bump fee is 0; spending
      91                 :             :                 // this UTXO is impossible as it will no longer exist after the replacement.
      92         [ +  + ]:       83446 :                 for (const auto& outpoint : outpoints_it->second) {
      93         [ +  - ]:       41738 :                     m_bump_fees.emplace(outpoint, 0);
      94                 :             :                 }
      95                 :       41708 :                 m_requested_outpoints_by_txid.erase(outpoints_it);
      96                 :             :             }
      97                 :             :         }
      98                 :             :     }
      99                 :             : 
     100                 :             :     // Build the m_descendant_set_by_txid cache.
     101         [ +  + ]:      250217 :     for (const auto& txiter : cluster) {
     102                 :      248264 :         const auto& txid = txiter->GetTx().GetHash();
     103                 :             :         // Cache descendants for future use. Unlike the real mempool, a descendant MiniMinerMempoolEntry
     104                 :             :         // will not exist without its ancestor MiniMinerMempoolEntry, so these sets won't be invalidated.
     105                 :      248264 :         std::vector<MockEntryMap::iterator> cached_descendants;
     106                 :      248264 :         const bool remove{m_to_be_replaced.count(txid) > 0};
     107         [ +  - ]:      248264 :         CTxMemPool::setEntries descendants;
     108         [ +  - ]:      248264 :         mempool.CalculateDescendants(txiter, descendants);
     109         [ +  - ]:      248264 :         Assume(descendants.count(txiter) > 0);
     110         [ +  + ]:    24325250 :         for (const auto& desc_txiter : descendants) {
     111                 :    24076986 :             const auto txid_desc = desc_txiter->GetTx().GetHash();
     112                 :    24076986 :             const bool remove_desc{m_to_be_replaced.count(txid_desc) > 0};
     113                 :    24076986 :             auto desc_it{m_entries_by_txid.find(txid_desc)};
     114         [ +  - ]:    24076986 :             Assume((desc_it == m_entries_by_txid.end()) == remove_desc);
     115   [ +  +  +  - ]:    24076986 :             if (remove) Assume(remove_desc);
     116                 :             :             // It's possible that remove=false but remove_desc=true.
     117         [ +  + ]:    15953258 :             if (!remove && !remove_desc) {
     118         [ +  - ]:    12457330 :                 cached_descendants.push_back(desc_it);
     119                 :             :             }
     120                 :             :         }
     121         [ +  + ]:      248264 :         if (remove) {
     122         [ +  - ]:       72168 :             Assume(cached_descendants.empty());
     123                 :             :         } else {
     124         [ +  - ]:      176096 :             m_descendant_set_by_txid.emplace(txid, cached_descendants);
     125                 :             :         }
     126                 :      248264 :     }
     127                 :             : 
     128                 :             :     // Release the mempool lock; we now have all the information we need for a subset of the entries
     129                 :             :     // we care about. We will solely operate on the MiniMinerMempoolEntry map from now on.
     130         [ +  - ]:        1953 :     Assume(m_in_block.empty());
     131         [ +  - ]:        1953 :     Assume(m_requested_outpoints_by_txid.size() <= outpoints.size());
     132         [ +  - ]:        1953 :     SanityCheck();
     133         [ +  - ]:      204621 : }
     134                 :             : 
     135                 :           0 : MiniMiner::MiniMiner(const std::vector<MiniMinerMempoolEntry>& manual_entries,
     136                 :           0 :                      const std::map<Txid, std::set<Txid>>& descendant_caches)
     137                 :             : {
     138         [ #  # ]:           0 :     for (const auto& entry : manual_entries) {
     139                 :           0 :         const auto& txid = entry.GetTx().GetHash();
     140                 :             :         // We need to know the descendant set of every transaction.
     141   [ #  #  #  # ]:           0 :         if (!Assume(descendant_caches.count(txid) > 0)) {
     142                 :           0 :             m_ready_to_calculate = false;
     143                 :           0 :             return;
     144                 :             :         }
     145                 :             :         // Just forward these args onto MiniMinerMempoolEntry
     146   [ #  #  #  # ]:           0 :         auto [mapiter, success] = m_entries_by_txid.emplace(txid, entry);
     147                 :             :         // Txids must be unique; this txid shouldn't already be an entry in m_entries_by_txid
     148   [ #  #  #  #  :           0 :         if (Assume(success)) m_entries.push_back(mapiter);
                   #  # ]
     149                 :             :     }
     150                 :             :     // Descendant cache is already built, but we need to translate them to m_entries_by_txid iters.
     151   [ #  #  #  # ]:           0 :     for (const auto& [txid, desc_txids] : descendant_caches) {
     152                 :             :         // Descendant cache should include at least the tx itself.
     153   [ #  #  #  # ]:           0 :         if (!Assume(!desc_txids.empty())) {
     154                 :           0 :             m_ready_to_calculate = false;
     155                 :           0 :             return;
     156                 :             :         }
     157                 :           0 :         std::vector<MockEntryMap::iterator> descendants;
     158         [ #  # ]:           0 :         for (const auto& desc_txid : desc_txids) {
     159                 :           0 :             auto desc_it{m_entries_by_txid.find(desc_txid)};
     160                 :             :             // Descendants should only include transactions with corresponding entries.
     161   [ #  #  #  # ]:           0 :             if (!Assume(desc_it != m_entries_by_txid.end())) {
     162                 :           0 :                 m_ready_to_calculate = false;
     163                 :           0 :                 return;
     164                 :             :             } else {
     165         [ #  # ]:           0 :                 descendants.emplace_back(desc_it);
     166                 :             :             }
     167                 :             :         }
     168         [ #  # ]:           0 :         m_descendant_set_by_txid.emplace(txid, descendants);
     169                 :           0 :     }
     170         [ #  # ]:           0 :     Assume(m_to_be_replaced.empty());
     171         [ #  # ]:           0 :     Assume(m_requested_outpoints_by_txid.empty());
     172         [ #  # ]:           0 :     Assume(m_bump_fees.empty());
     173         [ #  # ]:           0 :     Assume(m_inclusion_order.empty());
     174         [ #  # ]:           0 :     SanityCheck();
     175                 :           0 : }
     176                 :             : 
     177                 :             : // Compare by min(ancestor feerate, individual feerate), then txid
     178                 :             : //
     179                 :             : // Under the ancestor-based mining approach, high-feerate children can pay for parents, but high-feerate
     180                 :             : // parents do not incentive inclusion of their children. Therefore the mining algorithm only considers
     181                 :             : // transactions for inclusion on basis of the minimum of their own feerate or their ancestor feerate.
     182                 :             : struct AncestorFeerateComparator
     183                 :             : {
     184                 :             :     template<typename I>
     185         [ +  + ]:    66621898 :     bool operator()(const I& a, const I& b) const {
     186                 :   133243796 :         auto min_feerate = [](const MiniMinerMempoolEntry& e) -> FeeFrac {
     187                 :   133243796 :             FeeFrac self_feerate(e.GetModifiedFee(), e.GetTxSize());
     188                 :   133243796 :             FeeFrac ancestor_feerate(e.GetModFeesWithAncestors(), e.GetSizeWithAncestors());
     189                 :   133243796 :             return std::min(ancestor_feerate, self_feerate);
     190                 :             :         };
     191                 :    66621898 :         FeeFrac a_feerate{min_feerate(a->second)};
     192         [ +  + ]:    66621898 :         FeeFrac b_feerate{min_feerate(b->second)};
     193                 :    43934676 :         if (a_feerate != b_feerate) {
     194                 :    22687222 :             return a_feerate > b_feerate;
     195                 :             :         }
     196                 :             :         // Use txid as tiebreaker for stable sorting
     197                 :    43934676 :         return a->first < b->first;
     198                 :             :     }
     199                 :             : };
     200                 :             : 
     201                 :       69715 : void MiniMiner::DeleteAncestorPackage(const std::set<MockEntryMap::iterator, IteratorComparator>& ancestors)
     202                 :             : {
     203                 :       69715 :     Assume(ancestors.size() >= 1);
     204                 :             :     // "Mine" all transactions in this ancestor set.
     205         [ +  + ]:      217939 :     for (auto& anc : ancestors) {
     206                 :      148224 :         Assume(m_in_block.count(anc->first) == 0);
     207                 :      148224 :         m_in_block.insert(anc->first);
     208                 :      148224 :         m_total_fees += anc->second.GetModifiedFee();
     209                 :      148224 :         m_total_vsize += anc->second.GetTxSize();
     210                 :      148224 :         auto it = m_descendant_set_by_txid.find(anc->first);
     211                 :             :         // Each entry’s descendant set includes itself
     212                 :      148224 :         Assume(it != m_descendant_set_by_txid.end());
     213         [ +  + ]:     9344571 :         for (auto& descendant : it->second) {
     214                 :             :             // If these fail, we must be double-deducting.
     215                 :     9196347 :             Assume(descendant->second.GetModFeesWithAncestors() >= anc->second.GetModifiedFee());
     216                 :     9196347 :             Assume(descendant->second.GetSizeWithAncestors() >= anc->second.GetTxSize());
     217                 :     9196347 :             descendant->second.UpdateAncestorState(-anc->second.GetTxSize(), -anc->second.GetModifiedFee());
     218                 :             :         }
     219                 :             :     }
     220                 :             :     // Delete these entries.
     221         [ +  + ]:      217939 :     for (const auto& anc : ancestors) {
     222                 :      148224 :         m_descendant_set_by_txid.erase(anc->first);
     223                 :             :         // The above loop should have deducted each ancestor's size and fees from each of their
     224                 :             :         // respective descendants exactly once.
     225                 :      148224 :         Assume(anc->second.GetModFeesWithAncestors() == 0);
     226                 :      148224 :         Assume(anc->second.GetSizeWithAncestors() == 0);
     227                 :      148224 :         auto vec_it = std::find(m_entries.begin(), m_entries.end(), anc);
     228                 :      148224 :         Assume(vec_it != m_entries.end());
     229                 :      148224 :         m_entries.erase(vec_it);
     230                 :      148224 :         m_entries_by_txid.erase(anc);
     231                 :             :     }
     232                 :       69715 : }
     233                 :             : 
     234                 :       71668 : void MiniMiner::SanityCheck() const
     235                 :             : {
     236                 :             :     // m_entries, m_entries_by_txid, and m_descendant_set_by_txid all same size
     237                 :       71668 :     Assume(m_entries.size() == m_entries_by_txid.size());
     238                 :       71668 :     Assume(m_entries.size() == m_descendant_set_by_txid.size());
     239                 :             :     // Cached ancestor values should be at least as large as the transaction's own fee and size
     240   [ +  -  +  -  :     2320036 :     Assume(std::all_of(m_entries.begin(), m_entries.end(), [](const auto& entry) {
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
     241                 :             :         return entry->second.GetSizeWithAncestors() >= entry->second.GetTxSize() &&
     242                 :             :                entry->second.GetModFeesWithAncestors() >= entry->second.GetModifiedFee();}));
     243                 :             :     // None of the entries should be to-be-replaced transactions
     244                 :     2519784 :     Assume(std::all_of(m_to_be_replaced.begin(), m_to_be_replaced.end(),
     245                 :             :         [&](const auto& txid){return m_entries_by_txid.find(txid) == m_entries_by_txid.end();}));
     246                 :       71668 : }
     247                 :             : 
     248                 :      202668 : void MiniMiner::BuildMockTemplate(std::optional<CFeeRate> target_feerate)
     249                 :             : {
     250                 :      202668 :     const auto num_txns{m_entries_by_txid.size()};
     251                 :      202668 :     uint32_t sequence_num{0};
     252         [ +  + ]:      272383 :     while (!m_entries_by_txid.empty()) {
     253                 :             :         // Sort again, since transaction removal may change some m_entries' ancestor feerates.
     254                 :       70245 :         std::sort(m_entries.begin(), m_entries.end(), AncestorFeerateComparator());
     255                 :             : 
     256                 :             :         // Pick highest ancestor feerate entry.
     257                 :       70245 :         auto best_iter = m_entries.begin();
     258                 :       70245 :         Assume(best_iter != m_entries.end());
     259         [ +  - ]:       70245 :         const auto ancestor_package_size = (*best_iter)->second.GetSizeWithAncestors();
     260         [ +  - ]:       70245 :         const auto ancestor_package_fee = (*best_iter)->second.GetModFeesWithAncestors();
     261                 :             :         // Stop here. Everything that didn't "make it into the block" has bumpfee.
     262   [ +  -  +  + ]:      140490 :         if (target_feerate.has_value() &&
     263                 :       70245 :             ancestor_package_fee < target_feerate->GetFee(ancestor_package_size)) {
     264                 :             :             break;
     265                 :             :         }
     266                 :             : 
     267                 :             :         // Calculate ancestors on the fly. This lookup should be fairly cheap, and ancestor sets
     268                 :             :         // change at every iteration, so this is more efficient than maintaining a cache.
     269         [ +  - ]:       69715 :         std::set<MockEntryMap::iterator, IteratorComparator> ancestors;
     270                 :       69715 :         {
     271                 :       69715 :             std::set<MockEntryMap::iterator, IteratorComparator> to_process;
     272         [ +  - ]:       69715 :             to_process.insert(*best_iter);
     273         [ +  + ]:      217939 :             while (!to_process.empty()) {
     274         [ +  - ]:      148224 :                 auto iter = to_process.begin();
     275         [ +  - ]:      148224 :                 Assume(iter != to_process.end());
     276         [ +  - ]:      148224 :                 ancestors.insert(*iter);
     277         [ +  + ]:      817609 :                 for (const auto& input : (*iter)->second.GetTx().vin) {
     278         [ +  + ]:      669385 :                     if (auto parent_it{m_entries_by_txid.find(input.prevout.hash)}; parent_it != m_entries_by_txid.end()) {
     279         [ +  + ]:      464792 :                         if (ancestors.count(parent_it) == 0) {
     280         [ +  - ]:      371752 :                             to_process.insert(parent_it);
     281                 :             :                         }
     282                 :             :                     }
     283                 :             :                 }
     284                 :      148224 :                 to_process.erase(iter);
     285                 :             :             }
     286                 :           0 :         }
     287                 :             :         // Track the order in which transactions were selected.
     288         [ +  + ]:      217939 :         for (const auto& ancestor : ancestors) {
     289         [ +  - ]:      148224 :             m_inclusion_order.emplace(Txid::FromUint256(ancestor->first), sequence_num);
     290                 :             :         }
     291         [ +  - ]:       69715 :         DeleteAncestorPackage(ancestors);
     292         [ +  - ]:       69715 :         SanityCheck();
     293                 :       69715 :         ++sequence_num;
     294                 :       69715 :     }
     295         [ -  + ]:      202668 :     if (!target_feerate.has_value()) {
     296                 :           0 :         Assume(m_in_block.size() == num_txns);
     297                 :             :     } else {
     298   [ +  +  +  - ]:      204320 :         Assume(m_in_block.empty() || m_total_fees >= target_feerate->GetFee(m_total_vsize));
     299                 :             :     }
     300   [ +  +  -  + ]:      202668 :     Assume(m_in_block.empty() || sequence_num > 0);
     301                 :      202668 :     Assume(m_in_block.size() == m_inclusion_order.size());
     302                 :             :     // Do not try to continue building the block template with a different feerate.
     303                 :      202668 :     m_ready_to_calculate = false;
     304                 :      202668 : }
     305                 :             : 
     306                 :             : 
     307                 :           0 : std::map<Txid, uint32_t> MiniMiner::Linearize()
     308                 :             : {
     309                 :           0 :     BuildMockTemplate(std::nullopt);
     310                 :           0 :     return m_inclusion_order;
     311                 :             : }
     312                 :             : 
     313                 :       68489 : std::map<COutPoint, CAmount> MiniMiner::CalculateBumpFees(const CFeeRate& target_feerate)
     314                 :             : {
     315         [ -  + ]:       68489 :     if (!m_ready_to_calculate) return {};
     316                 :             :     // Build a block template until the target feerate is hit.
     317                 :       68489 :     BuildMockTemplate(target_feerate);
     318                 :             : 
     319                 :             :     // Each transaction that "made it into the block" has a bumpfee of 0, i.e. they are part of an
     320                 :             :     // ancestor package with at least the target feerate and don't need to be bumped.
     321         [ +  + ]:      124619 :     for (const auto& txid : m_in_block) {
     322                 :             :         // Not all of the block transactions were necessarily requested.
     323                 :       56130 :         auto it = m_requested_outpoints_by_txid.find(txid);
     324         [ +  + ]:       56130 :         if (it != m_requested_outpoints_by_txid.end()) {
     325         [ +  + ]:       70223 :             for (const auto& outpoint : it->second) {
     326                 :       35151 :                 m_bump_fees.emplace(outpoint, 0);
     327                 :             :             }
     328                 :       35072 :             m_requested_outpoints_by_txid.erase(it);
     329                 :             :         }
     330                 :             :     }
     331                 :             : 
     332                 :             :     // A transactions and its ancestors will only be picked into a block when
     333                 :             :     // both the ancestor set feerate and the individual feerate meet the target
     334                 :             :     // feerate.
     335                 :             :     //
     336                 :             :     // We had to convince ourselves that after running the mini miner and
     337                 :             :     // picking all eligible transactions into our MockBlockTemplate, there
     338                 :             :     // could still be transactions remaining that have a lower individual
     339                 :             :     // feerate than their ancestor feerate. So here is an example:
     340                 :             :     //
     341                 :             :     //               ┌─────────────────┐
     342                 :             :     //               │                 │
     343                 :             :     //               │   Grandparent   │
     344                 :             :     //               │    1700 vB      │
     345                 :             :     //               │    1700 sats    │                    Target feerate: 10    s/vB
     346                 :             :     //               │       1 s/vB    │    GP Ancestor Set Feerate (ASFR):  1    s/vB
     347                 :             :     //               │                 │                           P1_ASFR:  9.84 s/vB
     348                 :             :     //               └──────▲───▲──────┘                           P2_ASFR:  2.47 s/vB
     349                 :             :     //                      │   │                                   C_ASFR: 10.27 s/vB
     350                 :             :     // ┌───────────────┐    │   │    ┌──────────────┐
     351                 :             :     // │               ├────┘   └────┤              │             ⇒ C_FR < TFR < C_ASFR
     352                 :             :     // │   Parent 1    │             │   Parent 2   │
     353                 :             :     // │    200 vB     │             │    200 vB    │
     354                 :             :     // │  17000 sats   │             │   3000 sats  │
     355                 :             :     // │     85 s/vB   │             │     15 s/vB  │
     356                 :             :     // │               │             │              │
     357                 :             :     // └───────────▲───┘             └───▲──────────┘
     358                 :             :     //             │                     │
     359                 :             :     //             │    ┌───────────┐    │
     360                 :             :     //             └────┤           ├────┘
     361                 :             :     //                  │   Child   │
     362                 :             :     //                  │  100 vB   │
     363                 :             :     //                  │  900 sats │
     364                 :             :     //                  │    9 s/vB │
     365                 :             :     //                  │           │
     366                 :             :     //                  └───────────┘
     367                 :             :     //
     368                 :             :     // We therefore calculate both the bump fee that is necessary to elevate
     369                 :             :     // the individual transaction to the target feerate:
     370                 :             :     //         target_feerate × tx_size - tx_fees
     371                 :             :     // and the bump fee that is necessary to bump the entire ancestor set to
     372                 :             :     // the target feerate:
     373                 :             :     //         target_feerate × ancestor_set_size - ancestor_set_fees
     374                 :             :     // By picking the maximum from the two, we ensure that a transaction meets
     375                 :             :     // both criteria.
     376         [ +  + ]:       77845 :     for (const auto& [txid, outpoints] : m_requested_outpoints_by_txid) {
     377                 :        9356 :         auto it = m_entries_by_txid.find(txid);
     378                 :        9356 :         Assume(it != m_entries_by_txid.end());
     379         [ +  - ]:        9356 :         if (it != m_entries_by_txid.end()) {
     380         [ +  - ]:       18712 :             Assume(target_feerate.GetFee(it->second.GetSizeWithAncestors()) > std::min(it->second.GetModifiedFee(), it->second.GetModFeesWithAncestors()));
     381                 :        9356 :             CAmount bump_fee_with_ancestors = target_feerate.GetFee(it->second.GetSizeWithAncestors()) - it->second.GetModFeesWithAncestors();
     382         [ +  + ]:        9356 :             CAmount bump_fee_individual = target_feerate.GetFee(it->second.GetTxSize()) - it->second.GetModifiedFee();
     383         [ +  + ]:        9356 :             const CAmount bump_fee{std::max(bump_fee_with_ancestors, bump_fee_individual)};
     384                 :        9356 :             Assume(bump_fee >= 0);
     385         [ +  + ]:       18830 :             for (const auto& outpoint : outpoints) {
     386                 :        9474 :                 m_bump_fees.emplace(outpoint, bump_fee);
     387                 :             :             }
     388                 :             :         }
     389                 :             :     }
     390                 :       68489 :     return m_bump_fees;
     391                 :             : }
     392                 :             : 
     393                 :      133542 : std::optional<CAmount> MiniMiner::CalculateTotalBumpFees(const CFeeRate& target_feerate)
     394                 :             : {
     395         [ -  + ]:      133542 :     if (!m_ready_to_calculate) return std::nullopt;
     396                 :             :     // Build a block template until the target feerate is hit.
     397                 :      133542 :     BuildMockTemplate(target_feerate);
     398                 :             : 
     399                 :             :     // All remaining ancestors that are not part of m_in_block must be bumped, but no other relatives
     400                 :      133542 :     std::set<MockEntryMap::iterator, IteratorComparator> ancestors;
     401                 :      133542 :     std::set<MockEntryMap::iterator, IteratorComparator> to_process;
     402         [ +  + ]:      177970 :     for (const auto& [txid, outpoints] : m_requested_outpoints_by_txid) {
     403                 :             :         // Skip any ancestors that already have a miner score higher than the target feerate
     404                 :             :         // (already "made it" into the block)
     405         [ +  + ]:       44428 :         if (m_in_block.count(txid)) continue;
     406                 :        9356 :         auto iter = m_entries_by_txid.find(txid);
     407         [ -  + ]:        9356 :         if (iter == m_entries_by_txid.end()) continue;
     408         [ +  - ]:        9356 :         to_process.insert(iter);
     409         [ +  - ]:        9356 :         ancestors.insert(iter);
     410                 :             :     }
     411                 :             : 
     412                 :      133542 :     std::set<uint256> has_been_processed;
     413         [ +  + ]:      146584 :     while (!to_process.empty()) {
     414                 :       13042 :         auto iter = to_process.begin();
     415                 :       13042 :         const CTransaction& tx = (*iter)->second.GetTx();
     416         [ +  + ]:      181521 :         for (const auto& input : tx.vin) {
     417         [ +  + ]:      168479 :             if (auto parent_it{m_entries_by_txid.find(input.prevout.hash)}; parent_it != m_entries_by_txid.end()) {
     418         [ +  + ]:      152915 :                 if (!has_been_processed.count(input.prevout.hash)) {
     419         [ +  - ]:       83329 :                     to_process.insert(parent_it);
     420                 :             :                 }
     421         [ +  - ]:      152915 :                 ancestors.insert(parent_it);
     422                 :             :             }
     423                 :             :         }
     424         [ +  - ]:       13042 :         has_been_processed.insert(tx.GetHash());
     425                 :       13042 :         to_process.erase(iter);
     426                 :             :     }
     427                 :      133542 :     const auto ancestor_package_size = std::accumulate(ancestors.cbegin(), ancestors.cend(), int64_t{0},
     428                 :       13042 :         [](int64_t sum, const auto it) {return sum + it->second.GetTxSize();});
     429                 :      133542 :     const auto ancestor_package_fee = std::accumulate(ancestors.cbegin(), ancestors.cend(), CAmount{0},
     430                 :       13042 :         [](CAmount sum, const auto it) {return sum + it->second.GetModifiedFee();});
     431         [ +  - ]:      133542 :     return target_feerate.GetFee(ancestor_package_size) - ancestor_package_fee;
     432                 :      133542 : }
     433                 :             : } // namespace node
        

Generated by: LCOV version 2.0-1