Coverage Report

Created: 2026-09-15 16:03

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