Coverage Report

Created: 2026-04-29 19:21

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.49k
{
42
4.49k
    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.49k
    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.49k
        if (!active_chain.Contains(*lp.maxInputBlock)) {
49
230
            return false;
50
230
        }
51
4.49k
    }
52
53
    // LockPoints still valid
54
4.26k
    return true;
55
4.49k
}
56
57
std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetChildren(const CTxMemPoolEntry& entry) const
58
10.7M
{
59
10.7M
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
60
10.7M
    const auto& hash = entry.GetTx().GetHash();
61
10.7M
    {
62
10.7M
        LOCK(cs);
63
10.7M
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
64
10.9M
        for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
65
198k
            ret.emplace_back(*(iter->second));
66
198k
        }
67
10.7M
    }
68
10.7M
    std::ranges::sort(ret, CompareIteratorByHash{});
69
10.7M
    auto removed = std::ranges::unique(ret, [](auto& a, auto& b) noexcept { return &a.get() == &b.get(); });
70
10.7M
    ret.erase(removed.begin(), removed.end());
71
10.7M
    return ret;
72
10.7M
}
73
74
std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> CTxMemPool::GetParents(const CTxMemPoolEntry& entry) const
75
10.7M
{
76
10.7M
    LOCK(cs);
77
10.7M
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> ret;
78
10.7M
    std::set<Txid> inputs;
79
13.7M
    for (const auto& txin : entry.GetTx().vin) {
80
13.7M
        inputs.insert(txin.prevout.hash);
81
13.7M
    }
82
13.7M
    for (const auto& hash : inputs) {
83
13.7M
        std::optional<txiter> piter = GetIter(hash);
84
13.7M
        if (piter) {
85
197k
            ret.emplace_back(**piter);
86
197k
        }
87
13.7M
    }
88
10.7M
    return ret;
89
10.7M
}
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
783
        txiter it = mapTx.find(hash);
100
783
        if (it == mapTx.end()) {
101
0
            continue;
102
0
        }
103
783
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
104
783
        {
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
783
        }
113
783
    }
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
221
{
124
221
    LOCK(cs);
125
221
    auto entry = GetEntry(txid);
126
221
    if (!entry) return false;
127
220
    return m_txgraph->GetDescendants(*entry, TxGraph::Level::MAIN).size() > 1;
128
221
}
129
130
CTxMemPool::setEntries CTxMemPool::CalculateMemPoolAncestors(const CTxMemPoolEntry &entry) const
131
2.06k
{
132
2.06k
    auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
133
2.06k
    setEntries ret;
134
2.06k
    if (ancestors.size() > 0) {
135
14.2k
        for (auto ancestor : ancestors) {
136
14.2k
            if (ancestor != &entry) {
137
13.5k
                ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
138
13.5k
            }
139
14.2k
        }
140
759
        return ret;
141
759
    }
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.30k
    setEntries staged_parents;
146
1.30k
    const CTransaction &tx = entry.GetTx();
147
148
    // Get parents of this transaction that are in the mempool
149
2.95k
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
150
1.64k
        std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
151
1.64k
        if (piter) {
152
244
            staged_parents.insert(*piter);
153
244
        }
154
1.64k
    }
155
156
1.30k
    for (const auto& parent : staged_parents) {
157
218
        auto parent_ancestors = m_txgraph->GetAncestors(*parent, TxGraph::Level::MAIN);
158
607
        for (auto ancestor : parent_ancestors) {
159
607
            ret.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ancestor)));
160
607
        }
161
218
    }
162
163
1.30k
    return ret;
164
2.06k
}
165
166
static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
167
1.19k
{
168
1.19k
    opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
169
1.19k
    int64_t cluster_limit_bytes = opts.limits.cluster_size_vbytes * 40;
170
1.19k
    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.19k
    return std::move(opts);
174
1.19k
}
175
176
CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
177
1.19k
    : m_opts{Flatten(std::move(opts), error)}
178
1.19k
{
179
1.19k
    m_txgraph = MakeTxGraph(
180
1.19k
        /*max_cluster_count=*/m_opts.limits.cluster_count,
181
1.19k
        /*max_cluster_size=*/m_opts.limits.cluster_size_vbytes * WITNESS_SCALE_FACTOR,
182
1.19k
        /*acceptable_cost=*/ACCEPTABLE_COST,
183
75.5M
        /*fallback_order=*/[&](const TxGraph::Ref& a, const TxGraph::Ref& b) noexcept {
184
75.5M
            const Txid& txid_a = static_cast<const CTxMemPoolEntry&>(a).GetTx().GetHash();
185
75.5M
            const Txid& txid_b = static_cast<const CTxMemPoolEntry&>(b).GetTx().GetHash();
186
75.5M
            return txid_a <=> txid_b;
187
75.5M
        });
188
1.19k
}
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.08k
{
198
2.08k
    return nTransactionsUpdated;
199
2.08k
}
200
201
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
202
120k
{
203
120k
    nTransactionsUpdated += n;
204
120k
}
205
206
void CTxMemPool::Apply(ChangeSet* changeset)
207
51.9k
{
208
51.9k
    AssertLockHeld(cs);
209
51.9k
    m_txgraph->CommitStaging();
210
211
51.9k
    RemoveStaged(changeset->m_to_remove, MemPoolRemovalReason::REPLACED);
212
213
103k
    for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
214
51.9k
        auto tx_entry = changeset->m_entry_vec[i];
215
        // First splice this entry into mapTx.
216
51.9k
        auto node_handle = changeset->m_to_add.extract(tx_entry);
217
51.9k
        auto result = mapTx.insert(std::move(node_handle));
218
219
51.9k
        Assume(result.inserted);
220
51.9k
        txiter it = result.position;
221
222
51.9k
        addNewTransaction(it);
223
51.9k
    }
224
51.9k
    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
51.9k
}
228
229
void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit)
230
51.9k
{
231
51.9k
    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
51.9k
    cachedInnerUsage += entry.DynamicMemoryUsage();
237
238
51.9k
    const CTransaction& tx = newit->GetTx();
239
117k
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
240
65.2k
        mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, newit));
241
65.2k
    }
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
51.9k
    nTransactionsUpdated++;
250
51.9k
    totalTxSize += entry.GetTxSize();
251
51.9k
    m_total_fee += entry.GetFee();
252
253
51.9k
    txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
254
51.9k
    newit->idx_randomized = txns_randomized.size() - 1;
255
256
51.9k
    TRACEPOINT(mempool, added,
257
51.9k
        entry.GetTx().GetHash().data(),
258
51.9k
        entry.GetTxSize(),
259
51.9k
        entry.GetFee()
260
51.9k
    );
261
51.9k
}
262
263
void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
264
48.4k
{
265
    // We increment mempool sequence value no matter removal reason
266
    // even if not directly reported below.
267
48.4k
    uint64_t mempool_sequence = GetAndIncrementSequence();
268
269
48.4k
    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
1.96k
        m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
275
1.96k
    }
276
48.4k
    TRACEPOINT(mempool, removed,
277
48.4k
        it->GetTx().GetHash().data(),
278
48.4k
        RemovalReasonToString(reason).c_str(),
279
48.4k
        it->GetTxSize(),
280
48.4k
        it->GetFee(),
281
48.4k
        std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
282
48.4k
    );
283
284
48.4k
    for (const CTxIn& txin : it->GetTx().vin)
285
60.4k
        mapNextTx.erase(txin.prevout);
286
287
48.4k
    RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
288
289
48.4k
    if (txns_randomized.size() > 1) {
290
        // Remove entry from txns_randomized by replacing it with the back and deleting the back.
291
46.2k
        txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
292
46.2k
        txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
293
46.2k
        txns_randomized.pop_back();
294
46.2k
        if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
295
3.29k
            txns_randomized.shrink_to_fit();
296
3.29k
        }
297
46.2k
    } else {
298
2.17k
        txns_randomized.clear();
299
2.17k
    }
300
301
48.4k
    totalTxSize -= it->GetTxSize();
302
48.4k
    m_total_fee -= it->GetFee();
303
48.4k
    cachedInnerUsage -= it->DynamicMemoryUsage();
304
48.4k
    mapTx.erase(it);
305
48.4k
    nTransactionsUpdated++;
306
48.4k
}
307
308
// Calculates descendants of given entry and adds to setDescendants.
309
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
310
80.0k
{
311
80.0k
    (void)CalculateDescendants(*entryit, setDescendants);
312
80.0k
    return;
313
80.0k
}
314
315
CTxMemPool::txiter CTxMemPool::CalculateDescendants(const CTxMemPoolEntry& entry, setEntries& setDescendants) const
316
80.1k
{
317
283k
    for (auto tx : m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN)) {
318
283k
        setDescendants.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
319
283k
    }
320
80.1k
    return mapTx.iterator_to(entry);
321
80.1k
}
322
323
void CTxMemPool::removeRecursive(CTxMemPool::txiter to_remove, MemPoolRemovalReason reason)
324
161
{
325
161
    AssertLockHeld(cs);
326
161
    Assume(!m_have_changeset);
327
161
    auto descendants = m_txgraph->GetDescendants(*to_remove, TxGraph::Level::MAIN);
328
204
    for (auto tx: descendants) {
329
204
        removeUnchecked(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)), reason);
330
204
    }
331
161
}
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.39k
    for (txiter it = mapTx.begin(); it != mapTx.end(); it++) {
369
2.26k
        if (check_final_and_mature(it)) {
370
15
            to_remove.emplace_back(&*it);
371
15
        }
372
2.26k
    }
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.36k
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
381
2.23k
        assert(TestLockPointValidity(chain, it->GetLockPoints()));
382
2.23k
    }
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
58.9k
{
390
    // Remove transactions which depend on inputs of tx, recursively
391
58.9k
    AssertLockHeld(cs);
392
71.0k
    for (const CTxIn &txin : tx.vin) {
393
71.0k
        auto it = mapNextTx.find(txin.prevout);
394
71.0k
        if (it != mapNextTx.end()) {
395
154
            const CTransaction &txConflict = it->second->GetTx();
396
154
            if (Assume(txConflict.GetHash() != tx.GetHash()))
397
154
            {
398
154
                ClearPrioritisation(txConflict.GetHash());
399
154
                removeRecursive(it->second, MemPoolRemovalReason::CONFLICT);
400
154
            }
401
154
        }
402
71.0k
    }
403
58.9k
}
404
405
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
406
106k
{
407
    // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
408
106k
    AssertLockHeld(cs);
409
106k
    Assume(!m_have_changeset);
410
106k
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
411
106k
    if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
412
7.99k
        txs_removed_for_block.reserve(vtx.size());
413
58.9k
        for (const auto& tx : vtx) {
414
58.9k
            txiter it = mapTx.find(tx->GetHash());
415
58.9k
            if (it != mapTx.end()) {
416
46.4k
                txs_removed_for_block.emplace_back(*it);
417
46.4k
                removeUnchecked(it, MemPoolRemovalReason::BLOCK);
418
46.4k
            }
419
58.9k
            removeConflicts(*tx);
420
58.9k
            ClearPrioritisation(tx->GetHash());
421
58.9k
        }
422
7.99k
    }
423
106k
    if (m_opts.signals) {
424
106k
        m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
425
106k
    }
426
106k
    lastRollingFeeUpdate = GetTime();
427
106k
    blockSinceLastRollingFeeBump = true;
428
106k
    if (!m_txgraph->DoWork(/*max_cost=*/POST_CHANGE_COST)) {
429
0
        LogDebug(BCLog::MEMPOOL, "Mempool in non-optimal ordering after block.");
430
0
    }
431
106k
}
432
433
void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
434
130k
{
435
130k
    if (m_opts.check_ratio == 0) return;
436
437
128k
    if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
438
439
128k
    AssertLockHeld(::cs_main);
440
128k
    LOCK(cs);
441
128k
    LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
442
443
128k
    uint64_t checkTotal = 0;
444
128k
    CAmount check_total_fee{0};
445
128k
    CAmount check_total_modified_fee{0};
446
128k
    int64_t check_total_adjusted_weight{0};
447
128k
    uint64_t innerUsage = 0;
448
449
128k
    assert(!m_txgraph->IsOversized(TxGraph::Level::MAIN));
450
128k
    m_txgraph->SanityCheck();
451
452
128k
    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
453
454
128k
    const auto score_with_topo{GetSortedScoreWithTopology()};
455
456
    // Number of chunks is bounded by number of transactions.
457
128k
    const auto diagram{GetFeerateDiagram()};
458
128k
    assert(diagram.size() <= score_with_topo.size() + 1);
459
128k
    assert(diagram.size() >= 1);
460
461
128k
    std::optional<Wtxid> last_wtxid = std::nullopt;
462
128k
    auto diagram_iter = diagram.cbegin();
463
464
10.7M
    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
10.7M
        assert(diagram_iter->size >= check_total_adjusted_weight);
472
10.7M
        if (diagram_iter->fee == check_total_modified_fee &&
473
10.7M
                diagram_iter->size == check_total_adjusted_weight) {
474
10.6M
            ++diagram_iter;
475
10.6M
        }
476
10.7M
        checkTotal += it->GetTxSize();
477
10.7M
        check_total_adjusted_weight += it->GetAdjustedWeight();
478
10.7M
        check_total_fee += it->GetFee();
479
10.7M
        check_total_modified_fee += it->GetModifiedFee();
480
10.7M
        innerUsage += it->DynamicMemoryUsage();
481
10.7M
        const CTransaction& tx = it->GetTx();
482
483
        // CompareMiningScoreWithTopology should agree with GetSortedScoreWithTopology()
484
10.7M
        if (last_wtxid) {
485
10.6M
            assert(CompareMiningScoreWithTopology(*last_wtxid, tx.GetWitnessHash()));
486
10.6M
        }
487
10.7M
        last_wtxid = tx.GetWitnessHash();
488
489
10.7M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentCheck;
490
10.7M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setParentsStored;
491
13.7M
        for (const CTxIn &txin : tx.vin) {
492
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
493
13.7M
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
494
13.7M
            if (it2 != mapTx.end()) {
495
191k
                const CTransaction& tx2 = it2->GetTx();
496
191k
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
497
191k
                setParentCheck.insert(*it2);
498
191k
            }
499
            // We are iterating through the mempool entries sorted
500
            // topologically and by mining score. All parents must have been
501
            // checked before their children and their coins added to the
502
            // mempoolDuplicate coins cache.
503
13.7M
            assert(mempoolDuplicate.HaveCoin(txin.prevout));
504
            // Check whether its inputs are marked in mapNextTx.
505
13.7M
            auto it3 = mapNextTx.find(txin.prevout);
506
13.7M
            assert(it3 != mapNextTx.end());
507
13.7M
            assert(it3->first == &txin.prevout);
508
13.7M
            assert(&it3->second->GetTx() == &tx);
509
13.7M
        }
510
10.7M
        auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
511
382k
            return a.GetTx().GetHash() == b.GetTx().GetHash();
512
382k
        };
513
10.7M
        for (auto &txentry : GetParents(*it)) {
514
191k
            setParentsStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
515
191k
        }
516
10.7M
        assert(setParentCheck.size() == setParentsStored.size());
517
10.7M
        assert(std::equal(setParentCheck.begin(), setParentCheck.end(), setParentsStored.begin(), comp));
518
519
        // Check children against mapNextTx
520
10.7M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenCheck;
521
10.7M
        std::set<CTxMemPoolEntry::CTxMemPoolEntryRef, CompareIteratorByHash> setChildrenStored;
522
10.7M
        auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
523
10.8M
        for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
524
191k
            txiter childit = iter->second;
525
191k
            assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
526
191k
            setChildrenCheck.insert(*childit);
527
191k
        }
528
10.7M
        for (auto &txentry : GetChildren(*it)) {
529
191k
            setChildrenStored.insert(dynamic_cast<const CTxMemPoolEntry&>(txentry.get()));
530
191k
        }
531
10.7M
        assert(setChildrenCheck.size() == setChildrenStored.size());
532
10.7M
        assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), setChildrenStored.begin(), comp));
533
534
10.7M
        TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
535
10.7M
        CAmount txfee = 0;
536
10.7M
        assert(!tx.IsCoinBase());
537
10.7M
        assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
538
13.7M
        for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
539
10.7M
        AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
540
10.7M
    }
541
13.8M
    for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); it++) {
542
13.7M
        indexed_transaction_set::const_iterator it2 = it->second;
543
13.7M
        assert(it2 != mapTx.end());
544
13.7M
    }
545
546
128k
    ++diagram_iter;
547
128k
    assert(diagram_iter == diagram.cend());
548
549
128k
    assert(totalTxSize == checkTotal);
550
128k
    assert(m_total_fee == check_total_fee);
551
128k
    assert(diagram.back().fee == check_total_modified_fee);
552
128k
    assert(diagram.back().size == check_total_adjusted_weight);
553
128k
    assert(innerUsage == cachedInnerUsage);
554
128k
}
555
556
bool CTxMemPool::CompareMiningScoreWithTopology(const Wtxid& hasha, const Wtxid& hashb) const
557
10.6M
{
558
    /* Return `true` if hasha should be considered sooner than hashb, namely when:
559
     *     a is not in the mempool but b is, or
560
     *     both are in the mempool but a is sorted before b in the total mempool ordering
561
     *     (which takes dependencies and (chunk) feerates into account).
562
     */
563
10.6M
    LOCK(cs);
564
10.6M
    auto j{GetIter(hashb)};
565
10.6M
    if (!j.has_value()) return false;
566
10.6M
    auto i{GetIter(hasha)};
567
10.6M
    if (!i.has_value()) return true;
568
569
10.6M
    return m_txgraph->CompareMainOrder(*i.value(), *j.value()) < 0;
570
10.6M
}
571
572
std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedScoreWithTopology() const
573
138k
{
574
138k
    std::vector<indexed_transaction_set::const_iterator> iters;
575
138k
    AssertLockHeld(cs);
576
577
138k
    iters.reserve(mapTx.size());
578
579
11.1M
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
580
11.0M
        iters.push_back(mi);
581
11.0M
    }
582
126M
    std::sort(iters.begin(), iters.end(), [this](const auto& a, const auto& b) EXCLUSIVE_LOCKS_REQUIRED(cs) noexcept {
583
126M
        return m_txgraph->CompareMainOrder(*a, *b) < 0;
584
126M
    });
585
138k
    return iters;
586
138k
}
587
588
std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
589
9.14k
{
590
9.14k
    AssertLockHeld(cs);
591
592
9.14k
    std::vector<CTxMemPoolEntryRef> ret;
593
9.14k
    ret.reserve(mapTx.size());
594
304k
    for (const auto& it : GetSortedScoreWithTopology()) {
595
304k
        ret.emplace_back(*it);
596
304k
    }
597
9.14k
    return ret;
598
9.14k
}
599
600
std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
601
918
{
602
918
    LOCK(cs);
603
918
    auto iters = GetSortedScoreWithTopology();
604
605
918
    std::vector<TxMempoolInfo> ret;
606
918
    ret.reserve(mapTx.size());
607
1.21k
    for (auto it : iters) {
608
1.21k
        ret.push_back(GetInfo(it));
609
1.21k
    }
610
611
918
    return ret;
612
918
}
613
614
const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
615
3.00k
{
616
3.00k
    AssertLockHeld(cs);
617
3.00k
    const auto i = mapTx.find(txid);
618
3.00k
    return i == mapTx.end() ? nullptr : &(*i);
619
3.00k
}
620
621
CTransactionRef CTxMemPool::get(const Txid& hash) const
622
207k
{
623
207k
    LOCK(cs);
624
207k
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
625
207k
    if (i == mapTx.end())
626
150k
        return nullptr;
627
57.1k
    return i->GetSharedTx();
628
207k
}
629
630
void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
631
769
{
632
769
    {
633
769
        LOCK(cs);
634
769
        CAmount &delta = mapDeltas[hash];
635
769
        delta = SaturatingAdd(delta, nFeeDelta);
636
769
        txiter it = mapTx.find(hash);
637
769
        if (it != mapTx.end()) {
638
            // PrioritiseTransaction calls stack on previous ones. Set the new
639
            // transaction fee to be current modified fee + feedelta.
640
262
            it->UpdateModifiedFee(nFeeDelta);
641
262
            m_txgraph->SetTransactionFee(*it, it->GetModifiedFee());
642
262
            ++nTransactionsUpdated;
643
262
        }
644
769
        if (delta == 0) {
645
9
            mapDeltas.erase(hash);
646
9
            LogInfo("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
647
760
        } else {
648
760
            LogInfo("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
649
760
                      hash.ToString(),
650
760
                      it == mapTx.end() ? "not " : "",
651
760
                      FormatMoney(nFeeDelta),
652
760
                      FormatMoney(delta));
653
760
        }
654
769
    }
655
769
}
656
657
void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
658
63.2k
{
659
63.2k
    AssertLockHeld(cs);
660
63.2k
    std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
661
63.2k
    if (pos == mapDeltas.end())
662
63.1k
        return;
663
41
    const CAmount &delta = pos->second;
664
41
    nFeeDelta += delta;
665
41
}
666
667
void CTxMemPool::ClearPrioritisation(const Txid& hash)
668
59.0k
{
669
59.0k
    AssertLockHeld(cs);
670
59.0k
    mapDeltas.erase(hash);
671
59.0k
}
672
673
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
674
31
{
675
31
    AssertLockNotHeld(cs);
676
31
    LOCK(cs);
677
31
    std::vector<delta_info> result;
678
31
    result.reserve(mapDeltas.size());
679
31
    for (const auto& [txid, delta] : mapDeltas) {
680
30
        const auto iter{mapTx.find(txid)};
681
30
        const bool in_mempool{iter != mapTx.end()};
682
30
        std::optional<CAmount> modified_fee;
683
30
        if (in_mempool) modified_fee = iter->GetModifiedFee();
684
30
        result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
685
30
    }
686
31
    return result;
687
31
}
688
689
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
690
106k
{
691
106k
    const auto it = mapNextTx.find(prevout);
692
106k
    return it == mapNextTx.end() ? nullptr : &(it->second->GetTx());
693
106k
}
694
695
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
696
13.9M
{
697
13.9M
    AssertLockHeld(cs);
698
13.9M
    auto it = mapTx.find(txid);
699
13.9M
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
700
13.9M
}
701
702
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
703
21.4M
{
704
21.4M
    AssertLockHeld(cs);
705
21.4M
    auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
706
21.4M
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
707
21.4M
}
708
709
CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
710
32.9k
{
711
32.9k
    CTxMemPool::setEntries ret;
712
32.9k
    for (const auto& h : hashes) {
713
2.32k
        const auto mi = GetIter(h);
714
2.32k
        if (mi) ret.insert(*mi);
715
2.32k
    }
716
32.9k
    return ret;
717
32.9k
}
718
719
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
720
2
{
721
2
    AssertLockHeld(cs);
722
2
    std::vector<txiter> ret;
723
2
    ret.reserve(txids.size());
724
563
    for (const auto& txid : txids) {
725
563
        const auto it{GetIter(txid)};
726
563
        if (!it) return {};
727
563
        ret.push_back(*it);
728
563
    }
729
2
    return ret;
730
2
}
731
732
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
733
25.3k
{
734
58.4k
    for (unsigned int i = 0; i < tx.vin.size(); i++)
735
36.1k
        if (exists(tx.vin[i].prevout.hash))
736
3.05k
            return false;
737
22.3k
    return true;
738
25.3k
}
739
740
41.1k
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
741
742
std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
743
61.7k
{
744
    // Check to see if the inputs are made available by another tx in the package.
745
    // These Coins would not be available in the underlying CoinsView.
746
61.7k
    if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
747
615
        return it->second;
748
615
    }
749
750
    // If an entry in the mempool exists, always return that one, as it's guaranteed to never
751
    // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
752
    // transactions. First checking the underlying cache risks returning a pruned entry instead.
753
61.1k
    CTransactionRef ptx = mempool.get(outpoint.hash);
754
61.1k
    if (ptx) {
755
8.18k
        if (outpoint.n < ptx->vout.size()) {
756
8.18k
            Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
757
8.18k
            m_non_base_coins.emplace(outpoint);
758
8.18k
            return coin;
759
8.18k
        }
760
0
        return std::nullopt;
761
8.18k
    }
762
52.9k
    return base->GetCoin(outpoint);
763
61.1k
}
764
765
void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
766
778
{
767
1.59k
    for (unsigned int n = 0; n < tx->vout.size(); ++n) {
768
815
        m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
769
815
        m_non_base_coins.emplace(tx->GetHash(), n);
770
815
    }
771
778
}
772
void CCoinsViewMemPool::Reset()
773
64.4k
{
774
64.4k
    m_temp_added.clear();
775
64.4k
    m_non_base_coins.clear();
776
64.4k
}
777
778
461k
size_t CTxMemPool::DynamicMemoryUsage() const {
779
461k
    LOCK(cs);
780
    // 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.
781
461k
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 9 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + m_txgraph->GetMainMemoryUsage() + cachedInnerUsage;
782
461k
}
783
784
61.7k
void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
785
61.7k
    LOCK(cs);
786
787
61.7k
    if (m_unbroadcast_txids.erase(txid))
788
11.1k
    {
789
11.1k
        LogDebug(BCLog::MEMPOOL, "Removed %s from set of unbroadcast txns%s", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
790
11.1k
    }
791
61.7k
}
792
793
78.5k
void CTxMemPool::RemoveStaged(setEntries &stage, MemPoolRemovalReason reason) {
794
78.5k
    AssertLockHeld(cs);
795
78.5k
    for (txiter it : stage) {
796
1.59k
        removeUnchecked(it, reason);
797
1.59k
    }
798
78.5k
}
799
800
bool CTxMemPool::CheckPolicyLimits(const CTransactionRef& tx)
801
3.45k
{
802
3.45k
    LOCK(cs);
803
    // Use ChangeSet interface to check whether the cluster count
804
    // limits would be violated. Note that the changeset will be destroyed
805
    // when it goes out of scope.
806
3.45k
    auto changeset = GetChangeSet();
807
3.45k
    (void) changeset->StageAddition(tx, /*fee=*/0, /*time=*/0, /*entry_height=*/0, /*entry_sequence=*/0, /*spends_coinbase=*/false, /*sigops_cost=*/0, LockPoints{});
808
3.45k
    return changeset->CheckMemPoolPolicyLimits();
809
3.45k
}
810
811
int CTxMemPool::Expire(std::chrono::seconds time)
812
26.6k
{
813
26.6k
    AssertLockHeld(cs);
814
26.6k
    Assume(!m_have_changeset);
815
26.6k
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
816
26.6k
    setEntries toremove;
817
26.6k
    while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
818
4
        toremove.insert(mapTx.project<0>(it));
819
4
        it++;
820
4
    }
821
26.6k
    setEntries stage;
822
26.6k
    for (txiter removeit : toremove) {
823
4
        CalculateDescendants(removeit, stage);
824
4
    }
825
26.6k
    RemoveStaged(stage, MemPoolRemovalReason::EXPIRY);
826
26.6k
    return stage.size();
827
26.6k
}
828
829
408k
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
830
408k
    LOCK(cs);
831
408k
    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
832
408k
        return CFeeRate(llround(rollingMinimumFeeRate));
833
834
201
    int64_t time = GetTime();
835
201
    if (time > lastRollingFeeUpdate + 10) {
836
6
        double halflife = ROLLING_FEE_HALFLIFE;
837
6
        if (DynamicMemoryUsage() < sizelimit / 4)
838
1
            halflife /= 4;
839
5
        else if (DynamicMemoryUsage() < sizelimit / 2)
840
1
            halflife /= 2;
841
842
6
        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
843
6
        lastRollingFeeUpdate = time;
844
845
6
        if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
846
1
            rollingMinimumFeeRate = 0;
847
1
            return CFeeRate(0);
848
1
        }
849
6
    }
850
200
    return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
851
201
}
852
853
43
void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
854
43
    AssertLockHeld(cs);
855
43
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
856
41
        rollingMinimumFeeRate = rate.GetFeePerK();
857
41
        blockSinceLastRollingFeeBump = false;
858
41
    }
859
43
}
860
861
26.6k
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
862
26.6k
    AssertLockHeld(cs);
863
26.6k
    Assume(!m_have_changeset);
864
865
26.6k
    unsigned nTxnRemoved = 0;
866
26.6k
    CFeeRate maxFeeRateRemoved(0);
867
868
26.6k
    while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
869
43
        const auto &[worst_chunk, feeperweight] = m_txgraph->GetWorstMainChunk();
870
43
        FeePerVSize feerate = ToFeePerVSize(feeperweight);
871
43
        CFeeRate removed{feerate.fee, feerate.size};
872
873
        // We set the new mempool min fee to the feerate of the removed set, plus the
874
        // "minimum reasonable fee rate" (ie some value under which we consider txn
875
        // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
876
        // equal to txn which were removed with no block in between.
877
43
        removed += m_opts.incremental_relay_feerate;
878
43
        trackPackageRemoved(removed);
879
43
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
880
881
43
        nTxnRemoved += worst_chunk.size();
882
883
43
        std::vector<CTransaction> txn;
884
43
        if (pvNoSpendsRemaining) {
885
35
            txn.reserve(worst_chunk.size());
886
36
            for (auto ref : worst_chunk) {
887
36
                txn.emplace_back(static_cast<const CTxMemPoolEntry&>(*ref).GetTx());
888
36
            }
889
35
        }
890
891
43
        setEntries stage;
892
49
        for (auto ref : worst_chunk) {
893
49
            stage.insert(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*ref)));
894
49
        }
895
49
        for (auto e : stage) {
896
49
            removeUnchecked(e, MemPoolRemovalReason::SIZELIMIT);
897
49
        }
898
43
        if (pvNoSpendsRemaining) {
899
36
            for (const CTransaction& tx : txn) {
900
36
                for (const CTxIn& txin : tx.vin) {
901
36
                    if (exists(txin.prevout.hash)) continue;
902
35
                    pvNoSpendsRemaining->push_back(txin.prevout);
903
35
                }
904
36
            }
905
35
        }
906
43
    }
907
908
26.6k
    if (maxFeeRateRemoved > CFeeRate(0)) {
909
35
        LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
910
35
    }
911
26.6k
}
912
913
std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateAncestorData(const CTxMemPoolEntry& entry) const
914
124k
{
915
124k
    auto ancestors = m_txgraph->GetAncestors(entry, TxGraph::Level::MAIN);
916
917
124k
    size_t ancestor_count = ancestors.size();
918
124k
    size_t ancestor_size = 0;
919
124k
    CAmount ancestor_fees = 0;
920
320k
    for (auto tx: ancestors) {
921
320k
        const CTxMemPoolEntry& anc = static_cast<const CTxMemPoolEntry&>(*tx);
922
320k
        ancestor_size += anc.GetTxSize();
923
320k
        ancestor_fees += anc.GetModifiedFee();
924
320k
    }
925
124k
    return {ancestor_count, ancestor_size, ancestor_fees};
926
124k
}
927
928
std::tuple<size_t, size_t, CAmount> CTxMemPool::CalculateDescendantData(const CTxMemPoolEntry& entry) const
929
8.06k
{
930
8.06k
    auto descendants = m_txgraph->GetDescendants(entry, TxGraph::Level::MAIN);
931
8.06k
    size_t descendant_count = descendants.size();
932
8.06k
    size_t descendant_size = 0;
933
8.06k
    CAmount descendant_fees = 0;
934
935
153k
    for (auto tx: descendants) {
936
153k
        const CTxMemPoolEntry &desc = static_cast<const CTxMemPoolEntry&>(*tx);
937
153k
        descendant_size += desc.GetTxSize();
938
153k
        descendant_fees += desc.GetModifiedFee();
939
153k
    }
940
8.06k
    return {descendant_count, descendant_size, descendant_fees};
941
8.06k
}
942
943
583k
void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& cluster_count, size_t* const ancestorsize, CAmount* const ancestorfees) const {
944
583k
    LOCK(cs);
945
583k
    auto it = mapTx.find(txid);
946
583k
    ancestors = cluster_count = 0;
947
583k
    if (it != mapTx.end()) {
948
47.7k
        auto [ancestor_count, ancestor_size, ancestor_fees] = CalculateAncestorData(*it);
949
47.7k
        ancestors = ancestor_count;
950
47.7k
        if (ancestorsize) *ancestorsize = ancestor_size;
951
47.7k
        if (ancestorfees) *ancestorfees = ancestor_fees;
952
47.7k
        cluster_count = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN).size();
953
47.7k
    }
954
583k
}
955
956
bool CTxMemPool::GetLoadTried() const
957
2.47k
{
958
2.47k
    LOCK(cs);
959
2.47k
    return m_load_tried;
960
2.47k
}
961
962
void CTxMemPool::SetLoadTried(bool load_tried)
963
998
{
964
998
    LOCK(cs);
965
998
    m_load_tried = load_tried;
966
998
}
967
968
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
969
3.09k
{
970
3.09k
    AssertLockHeld(cs);
971
972
3.09k
    std::vector<CTxMemPool::txiter> ret;
973
3.09k
    std::set<const CTxMemPoolEntry*> unique_cluster_representatives;
974
49.6k
    for (auto txid : txids) {
975
49.6k
        auto it = mapTx.find(txid);
976
49.6k
        if (it != mapTx.end()) {
977
            // Note that TxGraph::GetCluster will return results in graph
978
            // order, which is deterministic (as long as we are not modifying
979
            // the graph).
980
49.6k
            auto cluster = m_txgraph->GetCluster(*it, TxGraph::Level::MAIN);
981
49.6k
            if (unique_cluster_representatives.insert(static_cast<const CTxMemPoolEntry*>(&(**cluster.begin()))).second) {
982
69.5k
                for (auto tx : cluster) {
983
69.5k
                    ret.emplace_back(mapTx.iterator_to(static_cast<const CTxMemPoolEntry&>(*tx)));
984
69.5k
                }
985
49.4k
            }
986
49.6k
        }
987
49.6k
    }
988
3.09k
    if (ret.size() > 500) {
989
1
        return {};
990
1
    }
991
3.09k
    return ret;
992
3.09k
}
993
994
util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
995
1.33k
{
996
1.33k
    LOCK(m_pool->cs);
997
998
1.33k
    if (!CheckMemPoolPolicyLimits()) {
999
0
        return util::Error{Untranslated("cluster size limit exceeded")};
1000
0
    }
1001
1002
1.33k
    return m_pool->m_txgraph->GetMainStagingDiagrams();
1003
1.33k
}
1004
1005
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)
1006
63.2k
{
1007
63.2k
    LOCK(m_pool->cs);
1008
63.2k
    Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1009
63.2k
    Assume(!m_dependencies_processed);
1010
1011
    // We need to process dependencies after adding a new transaction.
1012
63.2k
    m_dependencies_processed = false;
1013
1014
63.2k
    CAmount delta{0};
1015
63.2k
    m_pool->ApplyDelta(tx->GetHash(), delta);
1016
1017
63.2k
    FeePerWeight feerate(fee, GetSigOpsAdjustedWeight(GetTransactionWeight(*tx), sigops_cost, ::nBytesPerSigOp));
1018
63.2k
    auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1019
63.2k
    m_pool->m_txgraph->AddTransaction(const_cast<CTxMemPoolEntry&>(*newit), feerate);
1020
63.2k
    if (delta) {
1021
41
        newit->UpdateModifiedFee(delta);
1022
41
        m_pool->m_txgraph->SetTransactionFee(*newit, newit->GetModifiedFee());
1023
41
    }
1024
1025
63.2k
    m_entry_vec.push_back(newit);
1026
1027
63.2k
    return newit;
1028
63.2k
}
1029
1030
void CTxMemPool::ChangeSet::StageRemoval(CTxMemPool::txiter it)
1031
2.18k
{
1032
2.18k
    LOCK(m_pool->cs);
1033
2.18k
    m_pool->m_txgraph->RemoveTransaction(*it);
1034
2.18k
    m_to_remove.insert(it);
1035
2.18k
}
1036
1037
void CTxMemPool::ChangeSet::Apply()
1038
51.9k
{
1039
51.9k
    LOCK(m_pool->cs);
1040
51.9k
    if (!m_dependencies_processed) {
1041
3
        ProcessDependencies();
1042
3
    }
1043
51.9k
    m_pool->Apply(this);
1044
51.9k
    m_to_add.clear();
1045
51.9k
    m_to_remove.clear();
1046
51.9k
    m_entry_vec.clear();
1047
51.9k
    m_ancestors.clear();
1048
51.9k
}
1049
1050
void CTxMemPool::ChangeSet::ProcessDependencies()
1051
62.2k
{
1052
62.2k
    LOCK(m_pool->cs);
1053
62.2k
    Assume(!m_dependencies_processed); // should only call this once.
1054
62.8k
    for (const auto& entryptr : m_entry_vec) {
1055
89.4k
        for (const auto &txin : entryptr->GetSharedTx()->vin) {
1056
89.4k
            std::optional<txiter> piter = m_pool->GetIter(txin.prevout.hash);
1057
89.4k
            if (!piter) {
1058
79.9k
                auto it = m_to_add.find(txin.prevout.hash);
1059
79.9k
                if (it != m_to_add.end()) {
1060
585
                    piter = std::make_optional(it);
1061
585
                }
1062
79.9k
            }
1063
89.4k
            if (piter) {
1064
10.1k
                m_pool->m_txgraph->AddDependency(/*parent=*/**piter, /*child=*/*entryptr);
1065
10.1k
            }
1066
89.4k
        }
1067
62.8k
    }
1068
62.2k
    m_dependencies_processed = true;
1069
62.2k
    return;
1070
62.2k
 }
1071
1072
bool CTxMemPool::ChangeSet::CheckMemPoolPolicyLimits()
1073
64.9k
{
1074
64.9k
    LOCK(m_pool->cs);
1075
64.9k
    if (!m_dependencies_processed) {
1076
62.2k
        ProcessDependencies();
1077
62.2k
    }
1078
1079
64.9k
    return !m_pool->m_txgraph->IsOversized(TxGraph::Level::TOP);
1080
64.9k
}
1081
1082
std::vector<FeePerWeight> CTxMemPool::GetFeerateDiagram() const
1083
128k
{
1084
128k
    FeePerWeight zero{};
1085
128k
    std::vector<FeePerWeight> ret;
1086
1087
128k
    ret.emplace_back(zero);
1088
1089
128k
    StartBlockBuilding();
1090
1091
128k
    std::vector<CTxMemPoolEntry::CTxMemPoolEntryRef> dummy;
1092
1093
128k
    FeePerWeight last_selection = GetBlockBuilderChunk(dummy);
1094
10.8M
    while (last_selection != FeePerWeight{}) {
1095
10.6M
        last_selection += ret.back();
1096
10.6M
        ret.emplace_back(last_selection);
1097
10.6M
        IncludeBuilderChunk();
1098
10.6M
        last_selection = GetBlockBuilderChunk(dummy);
1099
10.6M
    }
1100
128k
    StopBlockBuilding();
1101
128k
    return ret;
1102
128k
}