Coverage Report

Created: 2026-08-14 20:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/txmempool.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present 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 <policy/policy.h>
15
#include <policy/settings.h>
16
#include <random.h>
17
#include <tinyformat.h>
18
#include <util/check.h>
19
#include <util/feefrac.h>
20
#include <util/log.h>
21
#include <util/moneystr.h>
22
#include <util/overflow.h>
23
#include <util/result.h>
24
#include <util/time.h>
25
#include <util/trace.h>
26
#include <util/translation.h>
27
#include <validationinterface.h>
28
29
#include <algorithm>
30
#include <cmath>
31
#include <numeric>
32
#include <optional>
33
#include <ranges>
34
#include <string_view>
35
#include <utility>
36
37
TRACEPOINT_SEMAPHORE(mempool, added);
38
TRACEPOINT_SEMAPHORE(mempool, removed);
39
40
bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp)
41
4.56k
{
42
4.56k
    AssertLockHeld(cs_main);
43
    // If there are relative lock times then the maxInputBlock will be set
44
    // If there are no relative lock times, the LockPoints don't depend on the chain
45
4.56k
    if (lp.maxInputBlock) {
46
        // Check whether active_chain is an extension of the block at which the LockPoints
47
        // calculation was valid.  If not LockPoints are no longer valid
48
4.56k
        if (!active_chain.Contains(*lp.maxInputBlock)) {
49
230
            return false;
50
230
        }
51
4.56k
    }
52
53
    // LockPoints still valid
54
4.33k
    return true;
55
4.56k
}
56
57
std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58
11.8M
{
59
11.8M
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60
11.8M
    const auto& hash = entry.GetTx().GetHash();
61
11.8M
    {
62
11.8M
        LOCK(cs);
63
11.8M
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64
12.0M
        for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65
210k
            ret.emplace_back(*(iter->second));
66
210k
        }
67
11.8M
    }
68
11.8M
    std::ranges::sort(ret, CompareIteratorByHash{});
69
11.8M
    auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70
11.8M
    ret.erase(removed.begin(), removed.end());
71
11.8M
    return ret;
72
11.8M
}
73
74
std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75
11.9M
{
76
11.9M
    LOCK(cs);
77
11.9M
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78
11.9M
    std::set<Txid> inputs;
79
15.3M
    for (const auto& txin : entry.GetTx().vin) {
80
15.3M
        inputs.insert(txin.prevout.hash);
81
15.3M
    }
82
15.3M
    for (const auto& hash : inputs) {
83
15.3M
        std::optional<txiter> piter = GetIter(hash);
84
15.3M
        if (piter) {
85
209k
            ret.emplace_back(**piter);
86
209k
        }
87
15.3M
    }
88
11.9M
    return ret;
89
11.9M
}
90
91
void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
92
2.13k
{
93
2.13k
    AssertLockHeld(cs);
94
95
    // Iterate in reverse, so that whenever we are looking at a transaction
96
    // we are sure that all in-mempool descendants have already been processed.
97
2.13k
    for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
98
        // calculate children from mapNextTx
99
790
        txiter it = mapTx.find(hash);
100
790
        if (it == mapTx.end()) {
101
0
            continue;
102
0
        }
103
790
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104
790
        {
105
3.25k
            for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
106
2.46k
                txiter childIter = iter->second;
107
2.46k
                assert(childIter != mapTx.end());
108
                // Add dependencies that are discovered between transactions in the
109
                // block and transactions that were in the mempool to txgraph.
110
2.46k
                m_txgraph->AddDependency(/*parent=*/*it, /*child=*/*childIter);
111
2.46k
            }
112
790
        }
113
790
    }
114
115
2.13k
    auto txs_to_remove = m_txgraph->Trim(); // Enforce cluster size limits.
116
2.13k
    for (auto txptr : txs_to_remove) {
117
0
        const CTxMemPoolEntry& entry = *(static_cast<const CTxMemPoolEntry*>(txptr));
118
0
        removeUnchecked(mapTx.iterator_to(entry), MemPoolRemovalReason::SIZELIMIT);
119
0
    }
120
2.13k
}
121
122
bool CTxMemPool::HasDescendants(const Txid& txid) const
123
223
{
124
223
    LOCK(cs);
125
223
    auto entry = GetEntry(txid);
126
223
    if (!entry) return false;
127
222
    return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128
223
}
129
130
CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131
1.93k
{
132
1.93k
    auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133
1.93k
    setEntries ret;
134
1.93k
    if (ancestors.size() > 0) {
135
14.1k
        for (auto ancestor : ancestors) {
136
14.1k
            if (ancestor != &entry) {
137
13.4k
                ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
138
13.4k
            }
139
14.1k
        }
140
615
        return ret;
141
615
    }
142
143
    // If we didn't get anything back, the transaction is not in the graph.
144
    // Find each parent and call GetAncestors on each.
145
1.32k
    setEntries staged_parents;
146
1.32k
    const CTransaction &tx = entry.GetTx();
147
148
    // Get parents of this transaction that are in the mempool
149
3.08k
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
150
1.76k
        std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151
1.76k
        if (piter) {
152
241
            staged_parents.insert(*piter);
153
241
        }
154
1.76k
    }
155
156
1.32k
    for (const auto& parent : staged_parents) {
157
215
        auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158
601
        for (auto ancestor : parent_ancestors) {
159
601
            ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160
601
        }
161
215
    }
162
163
1.32k
    return ret;
164
1.93k
}
165
166
static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167
1.25k
{
168
1.25k
    opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169
1.25k
    int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170
1.25k
    if (opts.max_size_bytes < 0 || (opts.max_size_bytes > 0 && opts.max_size_bytes < cluster_limit_bytes)) {
171
1
        error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(cluster_limit_bytes / 1'000'000.0));
172
1
    }
173
1.25k
    return std::move(opts);
174
1.25k
}
175
176
CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177
1.25k
    : m_opts{Flatten(std::move(opts), error)}
178
1.25k
{
179
1.25k
    m_txgraph = MakeTxGraph(
180
1.25k
        /*max_cluster_count=*/m_opts.limits.cluster_count,
181
1.25k
        /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182
1.25k
        /*acceptable_cost=*/ACCEPTABLE_COST,
183
84.5M
        /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184
84.5M
            const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185
84.5M
            const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186
84.5M
            return txid_a <=> txid_b;
187
84.5M
        });
188
1.25k
}
189
190
bool CTxMemPool::isSpent(const COutPoint& outpoint) const
191
54
{
192
54
    LOCK(cs);
193
54
    return mapNextTx.count(outpoint);
194
54
}
195
196
unsigned int CTxMemPool::GetTransactionsUpdated() const
197
2.09k
{
198
2.09k
    return nTransactionsUpdated;
199
2.09k
}
200
201
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202
127k
{
203
127k
    nTransactionsUpdated += n;
204
127k
}
205
206
void CTxMemPool::Apply(ChangeSet* changeset)
207
52.7k
{
208
52.7k
    AssertLockHeld(cs);
209
52.7k
    m_txgraph->CommitStaging();
210
211
52.7k
    RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212
213
105k
    for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214
52.8k
        auto tx_entry = changeset->m_entry_vec[i];
215
        // First splice this entry into mapTx.
216
52.8k
        auto node_handle = changeset->m_to_add.extract(tx_entry);
217
52.8k
        auto result = mapTx.insert(std::move(node_handle));
218
219
52.8k
        Assume(result.inserted);
220
52.8k
        txiter it = result.position;
221
222
52.8k
        addNewTransaction(it);
223
52.8k
    }
224
52.7k
    if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
225
0
        LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after addition(s).");
226
0
    }
227
52.7k
}
228
229
void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230
52.8k
{
231
52.8k
    const CTxMemPoolEntry& entry = *newit;
232
233
    // Update cachedInnerUsage to include contained transaction's usage.
234
    // (When we update the entry for in-mempool parents, memory usage will be
235
    // further updated.)
236
52.8k
    cachedInnerUsage += entry.DynamicMemoryUsage();
237
238
52.8k
    const CTransaction& tx = newit->GetTx();
239
119k
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
240
66.4k
        mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
241
66.4k
    }
242
    // Don't bother worrying about child transactions of this one.
243
    // Normal case of a new transaction arriving is that there can't be any
244
    // children, because such children would be orphans.
245
    // An exception to that is if a transaction enters that used to be in a block.
246
    // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
247
    // to clean up the mess we're leaving here.
248
249
52.8k
    nTransactionsUpdated++;
250
52.8k
    totalTxSize += entry.GetTxSize();
251
52.8k
    m_total_fee += entry.GetFee();
252
253
52.8k
    txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254
52.8k
    newit->idx_randomized = txns_randomized.size() - 1;
255
256
52.8k
    TRACEPOINT(mempool, added,
257
52.8k
        entry.GetTx().GetHash().data(),
258
52.8k
        entry.GetTxSize(),
259
52.8k
        entry.GetFee()
260
52.8k
    );
261
52.8k
}
262
263
void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
264
49.2k
{
265
    // We increment mempool sequence value no matter removal reason
266
    // even if not directly reported below.
267
49.2k
    uint64_t mempool_sequence = GetAndIncrementSequence();
268
269
49.2k
    if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
270
        // Notify clients that a transaction has been removed from the mempool
271
        // for any reason except being included in a block. Clients interested
272
        // in transactions included in blocks can subscribe to the BlockConnected
273
        // notification.
274
2.25k
        m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
275
2.25k
    }
276
49.2k
    TRACEPOINT(mempool, removed,
277
49.2k
        it->GetTx().GetHash().data(),
278
49.2k
        RemovalReasonToString(reason).c_str(),
279
49.2k
        it->GetTxSize(),
280
49.2k
        it->GetFee(),
281
49.2k
        std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
282
49.2k
    );
283
284
49.2k
    for (const CTxIn& txin : it->GetTx().vin)
285
61.5k
        mapNextTx.erase(txin.prevout);
286
287
49.2k
    RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288
289
49.2k
    if (txns_randomized.size() > 1) {
290
        // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291
46.9k
        txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292
46.9k
        txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293
46.9k
        txns_randomized.pop_back();
294
46.9k
        if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
295
3.32k
            txns_randomized.shrink_to_fit();
296
3.32k
        }
297
46.9k
    } else {
298
2.26k
        txns_randomized.clear();
299
2.26k
    }
300
301
49.2k
    totalTxSize -= it->GetTxSize();
302
49.2k
    m_total_fee -= it->GetFee();
303
49.2k
    cachedInnerUsage -= it->DynamicMemoryUsage();
304
49.2k
    mapTx.erase(it);
305
49.2k
    nTransactionsUpdated++;
306
49.2k
}
307
308
// Calculates descendants of given entry and adds to setDescendants.
309
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310
80.2k
{
311
80.2k
    (void)CalculateDescendants(*entryit, setDescendants);
312
80.2k
    return;
313
80.2k
}
314
315
CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316
80.2k
{
317
282k
    for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318
282k
        setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319
282k
    }
320
80.2k
    return mapTx.iterator_to(entry);
321
80.2k
}
322
323
void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324
152
{
325
152
    AssertLockHeld(cs);
326
152
    Assume(!m_have_changeset);
327
152
    auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328
396
    for (auto tx: descendants) {
329
396
        removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330
396
    }
331
152
}
332
333
void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
334
19.6k
{
335
    // Remove transaction from memory pool
336
19.6k
    AssertLockHeld(cs);
337
19.6k
    Assume(!m_have_changeset);
338
19.6k
    txiter origit = mapTx.find(origTx.GetHash());
339
19.6k
    if (origit != mapTx.end()) {
340
7
        removeRecursive(origit, reason);
341
19.6k
    } else {
342
        // When recursively removing but origTx isn't in the mempool
343
        // be sure to remove any descendants that are in the pool. This can
344
        // happen during chain re-orgs if origTx isn't re-accepted into
345
        // the mempool for any reason.
346
19.6k
        auto iter = mapNextTx.lower_bound(COutPoint(origTx.GetHash(), 0));
347
19.6k
        std::vector<const TxGraph::Ref*> to_remove;
348
19.7k
        while (iter != mapNextTx.end() && iter->first->hash == origTx.GetHash()) {
349
74
            to_remove.emplace_back(&*(iter->second));
350
74
            ++iter;
351
74
        }
352
19.6k
        auto all_removes = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
353
19.6k
        for (auto ref : all_removes) {
354
77
            auto tx = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
355
77
            removeUnchecked(tx, reason);
356
77
        }
357
19.6k
    }
358
19.6k
}
359
360
void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
361
2.13k
{
362
    // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
363
2.13k
    AssertLockHeld(cs);
364
2.13k
    AssertLockHeld(::cs_main);
365
2.13k
    Assume(!m_have_changeset);
366
367
2.13k
    std::vector<const TxGraph::Ref*> to_remove;
368
4.43k
    for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369
2.30k
        if (check_final_and_mature(it)) {
370
15
            to_remove.emplace_back(&*it);
371
15
        }
372
2.30k
    }
373
374
2.13k
    auto all_to_remove = m_txgraph->GetDescendantsUnion(to_remove, TxGraph::Level::MAIN);
375
376
2.13k
    for (auto ref : all_to_remove) {
377
37
        auto it = mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref));
378
37
        removeUnchecked(it, MemPoolRemovalReason::REORG);
379
37
    }
380
4.39k
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381
2.26k
        assert(TestLockPointValidity(chain, it->GetLockPoints()));
382
2.26k
    }
383
2.13k
    if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
384
0
        LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after reorg.");
385
0
    }
386
2.13k
}
387
388
void CTxMemPool::removeConflicts(const CTransaction &tx)
389
59.4k
{
390
    // Remove transactions which depend on inputs of tx, recursively
391
59.4k
    AssertLockHeld(cs);
392
71.7k
    for (const CTxIn &txin : tx.vin) {
393
71.7k
        auto it = mapNextTx.find(txin.prevout);
394
71.7k
        if (it != mapNextTx.end()) {
395
145
            const CTransaction &txConflict = it->second->GetTx();
396
145
            if (Assume(txConflict.GetHash() != tx.GetHash()))
397
145
            {
398
145
                ClearPrioritisation(txConflict.GetHash());
399
145
                removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400
145
            }
401
145
        }
402
71.7k
    }
403
59.4k
}
404
405
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
406
112k
{
407
    // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
408
112k
    AssertLockHeld(cs);
409
112k
    Assume(!m_have_changeset);
410
112k
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411
112k
    if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
412
7.97k
        txs_removed_for_block.reserve(vtx.size());
413
59.4k
        for (const auto& tx : vtx) {
414
59.4k
            txiter it = mapTx.find(tx->GetHash());
415
59.4k
            if (it != mapTx.end()) {
416
46.9k
                txs_removed_for_block.emplace_back(*it);
417
46.9k
                removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418
46.9k
            }
419
59.4k
            removeConflicts(*tx);
420
59.4k
            ClearPrioritisation(tx->GetHash());
421
59.4k
        }
422
7.97k
    }
423
112k
    if (m_opts.signals) {
424
112k
        m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425
112k
    }
426
112k
    lastRollingFeeUpdate = GetTime();
427
112k
    blockSinceLastRollingFeeBump = true;
428
112k
    if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429
0
        LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
430
0
    }
431
112k
}
432
433
void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434
147k
{
435
147k
    if (m_opts.check_ratio == 0) return;
436
437
145k
    if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438
439
145k
    AssertLockHeld(::cs_main);
440
145k
    LOCK(cs);
441
145k
    LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
442
443
145k
    uint64_t checkTotal = 0;
444
145k
    CAmount check_total_fee{0};
445
145k
    CAmount check_total_modified_fee{0};
446
145k
    int64_t check_total_adjusted_weight{0};
447
145k
    uint64_t innerUsage = 0;
448
449
145k
    assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450
145k
    m_txgraph->SanityCheck();
451
452
145k
    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453
454
145k
    const auto score_with_topo{GetSortedScoreWithTopology()};
455
456
    // Number of chunks is bounded by number of transactions.
457
145k
    const auto diagram{GetFeerateDiagram()};
458
145k
    assert(diagram.size() <= score_with_topo.size() + 1);
459
145k
    assert(diagram.size() >= 1);
460
461
145k
    std::optional<txiter> last_iter = std::nullopt;
462
145k
    auto diagram_iter = diagram.cbegin();
463
464
11.8M
    for (const auto& it : score_with_topo) {
465
        // GetSortedScoreWithTopology() contains the same chunks as the feerate
466
        // diagram. We do not know where the chunk boundaries are, but we can
467
        // check that there are points at which they match the cumulative fee
468
        // and weight.
469
        // The feerate diagram should never get behind the current transaction
470
        // size totals.
471
11.8M
        assert(diagram_iter->size >= check_total_adjusted_weight);
472
11.8M
        if (diagram_iter->fee == check_total_modified_fee &&
473
11.8M
                diagram_iter->size == check_total_adjusted_weight) {
474
11.8M
            ++diagram_iter;
475
11.8M
        }
476
11.8M
        checkTotal += it->GetTxSize();
477
11.8M
        check_total_adjusted_weight += it->GetAdjustedWeight();
478
11.8M
        check_total_fee += it->GetFee();
479
11.8M
        check_total_modified_fee += it->GetModifiedFee();
480
11.8M
        innerUsage += it->DynamicMemoryUsage();
481
11.8M
        const CTransaction& tx = it->GetTx();
482
483
11.8M
        if (last_iter) {
484
11.8M
            assert(m_txgraph->CompareMainOrder(**last_iter, *it) < 0);
485
11.8M
        }
486
11.8M
        last_iter = it;
487
488
11.8M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
489
11.8M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
490
15.2M
        for (const CTxIn &txin : tx.vin) {
491
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
492
15.2M
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
493
15.2M
            if (it2 != mapTx.end()) {
494
202k
                const CTransaction& tx2 = it2->GetTx();
495
202k
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
496
202k
                setParentCheck.insert(*it2);
497
202k
            }
498
            // We are iterating through the mempool entries sorted
499
            // topologically and by mining score. All parents must have been
500
            // checked before their children and their coins added to the
501
            // mempoolDuplicate coins cache.
502
15.2M
            assert(mempoolDuplicate.HaveCoin(txin.prevout));
503
            // Check whether its inputs are marked in mapNextTx.
504
15.2M
            auto it3 = mapNextTx.find(txin.prevout);
505
15.2M
            assert(it3 != mapNextTx.end());
506
15.2M
            assert(it3->first == &txin.prevout);
507
15.2M
            assert(&it3->second->GetTx() == &tx);
508
15.2M
        }
509
11.8M
        auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
510
405k
            return a.GetTx().GetHash() == b.GetTx().GetHash();
511
405k
        };
512
11.8M
        for (auto &txentry : GetParents(*it)) {
513
202k
            setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
514
202k
        }
515
11.8M
        assert(setParentCheck.size() == setParentsStored.size());
516
11.8M
        assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
517
518
        // Check children against mapNextTx
519
11.8M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
520
11.8M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
521
11.8M
        auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
522
12.0M
        for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
523
202k
            txiter childit = iter->second;
524
202k
            assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
525
202k
            setChildrenCheck.insert(*childit);
526
202k
        }
527
11.8M
        for (auto &txentry : GetChildren(*it)) {
528
202k
            setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
529
202k
        }
530
11.8M
        assert(setChildrenCheck.size() == setChildrenStored.size());
531
11.8M
        assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
532
533
11.8M
        TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
534
11.8M
        CAmount txfee = 0;
535
11.8M
        assert(!tx.IsCoinBase());
536
11.8M
        assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
537
15.2M
        for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
538
11.8M
        AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
539
11.8M
    }
540
15.4M
    for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
541
15.2M
        indexed_transaction_set::const_iterator it2 = it->second;
542
15.2M
        assert(it2 != mapTx.end());
543
15.2M
    }
544
545
145k
    ++diagram_iter;
546
145k
    assert(diagram_iter == diagram.cend());
547
548
145k
    assert(totalTxSize == checkTotal);
549
145k
    assert(m_total_fee == check_total_fee);
550
145k
    assert(diagram.back().fee == check_total_modified_fee);
551
145k
    assert(diagram.back().size == check_total_adjusted_weight);
552
145k
    assert(innerUsage == cachedInnerUsage);
553
145k
}
554
555
std::vector<CTxMemPool::txiter> CTxMemPool::ExtractBestByMiningScoreWithTopology(std::vector<Wtxid>& wtxids, size_t n_to_sort) const
556
64.4k
{
557
    /* This function takes a vector of `wtxids`, and returns the
558
     * best mempool entries corresponding to those `wtxids` (by mining
559
     * score/topology). It updates the input `wtxids` so that multiple
560
     * calls with the same vector will drain that vector to empty.
561
     *
562
     * It operates under the following constraints:
563
     *   - wtxids that do not correspond to a mempool entry are dropped
564
     *   - the return vector contains no duplicates, either with itself
565
     *     or with the updated `wtxids` input.
566
     *   - the return vector will have `n_to_sort` entries (or `wtxids`
567
           will become empty).
568
     *   - the `wtxids` vector will be reduced by at least `n_to_sort`
569
     *     entries (or will become empty).
570
     */
571
572
380k
    auto cmp = [&](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept { return m_txgraph->CompareMainOrder(*a, *b) < 0; };
573
574
64.4k
    std::vector<txiter> res;
575
576
64.4k
    n_to_sort = std::min(wtxids.size(), n_to_sort);
577
64.4k
    if (n_to_sort > 0) {
578
64.4k
        res.reserve(wtxids.size());
579
64.4k
        std::sort(wtxids.begin(), wtxids.end());
580
214k
        for (auto it = wtxids.begin(); it != wtxids.end(); ++it) {
581
            // skip duplicates
582
150k
            auto itnext = it + 1;
583
150k
            if (itnext != wtxids.end() && *it == *itnext) continue;
584
585
146k
            if (auto i{GetIter(*it)}; i.has_value()) {
586
140k
                res.push_back(i.value());
587
140k
            }
588
146k
        }
589
64.4k
        wtxids.clear();
590
591
64.4k
        if (!res.empty()) {
592
64.2k
            auto begin = res.begin();
593
64.2k
            auto end = res.end();
594
64.2k
            auto middle = end;
595
64.2k
            if (n_to_sort >= res.size()) {
596
                // use regular sort when sorting everything
597
64.0k
                std::sort(begin, end, cmp);
598
64.0k
            } else {
599
152
                middle = begin + n_to_sort;
600
152
                std::partial_sort(begin, middle, end, cmp);
601
152
            }
602
64.2k
            auto it = middle;
603
100k
            while (it != end) {
604
36.1k
                wtxids.push_back((*it)->GetTx().GetWitnessHash());
605
36.1k
                ++it;
606
36.1k
            }
607
64.2k
            res.erase(middle, end);
608
64.2k
        }
609
64.4k
    }
610
64.4k
    return res;
611
64.4k
}
612
613
std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
614
156k
{
615
156k
    std::vector<indexed_transaction_set::const_iterator> iters;
616
156k
    AssertLockHeld(cs);
617
618
156k
    iters.reserve(mapTx.size());
619
620
12.3M
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
621
12.2M
        iters.push_back(mi);
622
12.2M
    }
623
142M
    std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
624
142M
        return m_txgraph->CompareMainOrder(*a, *b) < 0;
625
142M
    });
626
156k
    return iters;
627
156k
}
628
629
std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
630
10.1k
{
631
10.1k
    AssertLockHeld(cs);
632
633
10.1k
    std::vector<CTxMemPoolEntryRef> ret;
634
10.1k
    ret.reserve(mapTx.size());
635
339k
    for (const auto& it : GetSortedScoreWithTopology()) {
636
339k
        ret.emplace_back(*it);
637
339k
    }
638
10.1k
    return ret;
639
10.1k
}
640
641
std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
642
958
{
643
958
    LOCK(cs);
644
958
    auto iters = GetSortedScoreWithTopology();
645
646
958
    std::vector<TxMempoolInfo> ret;
647
958
    ret.reserve(mapTx.size());
648
1.30k
    for (auto it : iters) {
649
1.30k
        ret.push_back(GetInfo(it));
650
1.30k
    }
651
652
958
    return ret;
653
958
}
654
655
const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
656
2.91k
{
657
2.91k
    AssertLockHeld(cs);
658
2.91k
    const auto i = mapTx.find(txid);
659
2.91k
    return i == mapTx.end() ? nullptr : &(*i);
660
2.91k
}
661
662
CTransactionRef CTxMemPool::get(const Txid& hash) const
663
252k
{
664
252k
    LOCK(cs);
665
252k
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
666
252k
    if (i == mapTx.end())
667
193k
        return nullptr;
668
58.3k
    return i->GetSharedTx();
669
252k
}
670
671
CTransactionRef CTxMemPool::get(const Wtxid& hash) const
672
4
{
673
4
    LOCK(cs);
674
4
    const auto& wtxid_map{mapTx.get<index_by_wtxid>()};
675
4
    const auto it{wtxid_map.find(hash)};
676
4
    if (it == wtxid_map.end()) return nullptr;
677
2
    return it->GetSharedTx();
678
4
}
679
680
void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
681
769
{
682
769
    {
683
769
        LOCK(cs);
684
769
        CAmount &delta = mapDeltas[hash];
685
769
        delta = SaturatingAdd(delta, nFeeDelta);
686
769
        txiter it = mapTx.find(hash);
687
769
        if (it != mapTx.end()) {
688
            // PrioritiseTransaction calls stack on previous ones. Set the new
689
            // transaction fee to be current modified fee + feedelta.
690
262
            it->UpdateModifiedFee(nFeeDelta);
691
262
            m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
692
262
            ++nTransactionsUpdated;
693
262
        }
694
769
        if (delta == 0) {
695
9
            mapDeltas.erase(hash);
696
9
            LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
697
760
        } else {
698
760
            LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
699
760
                      hash.ToString(),
700
760
                      it == mapTx.end() ? "not " : "",
701
760
                      FormatMoney(nFeeDelta),
702
760
                      FormatMoney(delta));
703
760
        }
704
769
    }
705
769
}
706
707
void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
708
74.3k
{
709
74.3k
    AssertLockHeld(cs);
710
74.3k
    std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
711
74.3k
    if (pos == mapDeltas.end())
712
74.2k
        return;
713
41
    const CAmount &delta = pos->second;
714
41
    nFeeDelta += delta;
715
41
}
716
717
void CTxMemPool::ClearPrioritisation(const Txid& hash)
718
59.5k
{
719
59.5k
    AssertLockHeld(cs);
720
59.5k
    mapDeltas.erase(hash);
721
59.5k
}
722
723
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
724
31
{
725
31
    AssertLockNotHeld(cs);
726
31
    LOCK(cs);
727
31
    std::vector<delta_info> result;
728
31
    result.reserve(mapDeltas.size());
729
31
    for (const auto& [txid, delta] : mapDeltas) {
730
30
        const auto iter{mapTx.find(txid)};
731
30
        const bool in_mempool{iter != mapTx.end()};
732
30
        std::optional<CAmount> modified_fee;
733
30
        if (in_mempool) modified_fee = iter->GetModifiedFee();
734
30
        result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
735
30
    }
736
31
    return result;
737
31
}
738
739
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
740
118k
{
741
118k
    const auto it = mapNextTx.find(prevout);
742
118k
    return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
743
118k
}
744
745
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
746
15.4M
{
747
15.4M
    AssertLockHeld(cs);
748
15.4M
    auto it = mapTx.find(txid);
749
15.4M
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
750
15.4M
}
751
752
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
753
160k
{
754
160k
    AssertLockHeld(cs);
755
160k
    auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
756
160k
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
757
160k
}
758
759
CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
760
43.9k
{
761
43.9k
    CTxMemPool::setEntries ret;
762
43.9k
    for (const auto& h : hashes) {
763
2.40k
        const auto mi = GetIter(h);
764
2.40k
        if (mi) ret.insert(*mi);
765
2.40k
    }
766
43.9k
    return ret;
767
43.9k
}
768
769
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
770
2
{
771
2
    AssertLockHeld(cs);
772
2
    std::vector<txiter> ret;
773
2
    ret.reserve(txids.size());
774
563
    for (const auto& txid : txids) {
775
563
        const auto it{GetIter(txid)};
776
563
        if (!it) return {};
777
563
        ret.push_back(*it);
778
563
    }
779
2
    return ret;
780
2
}
781
782
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
783
26.2k
{
784
60.2k
    for (unsigned int i = 0; i < tx.vin.size(); i++)
785
37.3k
        if (exists(tx.vin[i].prevout.hash))
786
3.32k
            return false;
787
22.9k
    return true;
788
26.2k
}
789
790
52.0k
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
791
792
std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
793
73.1k
{
794
    // Check to see if the inputs are made available by another tx in the package.
795
    // These Coins would not be available in the underlying CoinsView.
796
73.1k
    if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
797
615
        return it->second;
798
615
    }
799
800
    // If an entry in the mempool exists, always return that one, as it's guaranteed to never
801
    // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
802
    // transactions. First checking the underlying cache risks returning a pruned entry instead.
803
72.5k
    CTransactionRef ptx = mempool.get(outpoint.hash);
804
72.5k
    if (ptx) {
805
8.51k
        if (outpoint.n < ptx->vout.size()) {
806
8.51k
            Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
807
8.51k
            m_non_base_coins.emplace(outpoint);
808
8.51k
            return coin;
809
8.51k
        }
810
0
        return std::nullopt;
811
8.51k
    }
812
63.9k
    return base->GetCoin(outpoint);
813
72.5k
}
814
815
void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
816
776
{
817
1.58k
    for (unsigned int n = 0; n < tx->vout.size(); ++n) {
818
813
        m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
819
813
        m_non_base_coins.emplace(tx->GetHash(), n);
820
813
    }
821
776
}
822
void CCoinsViewMemPool::Reset()
823
76.2k
{
824
76.2k
    m_temp_added.clear();
825
76.2k
    m_non_base_coins.clear();
826
76.2k
}
827
828
492k
size_t CTxMemPool::DynamicMemoryUsage() const {
829
492k
    LOCK(cs);
830
    // Estimate the overhead of mapTx to be 9 pointers (3 pointers per index) + an allocation, as no exact formula for boost::multi_index_contained is implemented.
831
492k
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
832
492k
}
833
834
63.2k
void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
835
63.2k
    LOCK(cs);
836
837
63.2k
    if (m_unbroadcast_txids.erase(txid))
838
11.5k
    {
839
11.5k
        LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
840
11.5k
    }
841
63.2k
}
842
843
80.2k
void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
844
80.2k
    AssertLockHeld(cs);
845
80.2k
    for (txiter it : stage) {
846
1.69k
        removeUnchecked(it, reason);
847
1.69k
    }
848
80.2k
}
849
850
bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
851
3.53k
{
852
3.53k
    LOCK(cs);
853
    // Use ChangeSet interface to check whether the cluster count
854
    // limits would be violated. Note that the changeset will be destroyed
855
    // when it goes out of scope.
856
3.53k
    auto changeset = GetChangeSet();
857
3.53k
    (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
858
3.53k
    return changeset->CheckMemPoolPolicyLimits();
859
3.53k
}
860
861
int CTxMemPool::Expire(std::chrono::seconds time)
862
27.4k
{
863
27.4k
    AssertLockHeld(cs);
864
27.4k
    Assume(!m_have_changeset);
865
27.4k
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
866
27.4k
    setEntries toremove;
867
27.5k
    while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
868
22
        toremove.insert(mapTx.project<0>(it));
869
22
        it++;
870
22
    }
871
27.4k
    setEntries stage;
872
27.4k
    for (txiter removeit : toremove) {
873
22
        CalculateDescendants(removeit, stage);
874
22
    }
875
27.4k
    RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
876
27.4k
    return stage.size();
877
27.4k
}
878
879
435k
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
880
435k
    LOCK(cs);
881
435k
    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
882
435k
        return CFeeRate(llround(rollingMinimumFeeRate));
883
884
217
    int64_t time = GetTime();
885
217
    if (time > lastRollingFeeUpdate + 10) {
886
6
        double halflife = ROLLING_FEE_HALFLIFE;
887
6
        if (DynamicMemoryUsage() < sizelimit / 4)
888
1
            halflife /= 4;
889
5
        else if (DynamicMemoryUsage() < sizelimit / 2)
890
1
            halflife /= 2;
891
892
6
        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
893
6
        lastRollingFeeUpdate = time;
894
895
6
        if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
896
1
            rollingMinimumFeeRate = 0;
897
1
            return CFeeRate(0);
898
1
        }
899
6
    }
900
216
    return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
901
217
}
902
903
43
void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
904
43
    AssertLockHeld(cs);
905
43
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
906
41
        rollingMinimumFeeRate = rate.GetFeePerK();
907
41
        blockSinceLastRollingFeeBump = false;
908
41
    }
909
43
}
910
911
27.5k
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
912
27.5k
    AssertLockHeld(cs);
913
27.5k
    Assume(!m_have_changeset);
914
915
27.5k
    unsigned nTxnRemoved = 0;
916
27.5k
    CFeeRate maxFeeRateRemoved(0);
917
918
27.5k
    while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
919
43
        const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
920
43
        FeePerVSize feerate = ToFeePerVSize(feeperweight);
921
43
        CFeeRate removed{feerate.fee, feerate.size};
922
923
        // We set the new mempool min fee to the feerate of the removed set, plus the
924
        // "minimum reasonable fee rate" (ie some value under which we consider txn
925
        // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
926
        // equal to txn which were removed with no block in between.
927
43
        removed += m_opts.incremental_relay_feerate;
928
43
        trackPackageRemoved(removed);
929
43
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
930
931
43
        nTxnRemoved += worst_chunk.size();
932
933
43
        std::vector<CTransaction> txn;
934
43
        if (pvNoSpendsRemaining) {
935
35
            txn.reserve(worst_chunk.size());
936
36
            for (auto ref : worst_chunk) {
937
36
                txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
938
36
            }
939
35
        }
940
941
43
        setEntries stage;
942
49
        for (auto ref : worst_chunk) {
943
49
            stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
944
49
        }
945
49
        for (auto e : stage) {
946
49
            removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
947
49
        }
948
43
        if (pvNoSpendsRemaining) {
949
36
            for (const CTransaction& tx : txn) {
950
36
                for (const CTxIn& txin : tx.vin) {
951
36
                    if (exists(txin.prevout.hash)) continue;
952
35
                    pvNoSpendsRemaining->push_back(txin.prevout);
953
35
                }
954
36
            }
955
35
        }
956
43
    }
957
958
27.5k
    if (maxFeeRateRemoved > CFeeRate(0)) {
959
35
        LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
960
35
    }
961
27.5k
}
962
963
std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
964
124k
{
965
124k
    auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
966
967
124k
    size_t ancestor_count = ancestors.size();
968
124k
    size_t ancestor_size = 0;
969
124k
    CAmount ancestor_fees = 0;
970
319k
    for (auto tx: ancestors) {
971
319k
        const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
972
319k
        ancestor_size += anc.GetTxSize();
973
319k
        ancestor_fees += anc.GetModifiedFee();
974
319k
    }
975
124k
    return {ancestor_count, ancestor_size, ancestor_fees};
976
124k
}
977
978
std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
979
8.31k
{
980
8.31k
    auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
981
8.31k
    size_t descendant_count = descendants.size();
982
8.31k
    size_t descendant_size = 0;
983
8.31k
    CAmount descendant_fees = 0;
984
985
154k
    for (auto tx: descendants) {
986
154k
        const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
987
154k
        descendant_size += desc.GetTxSize();
988
154k
        descendant_fees += desc.GetModifiedFee();
989
154k
    }
990
8.31k
    return {descendant_count, descendant_size, descendant_fees};
991
8.31k
}
992
993
583k
void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
994
583k
    LOCK(cs);
995
583k
    auto it = mapTx.find(txid);
996
583k
    ancestors = cluster_count = 0;
997
583k
    if (it != mapTx.end()) {
998
47.8k
        auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
999
47.8k
        ancestors = ancestor_count;
1000
47.8k
        if (ancestorsize) *ancestorsize = ancestor_size;
1001
47.8k
        if (ancestorfees) *ancestorfees = ancestor_fees;
1002
47.8k
        cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
1003
47.8k
    }
1004
583k
}
1005
1006
bool CTxMemPool::GetLoadTried() const
1007
2.45k
{
1008
2.45k
    LOCK(cs);
1009
2.45k
    return m_load_tried;
1010
2.45k
}
1011
1012
void CTxMemPool::SetLoadTried(bool load_tried)
1013
1.03k
{
1014
1.03k
    LOCK(cs);
1015
1.03k
    m_load_tried = load_tried;
1016
1.03k
}
1017
1018
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1019
3.13k
{
1020
3.13k
    AssertLockHeld(cs);
1021
1022
3.13k
    std::vector<CTxMemPool::txiter> ret;
1023
3.13k
    std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
1024
49.7k
    for (auto txid : txids) {
1025
49.7k
        auto it = mapTx.find(txid);
1026
49.7k
        if (it != mapTx.end()) {
1027
            // Note that TxGraph::GetCluster will return results in graph
1028
            // order, which is deterministic (as long as we are not modifying
1029
            // the graph).
1030
49.7k
            auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
1031
49.7k
            if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
1032
69.6k
                for (auto tx : cluster) {
1033
69.6k
                    ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
1034
69.6k
                }
1035
49.5k
            }
1036
49.7k
        }
1037
49.7k
    }
1038
3.13k
    if (ret.size() > 500) {
1039
1
        return {};
1040
1
    }
1041
3.13k
    return ret;
1042
3.13k
}
1043
1044
util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1045
1.34k
{
1046
1.34k
    LOCK(m_pool->cs);
1047
1048
1.34k
    if (!CheckMemPoolPolicyLimits()) {
1049
0
        return util::Error{Untranslated("cluster size limit exceeded")};
1050
0
    }
1051
1052
1.34k
    return m_pool->m_txgraph->GetMainStagingDiagrams();
1053
1.34k
}
1054
1055
CTxMemPool::ChangeSet::TxHandle CTxMemPool::ChangeSet::StageAddition(const CTransactionRef& tx, const CAmount fee, int64_t time, unsigned int entry_height, uint64_t entry_sequence, bool spends_coinbase, int64_t sigops_cost, LockPoints lp)
1056
74.3k
{
1057
74.3k
    LOCK(m_pool->cs);
1058
74.3k
    Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1059
74.3k
    Assume(!m_dependencies_processed);
1060
1061
    // We need to process dependencies after adding a new transaction.
1062
74.3k
    m_dependencies_processed = false;
1063
1064
74.3k
    CAmount delta{0};
1065
74.3k
    m_pool->ApplyDelta(tx->GetHash(), delta);
1066
1067
74.3k
    FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1068
74.3k
    auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1069
74.3k
    m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1070
74.3k
    if (delta) {
1071
41
        newit->UpdateModifiedFee(delta);
1072
41
        m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1073
41
    }
1074
1075
74.3k
    m_entry_vec.push_back(newit);
1076
1077
74.3k
    return newit;
1078
74.3k
}
1079
1080
void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1081
2.26k
{
1082
2.26k
    LOCK(m_pool->cs);
1083
2.26k
    m_pool->m_txgraph->RemoveTransaction(*it);
1084
2.26k
    m_to_remove.insert(it);
1085
2.26k
}
1086
1087
void CTxMemPool::ChangeSet::Apply()
1088
52.7k
{
1089
52.7k
    LOCK(m_pool->cs);
1090
52.7k
    if (!m_dependencies_processed) {
1091
3
        ProcessDependencies();
1092
3
    }
1093
52.7k
    m_pool->Apply(this);
1094
52.7k
    m_to_add.clear();
1095
52.7k
    m_to_remove.clear();
1096
52.7k
    m_entry_vec.clear();
1097
52.7k
    m_ancestors.clear();
1098
52.7k
}
1099
1100
void CTxMemPool::ChangeSet::ProcessDependencies()
1101
73.3k
{
1102
73.3k
    LOCK(m_pool->cs);
1103
73.3k
    Assume(!m_dependencies_processed); // should only call this once.
1104
73.9k
    for (const auto& entryptr : m_entry_vec) {
1105
100k
        for (const auto &txin : entryptr->GetSharedTx()->vin) {
1106
100k
            std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1107
100k
            if (!piter) {
1108
91.1k
                auto it = m_to_add.find(txin.prevout.hash);
1109
91.1k
                if (it != m_to_add.end()) {
1110
585
                    piter = std::make_optional(it);
1111
585
                }
1112
91.1k
            }
1113
100k
            if (piter) {
1114
10.3k
                m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1115
10.3k
            }
1116
100k
        }
1117
73.9k
    }
1118
73.3k
    m_dependencies_processed = true;
1119
73.3k
    return;
1120
73.3k
 }
1121
1122
bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1123
76.0k
{
1124
76.0k
    LOCK(m_pool->cs);
1125
76.0k
    if (!m_dependencies_processed) {
1126
73.3k
        ProcessDependencies();
1127
73.3k
    }
1128
1129
76.0k
    return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1130
76.0k
}
1131
1132
std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1133
145k
{
1134
145k
    FeePerWeight zero{};
1135
145k
    std::vector<FeePerWeight> ret;
1136
1137
145k
    ret.emplace_back(zero);
1138
1139
145k
    StartBlockBuilding();
1140
1141
145k
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1142
1143
145k
    FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1144
11.9M
    while (last_selection != FeePerWeight{}) {
1145
11.8M
        last_selection += ret.back();
1146
11.8M
        ret.emplace_back(last_selection);
1147
11.8M
        IncludeBuilderChunk();
1148
11.8M
        last_selection = GetBlockBuilderChunk(dummy);
1149
11.8M
    }
1150
145k
    StopBlockBuilding();
1151
145k
    return ret;
1152
145k
}