Coverage Report

Created: 2026-07-29 23:27

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