Coverage Report

Created: 2026-07-14 18:13

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