Coverage Report

Created: 2026-07-23 20:35

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