bitcoin core ipc fuzz coverage

Coverage Report

Created: 2026-08-26 16:12

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