fuzz coverage

Coverage Report

Created: 2025-10-29 15:27

/Users/eugenesiegel/btc/bitcoin/src/txmempool.cpp
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-2022 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 <logging.h>
15
#include <policy/policy.h>
16
#include <policy/settings.h>
17
#include <random.h>
18
#include <tinyformat.h>
19
#include <util/check.h>
20
#include <util/feefrac.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
137
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
void CTxMemPool::UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
58
                                      const std::set<Txid>& setExclude, std::set<Txid>& descendants_to_remove)
59
0
{
60
0
    CTxMemPoolEntry::Children stageEntries, descendants;
61
0
    stageEntries = updateIt->GetMemPoolChildrenConst();
62
63
0
    while (!stageEntries.empty()) {
64
0
        const CTxMemPoolEntry& descendant = *stageEntries.begin();
65
0
        descendants.insert(descendant);
66
0
        stageEntries.erase(descendant);
67
0
        const CTxMemPoolEntry::Children& children = descendant.GetMemPoolChildrenConst();
68
0
        for (const CTxMemPoolEntry& childEntry : children) {
69
0
            cacheMap::iterator cacheIt = cachedDescendants.find(mapTx.iterator_to(childEntry));
70
0
            if (cacheIt != cachedDescendants.end()) {
71
                // We've already calculated this one, just add the entries for this set
72
                // but don't traverse again.
73
0
                for (txiter cacheEntry : cacheIt->second) {
74
0
                    descendants.insert(*cacheEntry);
75
0
                }
76
0
            } else if (!descendants.count(childEntry)) {
77
                // Schedule for later processing
78
0
                stageEntries.insert(childEntry);
79
0
            }
80
0
        }
81
0
    }
82
    // descendants now contains all in-mempool descendants of updateIt.
83
    // Update and add to cached descendant map
84
0
    int32_t modifySize = 0;
85
0
    CAmount modifyFee = 0;
86
0
    int64_t modifyCount = 0;
87
0
    for (const CTxMemPoolEntry& descendant : descendants) {
88
0
        if (!setExclude.count(descendant.GetTx().GetHash())) {
89
0
            modifySize += descendant.GetTxSize();
90
0
            modifyFee += descendant.GetModifiedFee();
91
0
            modifyCount++;
92
0
            cachedDescendants[updateIt].insert(mapTx.iterator_to(descendant));
93
            // Update ancestor state for each descendant
94
0
            mapTx.modify(mapTx.iterator_to(descendant), [=](CTxMemPoolEntry& e) {
95
0
              e.UpdateAncestorState(updateIt->GetTxSize(), updateIt->GetModifiedFee(), 1, updateIt->GetSigOpCost());
96
0
            });
97
            // Don't directly remove the transaction here -- doing so would
98
            // invalidate iterators in cachedDescendants. Mark it for removal
99
            // by inserting into descendants_to_remove.
100
0
            if (descendant.GetCountWithAncestors() > uint64_t(m_opts.limits.ancestor_count) || descendant.GetSizeWithAncestors() > m_opts.limits.ancestor_size_vbytes) {
101
0
                descendants_to_remove.insert(descendant.GetTx().GetHash());
102
0
            }
103
0
        }
104
0
    }
105
0
    mapTx.modify(updateIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); });
106
0
}
107
108
void CTxMemPool::UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate)
109
78
{
110
78
    AssertLockHeld(cs);
Line
Count
Source
137
78
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
111
    // For each entry in vHashesToUpdate, store the set of in-mempool, but not
112
    // in-vHashesToUpdate transactions, so that we don't have to recalculate
113
    // descendants when we come across a previously seen entry.
114
78
    cacheMap mapMemPoolDescendantsToUpdate;
115
116
    // Use a set for lookups into vHashesToUpdate (these entries are already
117
    // accounted for in the state of their ancestors)
118
78
    std::set<Txid> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
119
120
78
    std::set<Txid> descendants_to_remove;
121
122
    // Iterate in reverse, so that whenever we are looking at a transaction
123
    // we are sure that all in-mempool descendants have already been processed.
124
    // This maximizes the benefit of the descendant cache and guarantees that
125
    // CTxMemPoolEntry::m_children will be updated, an assumption made in
126
    // UpdateForDescendants.
127
78
    for (const Txid& hash : vHashesToUpdate | std::views::reverse) {
128
        // calculate children from mapNextTx
129
0
        txiter it = mapTx.find(hash);
130
0
        if (it == mapTx.end()) {
131
0
            continue;
132
0
        }
133
0
        auto iter = mapNextTx.lower_bound(COutPoint(hash, 0));
134
        // First calculate the children, and update CTxMemPoolEntry::m_children to
135
        // include them, and update their CTxMemPoolEntry::m_parents to include this tx.
136
        // we cache the in-mempool children to avoid duplicate updates
137
0
        {
138
0
            WITH_FRESH_EPOCH(m_epoch);
Line
Count
Source
100
0
#define WITH_FRESH_EPOCH(epoch) const Epoch::Guard UNIQUE_NAME(epoch_guard_)(epoch)
Line
Count
Source
11
0
#define 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
139
0
            for (; iter != mapNextTx.end() && iter->first->hash == hash; ++iter) {
140
0
                const Txid &childHash = iter->second->GetHash();
141
0
                txiter childIter = mapTx.find(childHash);
142
0
                assert(childIter != mapTx.end());
143
                // We can skip updating entries we've encountered before or that
144
                // are in the block (which are already accounted for).
145
0
                if (!visited(childIter) && !setAlreadyIncluded.count(childHash)) {
146
0
                    UpdateChild(it, childIter, true);
147
0
                    UpdateParent(childIter, it, true);
148
0
                }
149
0
            }
150
0
        } // release epoch guard for UpdateForDescendants
151
0
        UpdateForDescendants(it, mapMemPoolDescendantsToUpdate, setAlreadyIncluded, descendants_to_remove);
152
0
    }
153
154
78
    for (const auto& txid : descendants_to_remove) {
155
        // This txid may have been removed already in a prior call to removeRecursive.
156
        // Therefore we ensure it is not yet removed already.
157
0
        if (const std::optional<txiter> txiter = GetIter(txid)) {
158
0
            removeRecursive((*txiter)->GetTx(), MemPoolRemovalReason::SIZELIMIT);
159
0
        }
160
0
    }
161
78
}
162
163
util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateAncestorsAndCheckLimits(
164
    int64_t entry_size,
165
    size_t entry_count,
166
    CTxMemPoolEntry::Parents& staged_ancestors,
167
    const Limits& limits) const
168
17.3M
{
169
17.3M
    int64_t totalSizeWithAncestors = entry_size;
170
17.3M
    setEntries ancestors;
171
172
47.5M
    while (!staged_ancestors.empty()) {
173
30.2M
        const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
174
30.2M
        txiter stageit = mapTx.iterator_to(stage);
175
176
30.2M
        ancestors.insert(stageit);
177
30.2M
        staged_ancestors.erase(stage);
178
30.2M
        totalSizeWithAncestors += stageit->GetTxSize();
179
180
30.2M
        if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
181
0
            return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
Line
Count
Source
1172
0
#define strprintf tfm::format
182
30.2M
        } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
183
0
            return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
184
30.2M
        } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
185
0
            return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
Line
Count
Source
1172
0
#define strprintf tfm::format
186
0
        }
187
188
30.2M
        const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
189
30.2M
        for (const CTxMemPoolEntry& parent : parents) {
190
19.3M
            txiter parent_it = mapTx.iterator_to(parent);
191
192
            // If this is a new ancestor, add it.
193
19.3M
            if (ancestors.count(parent_it) == 0) {
194
19.3M
                staged_ancestors.insert(parent);
195
19.3M
            }
196
19.3M
            if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
197
0
                return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
198
0
            }
199
19.3M
        }
200
30.2M
    }
201
202
17.3M
    return ancestors;
203
17.3M
}
204
205
util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
206
                                                  const int64_t total_vsize) const
207
0
{
208
0
    size_t pack_count = package.size();
209
210
    // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
211
0
    if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
212
0
        return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
213
0
    } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
214
0
        return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
215
0
    } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
216
0
        return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
Line
Count
Source
1172
0
#define strprintf tfm::format
217
0
    } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
218
0
        return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_opts.limits.descendant_size_vbytes))};
Line
Count
Source
1172
0
#define strprintf tfm::format
219
0
    }
220
221
0
    CTxMemPoolEntry::Parents staged_ancestors;
222
0
    for (const auto& tx : package) {
223
0
        for (const auto& input : tx->vin) {
224
0
            std::optional<txiter> piter = GetIter(input.prevout.hash);
225
0
            if (piter) {
226
0
                staged_ancestors.insert(**piter);
227
0
                if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
228
0
                    return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_opts.limits.ancestor_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
229
0
                }
230
0
            }
231
0
        }
232
0
    }
233
    // When multiple transactions are passed in, the ancestors and descendants of all transactions
234
    // considered together must be within limits even if they are not interdependent. This may be
235
    // stricter than the limits for each individual transaction.
236
0
    const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
237
0
                                                          staged_ancestors, m_opts.limits)};
238
    // It's possible to overestimate the ancestor/descendant totals.
239
0
    if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
240
0
    return {};
241
0
}
242
243
util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
244
    const CTxMemPoolEntry &entry,
245
    const Limits& limits,
246
    bool fSearchForParents /* = true */) const
247
17.3M
{
248
17.3M
    CTxMemPoolEntry::Parents staged_ancestors;
249
17.3M
    const CTransaction &tx = entry.GetTx();
250
251
17.3M
    if (fSearchForParents) {
252
        // Get parents of this transaction that are in the mempool
253
        // GetMemPoolParents() is only valid for entries in the mempool, so we
254
        // iterate mapTx to find parents.
255
34.3M
        for (unsigned int i = 0; i < tx.vin.size(); 
i++17.1M
) {
256
17.1M
            std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257
17.1M
            if (piter) {
258
10.8M
                staged_ancestors.insert(**piter);
259
10.8M
                if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
260
0
                    return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
Line
Count
Source
1172
0
#define strprintf tfm::format
261
0
                }
262
10.8M
            }
263
17.1M
        }
264
17.1M
    } else {
265
        // If we're not searching for parents, we require this to already be an
266
        // entry in the mempool and use the entry's cached parents.
267
160k
        txiter it = mapTx.iterator_to(entry);
268
160k
        staged_ancestors = it->GetMemPoolParentsConst();
269
160k
    }
270
271
17.3M
    return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272
17.3M
                                            limits);
273
17.3M
}
274
275
CTxMemPool::setEntries CTxMemPool::AssumeCalculateMemPoolAncestors(
276
    std::string_view calling_fn_name,
277
    const CTxMemPoolEntry &entry,
278
    const Limits& limits,
279
    bool fSearchForParents /* = true */) const
280
16.6M
{
281
16.6M
    auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282
16.6M
    if (!Assume(result)) {
Line
Count
Source
118
16.6M
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
283
0
        LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
Line
Count
Source
373
0
    do {                                                              \
374
0
        if (LogAcceptCategory((category), (level))) {                 \
375
0
            bool rate_limit{level >= BCLog::Level::Info};             \
376
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
377
0
        }                                                             \
378
0
    } while (0)
284
0
                      calling_fn_name, util::ErrorString(result).original);
285
0
    }
286
16.6M
    return std::move(result).value_or(CTxMemPool::setEntries{});
287
16.6M
}
288
289
void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290
654k
{
291
654k
    const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292
    // add or remove this tx as a child of each parent
293
654k
    for (const CTxMemPoolEntry& parent : parents) {
294
361k
        UpdateChild(mapTx.iterator_to(parent), it, add);
295
361k
    }
296
654k
    const int32_t updateCount = (add ? 
1493k
:
-1160k
);
297
654k
    const int32_t updateSize{updateCount * it->GetTxSize()};
298
654k
    const CAmount updateFee = updateCount * it->GetModifiedFee();
299
1.00M
    for (txiter ancestorIt : setAncestors) {
300
1.00M
        mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301
1.00M
    }
302
654k
}
303
304
void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
305
493k
{
306
493k
    int64_t updateCount = setAncestors.size();
307
493k
    int64_t updateSize = 0;
308
493k
    CAmount updateFee = 0;
309
493k
    int64_t updateSigOpsCost = 0;
310
886k
    for (txiter ancestorIt : setAncestors) {
311
886k
        updateSize += ancestorIt->GetTxSize();
312
886k
        updateFee += ancestorIt->GetModifiedFee();
313
886k
        updateSigOpsCost += ancestorIt->GetSigOpCost();
314
886k
    }
315
493k
    mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316
493k
}
317
318
void CTxMemPool::UpdateChildrenForRemoval(txiter it)
319
160k
{
320
160k
    const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321
160k
    for (const CTxMemPoolEntry& updateIt : children) {
322
65.6k
        UpdateParent(mapTx.iterator_to(updateIt), it, false);
323
65.6k
    }
324
160k
}
325
326
void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
327
1.08M
{
328
    // For each entry, walk back all ancestors and decrement size associated with this
329
    // transaction
330
1.08M
    if (updateDescendants) {
331
        // updateDescendants should be true whenever we're not recursively
332
        // removing a tx and all its descendants, eg when a transaction is
333
        // confirmed in a block.
334
        // Here we only update statistics and not data in CTxMemPool::Parents
335
        // and CTxMemPoolEntry::Children (which we need to preserve until we're
336
        // finished with all operations that need to traverse the mempool).
337
95.1k
        for (txiter removeIt : entriesToRemove) {
338
95.1k
            setEntries setDescendants;
339
95.1k
            CalculateDescendants(removeIt, setDescendants);
340
95.1k
            setDescendants.erase(removeIt); // don't update state for self
341
95.1k
            int32_t modifySize = -removeIt->GetTxSize();
342
95.1k
            CAmount modifyFee = -removeIt->GetModifiedFee();
343
95.1k
            int modifySigOps = -removeIt->GetSigOpCost();
344
190k
            for (txiter dit : setDescendants) {
345
190k
                mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
346
190k
            }
347
95.1k
        }
348
95.1k
    }
349
1.08M
    for (txiter removeIt : entriesToRemove) {
350
160k
        const CTxMemPoolEntry &entry = *removeIt;
351
        // Since this is a tx that is already in the mempool, we can call CMPA
352
        // with fSearchForParents = false.  If the mempool is in a consistent
353
        // state, then using true or false should both be correct, though false
354
        // should be a bit faster.
355
        // However, if we happen to be in the middle of processing a reorg, then
356
        // the mempool can be in an inconsistent state.  In this case, the set
357
        // of ancestors reachable via GetMemPoolParents()/GetMemPoolChildren()
358
        // will be the same as the set of ancestors whose packages include this
359
        // transaction, because when we add a new transaction to the mempool in
360
        // addNewTransaction(), we assume it has no children, and in the case of a
361
        // reorg where that assumption is false, the in-mempool children aren't
362
        // linked to the in-block tx's until UpdateTransactionsFromBlock() is
363
        // called.
364
        // So if we're being called during a reorg, ie before
365
        // UpdateTransactionsFromBlock() has been called, then
366
        // GetMemPoolParents()/GetMemPoolChildren() will differ from the set of
367
        // mempool parents we'd calculate by searching, and it's important that
368
        // we use the cached notion of ancestor transactions as the set of
369
        // things to update for removal.
370
160k
        auto ancestors{AssumeCalculateMemPoolAncestors(__func__, entry, Limits::NoLimits(), /*fSearchForParents=*/false)};
371
        // Note that UpdateAncestorsOf severs the child links that point to
372
        // removeIt in the entries for the parents of removeIt.
373
160k
        UpdateAncestorsOf(false, removeIt, ancestors);
374
160k
    }
375
    // After updating all the ancestor sizes, we can now sever the link between each
376
    // transaction being removed and any mempool children (ie, update CTxMemPoolEntry::m_parents
377
    // for each direct child of a transaction being removed).
378
1.08M
    for (txiter removeIt : entriesToRemove) {
379
160k
        UpdateChildrenForRemoval(removeIt);
380
160k
    }
381
1.08M
}
382
383
void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384
1.00M
{
385
1.00M
    nSizeWithDescendants += modifySize;
386
1.00M
    assert(nSizeWithDescendants > 0);
387
1.00M
    nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
388
1.00M
    m_count_with_descendants += modifyCount;
389
1.00M
    assert(m_count_with_descendants > 0);
390
1.00M
}
391
392
void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393
683k
{
394
683k
    nSizeWithAncestors += modifySize;
395
683k
    assert(nSizeWithAncestors > 0);
396
683k
    nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
397
683k
    m_count_with_ancestors += modifyCount;
398
683k
    assert(m_count_with_ancestors > 0);
399
683k
    nSigOpCostWithAncestors += modifySigOps;
400
683k
    assert(int(nSigOpCostWithAncestors) >= 0);
401
683k
}
402
403
//! Clamp option values and populate the error if options are not valid.
404
static CTxMemPool::Options&& Flatten(CTxMemPool::Options&& opts, bilingual_str& error)
405
51.2k
{
406
51.2k
    opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
407
51.2k
    int64_t descendant_limit_bytes = opts.limits.descendant_size_vbytes * 40;
408
51.2k
    if (opts.max_size_bytes < 0 || opts.max_size_bytes < descendant_limit_bytes) {
409
0
        error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1'000'000.0));
Line
Count
Source
1172
0
#define strprintf tfm::format
410
0
    }
411
51.2k
    return std::move(opts);
412
51.2k
}
413
414
CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
415
51.2k
    : m_opts{Flatten(std::move(opts), error)}
416
51.2k
{
417
51.2k
}
418
419
bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420
0
{
421
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
422
0
    return mapNextTx.count(outpoint);
423
0
}
424
425
unsigned int CTxMemPool::GetTransactionsUpdated() const
426
0
{
427
0
    return nTransactionsUpdated;
428
0
}
429
430
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
431
21.8k
{
432
21.8k
    nTransactionsUpdated += n;
433
21.8k
}
434
435
void CTxMemPool::Apply(ChangeSet* changeset)
436
493k
{
437
493k
    AssertLockHeld(cs);
Line
Count
Source
137
493k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
438
493k
    RemoveStaged(changeset->m_to_remove, false, MemPoolRemovalReason::REPLACED);
439
440
987k
    for (size_t i=0; i<changeset->m_entry_vec.size(); 
++i493k
) {
441
493k
        auto tx_entry = changeset->m_entry_vec[i];
442
493k
        std::optional<CTxMemPool::setEntries> ancestors;
443
493k
        if (i == 0) {
444
            // Note: ChangeSet::CalculateMemPoolAncestors() will return a
445
            // cached value if mempool ancestors for this transaction were
446
            // previously calculated.
447
            // We can only use a cached ancestor calculation for the first
448
            // transaction in a package, because in-package parents won't be
449
            // present in the cached ancestor sets of in-package children.
450
            // We pass in Limits::NoLimits() to ensure that this function won't fail
451
            // (we're going to be applying this set of transactions whether or
452
            // not the mempool policy limits are being respected).
453
493k
            ancestors = *Assume(changeset->CalculateMemPoolAncestors(tx_entry, Limits::NoLimits()));
Line
Count
Source
118
493k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
454
493k
        }
455
        // First splice this entry into mapTx.
456
493k
        auto node_handle = changeset->m_to_add.extract(tx_entry);
457
493k
        auto result = mapTx.insert(std::move(node_handle));
458
459
493k
        Assume(result.inserted);
Line
Count
Source
118
493k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
460
493k
        txiter it = result.position;
461
462
        // Now update the entry for ancestors/descendants.
463
493k
        if (ancestors.has_value()) {
464
493k
            addNewTransaction(it, *ancestors);
465
493k
        } else {
466
0
            addNewTransaction(it);
467
0
        }
468
493k
    }
469
493k
}
470
471
void CTxMemPool::addNewTransaction(CTxMemPool::txiter it)
472
0
{
473
0
    auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
474
0
    return addNewTransaction(it, ancestors);
475
0
}
476
477
void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit, CTxMemPool::setEntries& setAncestors)
478
493k
{
479
493k
    const CTxMemPoolEntry& entry = *newit;
480
481
    // Update cachedInnerUsage to include contained transaction's usage.
482
    // (When we update the entry for in-mempool parents, memory usage will be
483
    // further updated.)
484
493k
    cachedInnerUsage += entry.DynamicMemoryUsage();
485
486
493k
    const CTransaction& tx = newit->GetTx();
487
493k
    std::set<Txid> setParentTransactions;
488
987k
    for (unsigned int i = 0; i < tx.vin.size(); 
i++493k
) {
489
493k
        mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
490
493k
        setParentTransactions.insert(tx.vin[i].prevout.hash);
491
493k
    }
492
    // Don't bother worrying about child transactions of this one.
493
    // Normal case of a new transaction arriving is that there can't be any
494
    // children, because such children would be orphans.
495
    // An exception to that is if a transaction enters that used to be in a block.
496
    // In that case, our disconnect block logic will call UpdateTransactionsFromBlock
497
    // to clean up the mess we're leaving here.
498
499
    // Update ancestors with information about this tx
500
493k
    for (const auto& pit : GetIterSet(setParentTransactions)) {
501
319k
        UpdateParent(newit, pit, true);
502
319k
    }
503
493k
    UpdateAncestorsOf(true, newit, setAncestors);
504
493k
    UpdateEntryForAncestors(newit, setAncestors);
505
506
493k
    nTransactionsUpdated++;
507
493k
    totalTxSize += entry.GetTxSize();
508
493k
    m_total_fee += entry.GetFee();
509
510
493k
    txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
511
493k
    newit->idx_randomized = txns_randomized.size() - 1;
512
513
493k
    TRACEPOINT(mempool, added,
514
493k
        entry.GetTx().GetHash().data(),
515
493k
        entry.GetTxSize(),
516
493k
        entry.GetFee()
517
493k
    );
518
493k
}
519
520
void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
521
160k
{
522
    // We increment mempool sequence value no matter removal reason
523
    // even if not directly reported below.
524
160k
    uint64_t mempool_sequence = GetAndIncrementSequence();
525
526
160k
    if (reason != MemPoolRemovalReason::BLOCK && 
m_opts.signals65.4k
) {
527
        // Notify clients that a transaction has been removed from the mempool
528
        // for any reason except being included in a block. Clients interested
529
        // in transactions included in blocks can subscribe to the BlockConnected
530
        // notification.
531
65.4k
        m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
532
65.4k
    }
533
160k
    TRACEPOINT(mempool, removed,
534
160k
        it->GetTx().GetHash().data(),
535
160k
        RemovalReasonToString(reason).c_str(),
536
160k
        it->GetTxSize(),
537
160k
        it->GetFee(),
538
160k
        std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
539
160k
    );
540
541
160k
    for (const CTxIn& txin : it->GetTx().vin)
542
160k
        mapNextTx.erase(txin.prevout);
543
544
160k
    RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
545
546
160k
    if (txns_randomized.size() > 1) {
547
        // Remove entry from txns_randomized by replacing it with the back and deleting the back.
548
147k
        txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
549
147k
        txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
550
147k
        txns_randomized.pop_back();
551
147k
        if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
552
33.6k
            txns_randomized.shrink_to_fit();
553
33.6k
        }
554
147k
    } else {
555
13.1k
        txns_randomized.clear();
556
13.1k
    }
557
558
160k
    totalTxSize -= it->GetTxSize();
559
160k
    m_total_fee -= it->GetFee();
560
160k
    cachedInnerUsage -= it->DynamicMemoryUsage();
561
160k
    cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
562
160k
    mapTx.erase(it);
563
160k
    nTransactionsUpdated++;
564
160k
}
565
566
// Calculates descendants of entry that are not already in setDescendants, and adds to
567
// setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
568
// is correct for tx and all descendants.
569
// Also assumes that if an entry is in setDescendants already, then all
570
// in-mempool descendants of it are already in setDescendants as well, so that we
571
// can save time by not iterating over those entries.
572
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
573
157k
{
574
157k
    setEntries stage;
575
157k
    if (setDescendants.count(entryit) == 0) {
576
131k
        stage.insert(entryit);
577
131k
    }
578
    // Traverse down the children of entry, only adding children that are not
579
    // accounted for in setDescendants already (because those children have either
580
    // already been walked, or will be walked in this iteration).
581
508k
    while (!stage.empty()) {
582
350k
        txiter it = *stage.begin();
583
350k
        setDescendants.insert(it);
584
350k
        stage.erase(it);
585
586
350k
        const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
587
350k
        for (const CTxMemPoolEntry& child : children) {
588
232k
            txiter childiter = mapTx.iterator_to(child);
589
232k
            if (!setDescendants.count(childiter)) {
590
219k
                stage.insert(childiter);
591
219k
            }
592
232k
        }
593
350k
    }
594
157k
}
595
596
void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
597
182
{
598
    // Remove transaction from memory pool
599
182
    AssertLockHeld(cs);
Line
Count
Source
137
182
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
600
182
    Assume(!m_have_changeset);
Line
Count
Source
118
182
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
601
182
        setEntries txToRemove;
602
182
        txiter origit = mapTx.find(origTx.GetHash());
603
182
        if (origit != mapTx.end()) {
604
104
            txToRemove.insert(origit);
605
104
        } else {
606
            // When recursively removing but origTx isn't in the mempool
607
            // be sure to remove any children that are in the pool. This can
608
            // happen during chain re-orgs if origTx isn't re-accepted into
609
            // the mempool for any reason.
610
234
            for (unsigned int i = 0; i < origTx.vout.size(); 
i++156
) {
611
156
                auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
612
156
                if (it == mapNextTx.end())
613
156
                    continue;
614
0
                txiter nextit = mapTx.find(it->second->GetHash());
615
0
                assert(nextit != mapTx.end());
616
0
                txToRemove.insert(nextit);
617
0
            }
618
78
        }
619
182
        setEntries setAllRemoves;
620
182
        for (txiter it : txToRemove) {
621
104
            CalculateDescendants(it, setAllRemoves);
622
104
        }
623
624
182
        RemoveStaged(setAllRemoves, false, reason);
625
182
}
626
627
void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
628
78
{
629
    // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
630
78
    AssertLockHeld(cs);
Line
Count
Source
137
78
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
631
78
    AssertLockHeld(::cs_main);
Line
Count
Source
137
78
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
632
78
    Assume(!m_have_changeset);
Line
Count
Source
118
78
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
633
634
78
    setEntries txToRemove;
635
78
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); 
it++0
) {
636
0
        if (check_final_and_mature(it)) txToRemove.insert(it);
637
0
    }
638
78
    setEntries setAllRemoves;
639
78
    for (txiter it : txToRemove) {
640
0
        CalculateDescendants(it, setAllRemoves);
641
0
    }
642
78
    RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
643
78
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); 
it++0
) {
644
0
        assert(TestLockPointValidity(chain, it->GetLockPoints()));
645
0
    }
646
78
}
647
648
void CTxMemPool::removeConflicts(const CTransaction &tx)
649
114k
{
650
    // Remove transactions which depend on inputs of tx, recursively
651
114k
    AssertLockHeld(cs);
Line
Count
Source
137
114k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
652
114k
    for (const CTxIn &txin : tx.vin) {
653
114k
        auto it = mapNextTx.find(txin.prevout);
654
114k
        if (it != mapNextTx.end()) {
655
104
            const CTransaction &txConflict = *it->second;
656
104
            if (Assume(txConflict.GetHash() != tx.GetHash()))
Line
Count
Source
118
104
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
657
104
            {
658
104
                ClearPrioritisation(txConflict.GetHash());
659
104
                removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
660
104
            }
661
104
        }
662
114k
    }
663
114k
}
664
665
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
666
21.7k
{
667
    // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
668
21.7k
    AssertLockHeld(cs);
Line
Count
Source
137
21.7k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
669
21.7k
    Assume(!m_have_changeset);
Line
Count
Source
118
21.7k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
670
21.7k
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
671
21.7k
    if (mapTx.size() || 
mapNextTx.size()4.57k
||
mapDeltas.size()4.57k
) {
672
17.2k
        txs_removed_for_block.reserve(vtx.size());
673
114k
        for (const auto& tx : vtx) {
674
114k
            txiter it = mapTx.find(tx->GetHash());
675
114k
            if (it != mapTx.end()) {
676
95.1k
                setEntries stage;
677
95.1k
                stage.insert(it);
678
95.1k
                txs_removed_for_block.emplace_back(*it);
679
95.1k
                RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
680
95.1k
            }
681
114k
            removeConflicts(*tx);
682
114k
            ClearPrioritisation(tx->GetHash());
683
114k
        }
684
17.2k
    }
685
21.7k
    if (m_opts.signals) {
686
21.7k
        m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
687
21.7k
    }
688
21.7k
    lastRollingFeeUpdate = GetTime();
689
21.7k
    blockSinceLastRollingFeeBump = true;
690
21.7k
}
691
692
void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
693
744k
{
694
744k
    if (m_opts.check_ratio == 0) 
return0
;
695
696
744k
    if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) 
return0
;
697
698
744k
    AssertLockHeld(::cs_main);
Line
Count
Source
137
744k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
699
744k
    LOCK(cs);
Line
Count
Source
259
744k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
744k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
744k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
744k
#define PASTE(x, y) x ## y
700
744k
    LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
Line
Count
Source
381
744k
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
373
744k
    do {                                                              \
374
744k
        if (LogAcceptCategory((category), (level))) {                 \
375
0
            bool rate_limit{level >= BCLog::Level::Info};             \
376
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
377
0
        }                                                             \
378
744k
    } while (0)
701
702
744k
    uint64_t checkTotal = 0;
703
744k
    CAmount check_total_fee{0};
704
744k
    uint64_t innerUsage = 0;
705
744k
    uint64_t prev_ancestor_count{0};
706
707
744k
    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
708
709
16.5M
    for (const auto& it : GetSortedDepthAndScore()) {
710
16.5M
        checkTotal += it->GetTxSize();
711
16.5M
        check_total_fee += it->GetFee();
712
16.5M
        innerUsage += it->DynamicMemoryUsage();
713
16.5M
        const CTransaction& tx = it->GetTx();
714
16.5M
        innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
715
16.5M
        CTxMemPoolEntry::Parents setParentCheck;
716
16.5M
        for (const CTxIn &txin : tx.vin) {
717
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
718
16.5M
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
719
16.5M
            if (it2 != mapTx.end()) {
720
10.3M
                const CTransaction& tx2 = it2->GetTx();
721
10.3M
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
722
10.3M
                setParentCheck.insert(*it2);
723
10.3M
            }
724
            // We are iterating through the mempool entries sorted in order by ancestor count.
725
            // All parents must have been checked before their children and their coins added to
726
            // the mempoolDuplicate coins cache.
727
16.5M
            assert(mempoolDuplicate.HaveCoin(txin.prevout));
728
            // Check whether its inputs are marked in mapNextTx.
729
16.5M
            auto it3 = mapNextTx.find(txin.prevout);
730
16.5M
            assert(it3 != mapNextTx.end());
731
16.5M
            assert(it3->first == &txin.prevout);
732
16.5M
            assert(it3->second == &tx);
733
16.5M
        }
734
20.7M
        
auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool 16.5M
{
735
20.7M
            return a.GetTx().GetHash() == b.GetTx().GetHash();
736
20.7M
        };
737
16.5M
        assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
738
16.5M
        assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
739
        // Verify ancestor state is correct.
740
16.5M
        auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
741
16.5M
        uint64_t nCountCheck = ancestors.size() + 1;
742
16.5M
        int32_t nSizeCheck = it->GetTxSize();
743
16.5M
        CAmount nFeesCheck = it->GetModifiedFee();
744
16.5M
        int64_t nSigOpCheck = it->GetSigOpCost();
745
746
28.8M
        for (txiter ancestorIt : ancestors) {
747
28.8M
            nSizeCheck += ancestorIt->GetTxSize();
748
28.8M
            nFeesCheck += ancestorIt->GetModifiedFee();
749
28.8M
            nSigOpCheck += ancestorIt->GetSigOpCost();
750
28.8M
        }
751
752
16.5M
        assert(it->GetCountWithAncestors() == nCountCheck);
753
16.5M
        assert(it->GetSizeWithAncestors() == nSizeCheck);
754
16.5M
        assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
755
16.5M
        assert(it->GetModFeesWithAncestors() == nFeesCheck);
756
        // Sanity check: we are walking in ascending ancestor count order.
757
16.5M
        assert(prev_ancestor_count <= it->GetCountWithAncestors());
758
16.5M
        prev_ancestor_count = it->GetCountWithAncestors();
759
760
        // Check children against mapNextTx
761
16.5M
        CTxMemPoolEntry::Children setChildrenCheck;
762
16.5M
        auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
763
16.5M
        int32_t child_sizes{0};
764
26.9M
        for (; iter != mapNextTx.end() && 
iter->first->hash == it->GetTx().GetHash()26.1M
;
++iter10.3M
) {
765
10.3M
            txiter childit = mapTx.find(iter->second->GetHash());
766
10.3M
            assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
767
10.3M
            if (setChildrenCheck.insert(*childit).second) {
768
10.3M
                child_sizes += childit->GetTxSize();
769
10.3M
            }
770
10.3M
        }
771
16.5M
        assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
772
16.5M
        assert(std::equal(setChildrenCheck.begin(), setChildrenCheck.end(), it->GetMemPoolChildrenConst().begin(), comp));
773
        // Also check to make sure size is greater than sum with immediate children.
774
        // just a sanity check, not definitive that this calc is correct...
775
16.5M
        assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
776
777
16.5M
        TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
778
16.5M
        CAmount txfee = 0;
779
16.5M
        assert(!tx.IsCoinBase());
780
16.5M
        assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
781
16.5M
        for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
782
16.5M
        AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
783
16.5M
    }
784
16.5M
    
for (const auto& [_, next_tx] : mapNextTx)744k
{
785
16.5M
        auto it = mapTx.find(next_tx->GetHash());
786
16.5M
        const CTransaction& tx = it->GetTx();
787
16.5M
        assert(it != mapTx.end());
788
16.5M
        assert(&tx == next_tx);
789
16.5M
    }
790
791
744k
    assert(totalTxSize == checkTotal);
792
744k
    assert(m_total_fee == check_total_fee);
793
744k
    assert(innerUsage == cachedInnerUsage);
794
744k
}
795
796
bool CTxMemPool::CompareDepthAndScore(const Wtxid& hasha, const Wtxid& hashb) const
797
43.2k
{
798
    /* Return `true` if hasha should be considered sooner than hashb. Namely when:
799
     *   a is not in the mempool, but b is
800
     *   both are in the mempool and a has fewer ancestors than b
801
     *   both are in the mempool and a has a higher score than b
802
     */
803
43.2k
    LOCK(cs);
Line
Count
Source
259
43.2k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
43.2k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
43.2k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
43.2k
#define PASTE(x, y) x ## y
804
43.2k
    auto j{GetIter(hashb)};
805
43.2k
    if (!j.has_value()) 
return false8.43k
;
806
34.7k
    auto i{GetIter(hasha)};
807
34.7k
    if (!i.has_value()) 
return true1.54k
;
808
33.2k
    uint64_t counta = i.value()->GetCountWithAncestors();
809
33.2k
    uint64_t countb = j.value()->GetCountWithAncestors();
810
33.2k
    if (counta == countb) {
811
7.06k
        return CompareTxMemPoolEntryByScore()(*i.value(), *j.value());
812
7.06k
    }
813
26.1k
    return counta < countb;
814
33.2k
}
815
816
namespace {
817
class DepthAndScoreComparator
818
{
819
public:
820
    bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
821
98.1M
    {
822
98.1M
        uint64_t counta = a->GetCountWithAncestors();
823
98.1M
        uint64_t countb = b->GetCountWithAncestors();
824
98.1M
        if (counta == countb) {
825
40.0M
            return CompareTxMemPoolEntryByScore()(*a, *b);
826
40.0M
        }
827
58.0M
        return counta < countb;
828
98.1M
    }
829
};
830
} // namespace
831
832
std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
833
744k
{
834
744k
    std::vector<indexed_transaction_set::const_iterator> iters;
835
744k
    AssertLockHeld(cs);
Line
Count
Source
137
744k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
836
837
744k
    iters.reserve(mapTx.size());
838
839
17.2M
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); 
++mi16.5M
) {
840
16.5M
        iters.push_back(mi);
841
16.5M
    }
842
744k
    std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
843
744k
    return iters;
844
744k
}
845
846
std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
847
0
{
848
0
    AssertLockHeld(cs);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
849
850
0
    std::vector<CTxMemPoolEntryRef> ret;
851
0
    ret.reserve(mapTx.size());
852
0
    for (const auto& it : GetSortedDepthAndScore()) {
853
0
        ret.emplace_back(*it);
854
0
    }
855
0
    return ret;
856
0
}
857
858
std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
859
0
{
860
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
861
0
    auto iters = GetSortedDepthAndScore();
862
863
0
    std::vector<TxMempoolInfo> ret;
864
0
    ret.reserve(mapTx.size());
865
0
    for (auto it : iters) {
866
0
        ret.push_back(GetInfo(it));
867
0
    }
868
869
0
    return ret;
870
0
}
871
872
const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
873
0
{
874
0
    AssertLockHeld(cs);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
875
0
    const auto i = mapTx.find(txid);
876
0
    return i == mapTx.end() ? nullptr : &(*i);
877
0
}
878
879
CTransactionRef CTxMemPool::get(const Txid& hash) const
880
7.77M
{
881
7.77M
    LOCK(cs);
Line
Count
Source
259
7.77M
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
7.77M
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
7.77M
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
7.77M
#define PASTE(x, y) x ## y
882
7.77M
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
883
7.77M
    if (i == mapTx.end())
884
1.55M
        return nullptr;
885
6.21M
    return i->GetSharedTx();
886
7.77M
}
887
888
void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
889
0
{
890
0
    {
891
0
        LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
892
0
        CAmount &delta = mapDeltas[hash];
893
0
        delta = SaturatingAdd(delta, nFeeDelta);
894
0
        txiter it = mapTx.find(hash);
895
0
        if (it != mapTx.end()) {
896
0
            mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
897
            // Now update all ancestors' modified fees with descendants
898
0
            auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
899
0
            for (txiter ancestorIt : ancestors) {
900
0
                mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
901
0
            }
902
            // Now update all descendants' modified fees with ancestors
903
0
            setEntries setDescendants;
904
0
            CalculateDescendants(it, setDescendants);
905
0
            setDescendants.erase(it);
906
0
            for (txiter descendantIt : setDescendants) {
907
0
                mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
908
0
            }
909
0
            ++nTransactionsUpdated;
910
0
        }
911
0
        if (delta == 0) {
912
0
            mapDeltas.erase(hash);
913
0
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
Line
Count
Source
361
0
#define LogPrintf(...) LogInfo(__VA_ARGS__)
Line
Count
Source
356
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
914
0
        } else {
915
0
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
Line
Count
Source
361
0
#define LogPrintf(...) LogInfo(__VA_ARGS__)
Line
Count
Source
356
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
916
0
                      hash.ToString(),
917
0
                      it == mapTx.end() ? "not " : "",
918
0
                      FormatMoney(nFeeDelta),
919
0
                      FormatMoney(delta));
920
0
        }
921
0
    }
922
0
}
923
924
void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
925
638k
{
926
638k
    AssertLockHeld(cs);
Line
Count
Source
137
638k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
927
638k
    std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
928
638k
    if (pos == mapDeltas.end())
929
638k
        return;
930
0
    const CAmount &delta = pos->second;
931
0
    nFeeDelta += delta;
932
0
}
933
934
void CTxMemPool::ClearPrioritisation(const Txid& hash)
935
114k
{
936
114k
    AssertLockHeld(cs);
Line
Count
Source
137
114k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
937
114k
    mapDeltas.erase(hash);
938
114k
}
939
940
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
941
0
{
942
0
    AssertLockNotHeld(cs);
Line
Count
Source
142
0
#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
943
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
944
0
    std::vector<delta_info> result;
945
0
    result.reserve(mapDeltas.size());
946
0
    for (const auto& [txid, delta] : mapDeltas) {
947
0
        const auto iter{mapTx.find(txid)};
948
0
        const bool in_mempool{iter != mapTx.end()};
949
0
        std::optional<CAmount> modified_fee;
950
0
        if (in_mempool) modified_fee = iter->GetModifiedFee();
951
0
        result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
952
0
    }
953
0
    return result;
954
0
}
955
956
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
957
654k
{
958
654k
    const auto it = mapNextTx.find(prevout);
959
654k
    return it == mapNextTx.end() ? 
nullptr497k
:
it->second156k
;
960
654k
}
961
962
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
963
18.2M
{
964
18.2M
    AssertLockHeld(cs);
Line
Count
Source
137
18.2M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
965
18.2M
    auto it = mapTx.find(txid);
966
18.2M
    return it != mapTx.end() ? 
std::make_optional(it)11.8M
:
std::nullopt6.46M
;
967
18.2M
}
968
969
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
970
90.8k
{
971
90.8k
    AssertLockHeld(cs);
Line
Count
Source
137
90.8k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
972
90.8k
    auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
973
90.8k
    return it != mapTx.end() ? 
std::make_optional(it)78.4k
:
std::nullopt12.3k
;
974
90.8k
}
975
976
CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
977
1.13M
{
978
1.13M
    CTxMemPool::setEntries ret;
979
1.13M
    for (const auto& h : hashes) {
980
638k
        const auto mi = GetIter(h);
981
638k
        if (mi) 
ret.insert(*mi)464k
;
982
638k
    }
983
1.13M
    return ret;
984
1.13M
}
985
986
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
987
0
{
988
0
    AssertLockHeld(cs);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
989
0
    std::vector<txiter> ret;
990
0
    ret.reserve(txids.size());
991
0
    for (const auto& txid : txids) {
992
0
        const auto it{GetIter(txid)};
993
0
        if (!it) return {};
994
0
        ret.push_back(*it);
995
0
    }
996
0
    return ret;
997
0
}
998
999
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
1000
491k
{
1001
664k
    for (unsigned int i = 0; i < tx.vin.size(); 
i++173k
)
1002
491k
        if (exists(tx.vin[i].prevout.hash))
1003
317k
            return false;
1004
173k
    return true;
1005
491k
}
1006
1007
764k
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1008
1009
std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
1010
6.64M
{
1011
    // Check to see if the inputs are made available by another tx in the package.
1012
    // These Coins would not be available in the underlying CoinsView.
1013
6.64M
    if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1014
0
        return it->second;
1015
0
    }
1016
1017
    // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1018
    // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1019
    // transactions. First checking the underlying cache risks returning a pruned entry instead.
1020
6.64M
    CTransactionRef ptx = mempool.get(outpoint.hash);
1021
6.64M
    if (ptx) {
1022
5.43M
        if (outpoint.n < ptx->vout.size()) {
1023
5.43M
            Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1024
5.43M
            m_non_base_coins.emplace(outpoint);
1025
5.43M
            return coin;
1026
5.43M
        }
1027
0
        return std::nullopt;
1028
5.43M
    }
1029
1.20M
    return base->GetCoin(outpoint);
1030
6.64M
}
1031
1032
void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1033
0
{
1034
0
    for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1035
0
        m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1036
0
        m_non_base_coins.emplace(tx->GetHash(), n);
1037
0
    }
1038
0
}
1039
void CCoinsViewMemPool::Reset()
1040
493k
{
1041
493k
    m_temp_added.clear();
1042
493k
    m_non_base_coins.clear();
1043
493k
}
1044
1045
1.28M
size_t CTxMemPool::DynamicMemoryUsage() const {
1046
1.28M
    LOCK(cs);
Line
Count
Source
259
1.28M
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
1.28M
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
1.28M
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
1.28M
#define PASTE(x, y) x ## y
1047
    // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1048
1.28M
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1049
1.28M
}
1050
1051
160k
void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
1052
160k
    LOCK(cs);
Line
Count
Source
259
160k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
160k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
160k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
160k
#define PASTE(x, y) x ## y
1053
1054
160k
    if (m_unbroadcast_txids.erase(txid))
1055
0
    {
1056
0
        LogDebug(BCLog::MEMPOOL, "Removed %i from set of unbroadcast txns%s\n", txid.GetHex(), (unchecked ? " before confirmation that txn was sent out" : ""));
Line
Count
Source
381
0
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
373
0
    do {                                                              \
374
0
        if (LogAcceptCategory((category), (level))) {                 \
375
0
            bool rate_limit{level >= BCLog::Level::Info};             \
376
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
377
0
        }                                                             \
378
0
    } while (0)
1057
0
    }
1058
160k
}
1059
1060
1.08M
void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1061
1.08M
    AssertLockHeld(cs);
Line
Count
Source
137
1.08M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1062
1.08M
    UpdateForRemoveFromMempool(stage, updateDescendants);
1063
1.08M
    for (txiter it : stage) {
1064
160k
        removeUnchecked(it, reason);
1065
160k
    }
1066
1.08M
}
1067
1068
int CTxMemPool::Expire(std::chrono::seconds time)
1069
493k
{
1070
493k
    AssertLockHeld(cs);
Line
Count
Source
137
493k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1071
493k
    Assume(!m_have_changeset);
Line
Count
Source
118
493k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1072
493k
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1073
493k
    setEntries toremove;
1074
556k
    while (it != mapTx.get<entry_time>().end() && 
it->GetTime() < time556k
) {
1075
62.4k
        toremove.insert(mapTx.project<0>(it));
1076
62.4k
        it++;
1077
62.4k
    }
1078
493k
    setEntries stage;
1079
493k
    for (txiter removeit : toremove) {
1080
62.4k
        CalculateDescendants(removeit, stage);
1081
62.4k
    }
1082
493k
    RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1083
493k
    return stage.size();
1084
493k
}
1085
1086
void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1087
361k
{
1088
361k
    AssertLockHeld(cs);
Line
Count
Source
137
361k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1089
361k
    CTxMemPoolEntry::Children s;
1090
361k
    if (add && 
entry->GetMemPoolChildren().insert(*child).second319k
) {
1091
319k
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1092
319k
    } else 
if (42.1k
!add42.1k
&&
entry->GetMemPoolChildren().erase(*child)42.1k
) {
1093
42.1k
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1094
42.1k
    }
1095
361k
}
1096
1097
void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1098
385k
{
1099
385k
    AssertLockHeld(cs);
Line
Count
Source
137
385k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1100
385k
    CTxMemPoolEntry::Parents s;
1101
385k
    if (add && 
entry->GetMemPoolParents().insert(*parent).second319k
) {
1102
319k
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1103
319k
    } else 
if (65.6k
!add65.6k
&&
entry->GetMemPoolParents().erase(*parent)65.6k
) {
1104
65.6k
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1105
65.6k
    }
1106
385k
}
1107
1108
6.02M
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1109
6.02M
    LOCK(cs);
Line
Count
Source
259
6.02M
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
6.02M
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
6.02M
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
6.02M
#define PASTE(x, y) x ## y
1110
6.02M
    if (!blockSinceLastRollingFeeBump || 
rollingMinimumFeeRate == 03.12M
)
1111
6.02M
        return CFeeRate(llround(rollingMinimumFeeRate));
1112
1113
0
    int64_t time = GetTime();
1114
0
    if (time > lastRollingFeeUpdate + 10) {
1115
0
        double halflife = ROLLING_FEE_HALFLIFE;
1116
0
        if (DynamicMemoryUsage() < sizelimit / 4)
1117
0
            halflife /= 4;
1118
0
        else if (DynamicMemoryUsage() < sizelimit / 2)
1119
0
            halflife /= 2;
1120
1121
0
        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1122
0
        lastRollingFeeUpdate = time;
1123
1124
0
        if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1125
0
            rollingMinimumFeeRate = 0;
1126
0
            return CFeeRate(0);
1127
0
        }
1128
0
    }
1129
0
    return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1130
0
}
1131
1132
0
void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1133
0
    AssertLockHeld(cs);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1134
0
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1135
0
        rollingMinimumFeeRate = rate.GetFeePerK();
1136
0
        blockSinceLastRollingFeeBump = false;
1137
0
    }
1138
0
}
1139
1140
493k
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1141
493k
    AssertLockHeld(cs);
Line
Count
Source
137
493k
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1142
493k
    Assume(!m_have_changeset);
Line
Count
Source
118
493k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1143
1144
493k
    unsigned nTxnRemoved = 0;
1145
493k
    CFeeRate maxFeeRateRemoved(0);
1146
493k
    while (!mapTx.empty() && 
DynamicMemoryUsage() > sizelimit491k
) {
1147
0
        indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1148
1149
        // We set the new mempool min fee to the feerate of the removed set, plus the
1150
        // "minimum reasonable fee rate" (ie some value under which we consider txn
1151
        // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1152
        // equal to txn which were removed with no block in between.
1153
0
        CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1154
0
        removed += m_opts.incremental_relay_feerate;
1155
0
        trackPackageRemoved(removed);
1156
0
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1157
1158
0
        setEntries stage;
1159
0
        CalculateDescendants(mapTx.project<0>(it), stage);
1160
0
        nTxnRemoved += stage.size();
1161
1162
0
        std::vector<CTransaction> txn;
1163
0
        if (pvNoSpendsRemaining) {
1164
0
            txn.reserve(stage.size());
1165
0
            for (txiter iter : stage)
1166
0
                txn.push_back(iter->GetTx());
1167
0
        }
1168
0
        RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1169
0
        if (pvNoSpendsRemaining) {
1170
0
            for (const CTransaction& tx : txn) {
1171
0
                for (const CTxIn& txin : tx.vin) {
1172
0
                    if (exists(txin.prevout.hash)) continue;
1173
0
                    pvNoSpendsRemaining->push_back(txin.prevout);
1174
0
                }
1175
0
            }
1176
0
        }
1177
0
    }
1178
1179
493k
    if (maxFeeRateRemoved > CFeeRate(0)) {
1180
0
        LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
Line
Count
Source
381
0
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
373
0
    do {                                                              \
374
0
        if (LogAcceptCategory((category), (level))) {                 \
375
0
            bool rate_limit{level >= BCLog::Level::Info};             \
376
0
            LogPrintLevel_(category, level, rate_limit, __VA_ARGS__); \
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
377
0
        }                                                             \
378
0
    } while (0)
1181
0
    }
1182
493k
}
1183
1184
0
uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
1185
    // find parent with highest descendant count
1186
0
    std::vector<txiter> candidates;
1187
0
    setEntries counted;
1188
0
    candidates.push_back(entry);
1189
0
    uint64_t maximum = 0;
1190
0
    while (candidates.size()) {
1191
0
        txiter candidate = candidates.back();
1192
0
        candidates.pop_back();
1193
0
        if (!counted.insert(candidate).second) continue;
1194
0
        const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1195
0
        if (parents.size() == 0) {
1196
0
            maximum = std::max(maximum, candidate->GetCountWithDescendants());
1197
0
        } else {
1198
0
            for (const CTxMemPoolEntry& i : parents) {
1199
0
                candidates.push_back(mapTx.iterator_to(i));
1200
0
            }
1201
0
        }
1202
0
    }
1203
0
    return maximum;
1204
0
}
1205
1206
0
void CTxMemPool::GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1207
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
1208
0
    auto it = mapTx.find(txid);
1209
0
    ancestors = descendants = 0;
1210
0
    if (it != mapTx.end()) {
1211
0
        ancestors = it->GetCountWithAncestors();
1212
0
        if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1213
0
        if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1214
0
        descendants = CalculateDescendantMaximum(it);
1215
0
    }
1216
0
}
1217
1218
bool CTxMemPool::GetLoadTried() const
1219
0
{
1220
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
1221
0
    return m_load_tried;
1222
0
}
1223
1224
void CTxMemPool::SetLoadTried(bool load_tried)
1225
0
{
1226
0
    LOCK(cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
1227
0
    m_load_tried = load_tried;
1228
0
}
1229
1230
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1231
0
{
1232
0
    AssertLockHeld(cs);
Line
Count
Source
137
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1233
0
    std::vector<txiter> clustered_txs{GetIterVec(txids)};
1234
    // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1235
    // necessarily mean the entry has been processed.
1236
0
    WITH_FRESH_EPOCH(m_epoch);
Line
Count
Source
100
0
#define WITH_FRESH_EPOCH(epoch) const Epoch::Guard UNIQUE_NAME(epoch_guard_)(epoch)
Line
Count
Source
11
0
#define 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
1237
0
    for (const auto& it : clustered_txs) {
1238
0
        visited(it);
1239
0
    }
1240
    // i = index of where the list of entries to process starts
1241
0
    for (size_t i{0}; i < clustered_txs.size(); ++i) {
1242
        // DoS protection: if there are 500 or more entries to process, just quit.
1243
0
        if (clustered_txs.size() > 500) return {};
1244
0
        const txiter& tx_iter = clustered_txs.at(i);
1245
0
        for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
1246
0
            for (const CTxMemPoolEntry& entry : entries) {
1247
0
                const auto entry_it = mapTx.iterator_to(entry);
1248
0
                if (!visited(entry_it)) {
1249
0
                    clustered_txs.push_back(entry_it);
1250
0
                }
1251
0
            }
1252
0
        }
1253
0
    }
1254
0
    return clustered_txs;
1255
0
}
1256
1257
std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1258
0
{
1259
0
    for (const auto& direct_conflict : direct_conflicts) {
1260
        // Ancestor and descendant counts are inclusive of the tx itself.
1261
0
        const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1262
0
        const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1263
0
        const bool has_ancestor{ancestor_count > 1};
1264
0
        const bool has_descendant{descendant_count > 1};
1265
0
        const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
1266
        // The only allowed configurations are:
1267
        // 1 ancestor and 0 descendant
1268
        // 0 ancestor and 1 descendant
1269
        // 0 ancestor and 0 descendant
1270
0
        if (ancestor_count > 2) {
1271
0
            return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
Line
Count
Source
1172
0
#define strprintf tfm::format
1272
0
        } else if (descendant_count > 2) {
1273
0
            return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
Line
Count
Source
1172
0
#define strprintf tfm::format
1274
0
        } else if (has_ancestor && has_descendant) {
1275
0
            return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
Line
Count
Source
1172
0
#define strprintf tfm::format
1276
0
        }
1277
        // Additionally enforce that:
1278
        // If we have a child,  we are its only parent.
1279
        // If we have a parent, we are its only child.
1280
0
        if (has_descendant) {
1281
0
            const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1282
0
            if (our_child->get().GetCountWithAncestors() > 2) {
1283
0
                return strprintf("%s is not the only parent of child %s",
Line
Count
Source
1172
0
#define strprintf tfm::format
1284
0
                                 txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
1285
0
            }
1286
0
        } else if (has_ancestor) {
1287
0
            const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1288
0
            if (our_parent->get().GetCountWithDescendants() > 2) {
1289
0
                return strprintf("%s is not the only child of parent %s",
Line
Count
Source
1172
0
#define strprintf tfm::format
1290
0
                                 txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
1291
0
            }
1292
0
        }
1293
0
    }
1294
0
    return std::nullopt;
1295
0
}
1296
1297
util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1298
0
{
1299
0
    LOCK(m_pool->cs);
Line
Count
Source
259
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define 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
1300
0
    FeeFrac replacement_feerate{0, 0};
1301
0
    for (auto it : m_entry_vec) {
1302
0
        replacement_feerate += {it->GetModifiedFee(), it->GetTxSize()};
1303
0
    }
1304
1305
0
    auto err_string{m_pool->CheckConflictTopology(m_to_remove)};
1306
0
    if (err_string.has_value()) {
1307
        // Unsupported topology for calculating a feerate diagram
1308
0
        return util::Error{Untranslated(err_string.value())};
1309
0
    }
1310
1311
    // new diagram will have chunks that consist of each ancestor of
1312
    // direct_conflicts that is at its own fee/size, along with the replacement
1313
    // tx/package at its own fee/size
1314
1315
    // old diagram will consist of the ancestors and descendants of each element of
1316
    // all_conflicts.  every such transaction will either be at its own feerate (followed
1317
    // by any descendant at its own feerate), or as a single chunk at the descendant's
1318
    // ancestor feerate.
1319
1320
0
    std::vector<FeeFrac> old_chunks;
1321
    // Step 1: build the old diagram.
1322
1323
    // The above clusters are all trivially linearized;
1324
    // they have a strict topology of 1 or two connected transactions.
1325
1326
    // OLD: Compute existing chunks from all affected clusters
1327
0
    for (auto txiter : m_to_remove) {
1328
        // Does this transaction have descendants?
1329
0
        if (txiter->GetCountWithDescendants() > 1) {
1330
            // Consider this tx when we consider the descendant.
1331
0
            continue;
1332
0
        }
1333
        // Does this transaction have ancestors?
1334
0
        FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
1335
0
        if (txiter->GetCountWithAncestors() > 1) {
1336
            // We'll add chunks for either the ancestor by itself and this tx
1337
            // by itself, or for a combined package.
1338
0
            FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
1339
0
            if (individual >> package) {
1340
                // The individual feerate is higher than the package, and
1341
                // therefore higher than the parent's fee. Chunk these
1342
                // together.
1343
0
                old_chunks.emplace_back(package);
1344
0
            } else {
1345
                // Add two points, one for the parent and one for this child.
1346
0
                old_chunks.emplace_back(package - individual);
1347
0
                old_chunks.emplace_back(individual);
1348
0
            }
1349
0
        } else {
1350
0
            old_chunks.emplace_back(individual);
1351
0
        }
1352
0
    }
1353
1354
    // No topology restrictions post-chunking; sort
1355
0
    std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1356
1357
0
    std::vector<FeeFrac> new_chunks;
1358
1359
    /* Step 2: build the NEW diagram
1360
     * CON = Conflicts of proposed chunk
1361
     * CNK = Proposed chunk
1362
     * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
1363
     * the conflicts, plus the proposed chunk
1364
     */
1365
1366
    // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
1367
0
    for (auto direct_conflict : m_to_remove) {
1368
        // If a direct conflict has an ancestor that is not in all_conflicts,
1369
        // it can be affected by the replacement of the child.
1370
0
        if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
1371
            // Grab the parent.
1372
0
            const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1373
0
            if (!m_to_remove.contains(m_pool->mapTx.iterator_to(parent))) {
1374
                // This transaction would be left over, so add to the NEW
1375
                // diagram.
1376
0
                new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
1377
0
            }
1378
0
        }
1379
0
    }
1380
    // + CNK: Add the proposed chunk itself
1381
0
    new_chunks.emplace_back(replacement_feerate);
1382
1383
    // No topology restrictions post-chunking; sort
1384
0
    std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1385
0
    return std::make_pair(old_chunks, new_chunks);
1386
0
}
1387
1388
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)
1389
638k
{
1390
638k
    LOCK(m_pool->cs);
Line
Count
Source
259
638k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
638k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
638k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
638k
#define PASTE(x, y) x ## y
1391
638k
    Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
Line
Count
Source
118
638k
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1392
638k
    auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1393
638k
    CAmount delta{0};
1394
638k
    m_pool->ApplyDelta(tx->GetHash(), delta);
1395
638k
    if (delta) 
m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) 0
{ e.UpdateModifiedFee(delta); }0
);
1396
1397
638k
    m_entry_vec.push_back(newit);
1398
638k
    return newit;
1399
638k
}
1400
1401
void CTxMemPool::ChangeSet::Apply()
1402
493k
{
1403
493k
    LOCK(m_pool->cs);
Line
Count
Source
259
493k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
493k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
493k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
493k
#define PASTE(x, y) x ## y
1404
493k
    m_pool->Apply(this);
1405
493k
    m_to_add.clear();
1406
493k
    m_to_remove.clear();
1407
493k
    m_entry_vec.clear();
1408
493k
    m_ancestors.clear();
1409
493k
}