Coverage Report

Created: 2026-11-13 17:38

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