fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

/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
142
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<uint256>& setExclude, std::set<uint256>& 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<uint256>& vHashesToUpdate)
109
55
{
110
55
    AssertLockHeld(cs);
Line
Count
Source
142
55
#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
55
    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
55
    std::set<uint256> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
119
120
55
    std::set<uint256> 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
55
    for (const uint256& 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(Txid::FromUint256(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 uint256 &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
55
    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
55
}
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
0
{
169
0
    int64_t totalSizeWithAncestors = entry_size;
170
0
    setEntries ancestors;
171
172
0
    while (!staged_ancestors.empty()) {
173
0
        const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
174
0
        txiter stageit = mapTx.iterator_to(stage);
175
176
0
        ancestors.insert(stageit);
177
0
        staged_ancestors.erase(stage);
178
0
        totalSizeWithAncestors += stageit->GetTxSize();
179
180
0
        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
0
        } 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
0
        } 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
0
        const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
189
0
        for (const CTxMemPoolEntry& parent : parents) {
190
0
            txiter parent_it = mapTx.iterator_to(parent);
191
192
            // If this is a new ancestor, add it.
193
0
            if (ancestors.count(parent_it) == 0) {
194
0
                staged_ancestors.insert(parent);
195
0
            }
196
0
            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
0
        }
200
0
    }
201
202
0
    return ancestors;
203
0
}
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
0
{
248
0
    CTxMemPoolEntry::Parents staged_ancestors;
249
0
    const CTransaction &tx = entry.GetTx();
250
251
0
    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
0
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
256
0
            std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257
0
            if (piter) {
258
0
                staged_ancestors.insert(**piter);
259
0
                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
0
            }
263
0
        }
264
0
    } 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
0
        txiter it = mapTx.iterator_to(entry);
268
0
        staged_ancestors = it->GetMemPoolParentsConst();
269
0
    }
270
271
0
    return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272
0
                                            limits);
273
0
}
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
0
{
281
0
    auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282
0
    if (!Assume(result)) {
Line
Count
Source
118
0
#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
273
0
    do {                                                  \
274
0
        if (LogAcceptCategory((category), (level))) {     \
275
0
            LogPrintLevel_(category, level, __VA_ARGS__); \
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
276
0
        }                                                 \
277
0
    } while (0)
284
0
                      calling_fn_name, util::ErrorString(result).original);
285
0
    }
286
0
    return std::move(result).value_or(CTxMemPool::setEntries{});
287
0
}
288
289
void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290
0
{
291
0
    const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292
    // add or remove this tx as a child of each parent
293
0
    for (const CTxMemPoolEntry& parent : parents) {
294
0
        UpdateChild(mapTx.iterator_to(parent), it, add);
295
0
    }
296
0
    const int32_t updateCount = (add ? 1 : -1);
297
0
    const int32_t updateSize{updateCount * it->GetTxSize()};
298
0
    const CAmount updateFee = updateCount * it->GetModifiedFee();
299
0
    for (txiter ancestorIt : setAncestors) {
300
0
        mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301
0
    }
302
0
}
303
304
void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
305
0
{
306
0
    int64_t updateCount = setAncestors.size();
307
0
    int64_t updateSize = 0;
308
0
    CAmount updateFee = 0;
309
0
    int64_t updateSigOpsCost = 0;
310
0
    for (txiter ancestorIt : setAncestors) {
311
0
        updateSize += ancestorIt->GetTxSize();
312
0
        updateFee += ancestorIt->GetModifiedFee();
313
0
        updateSigOpsCost += ancestorIt->GetSigOpCost();
314
0
    }
315
0
    mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316
0
}
317
318
void CTxMemPool::UpdateChildrenForRemoval(txiter it)
319
0
{
320
0
    const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321
0
    for (const CTxMemPoolEntry& updateIt : children) {
322
0
        UpdateParent(mapTx.iterator_to(updateIt), it, false);
323
0
    }
324
0
}
325
326
void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
327
110
{
328
    // For each entry, walk back all ancestors and decrement size associated with this
329
    // transaction
330
110
    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
0
        for (txiter removeIt : entriesToRemove) {
338
0
            setEntries setDescendants;
339
0
            CalculateDescendants(removeIt, setDescendants);
340
0
            setDescendants.erase(removeIt); // don't update state for self
341
0
            int32_t modifySize = -removeIt->GetTxSize();
342
0
            CAmount modifyFee = -removeIt->GetModifiedFee();
343
0
            int modifySigOps = -removeIt->GetSigOpCost();
344
0
            for (txiter dit : setDescendants) {
345
0
                mapTx.modify(dit, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(modifySize, modifyFee, -1, modifySigOps); });
346
0
            }
347
0
        }
348
0
    }
349
110
    for (txiter removeIt : entriesToRemove) {
350
0
        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
0
        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
0
        UpdateAncestorsOf(false, removeIt, ancestors);
374
0
    }
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
110
    for (txiter removeIt : entriesToRemove) {
379
0
        UpdateChildrenForRemoval(removeIt);
380
0
    }
381
110
}
382
383
void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384
0
{
385
0
    nSizeWithDescendants += modifySize;
386
0
    assert(nSizeWithDescendants > 0);
387
0
    nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
388
0
    m_count_with_descendants += modifyCount;
389
0
    assert(m_count_with_descendants > 0);
390
0
}
391
392
void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393
0
{
394
0
    nSizeWithAncestors += modifySize;
395
0
    assert(nSizeWithAncestors > 0);
396
0
    nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
397
0
    m_count_with_ancestors += modifyCount;
398
0
    assert(m_count_with_ancestors > 0);
399
0
    nSigOpCostWithAncestors += modifySigOps;
400
0
    assert(int(nSigOpCostWithAncestors) >= 0);
401
0
}
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
49.9k
{
406
49.9k
    opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
407
49.9k
    int64_t descendant_limit_bytes = opts.limits.descendant_size_vbytes * 40;
408
49.9k
    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
49.9k
    return std::move(opts);
412
49.9k
}
413
414
CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
415
49.9k
    : m_opts{Flatten(std::move(opts), error)}
416
49.9k
{
417
49.9k
}
418
419
bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420
0
{
421
0
    LOCK(cs);
Line
Count
Source
257
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
10.0M
{
432
10.0M
    nTransactionsUpdated += n;
433
10.0M
}
434
435
void CTxMemPool::Apply(ChangeSet* changeset)
436
0
{
437
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
438
0
    RemoveStaged(changeset->m_to_remove, false, MemPoolRemovalReason::REPLACED);
439
440
0
    for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
441
0
        auto tx_entry = changeset->m_entry_vec[i];
442
0
        std::optional<CTxMemPool::setEntries> ancestors;
443
0
        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
0
            ancestors = *Assume(changeset->CalculateMemPoolAncestors(tx_entry, Limits::NoLimits()));
Line
Count
Source
118
0
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
454
0
        }
455
        // First splice this entry into mapTx.
456
0
        auto node_handle = changeset->m_to_add.extract(tx_entry);
457
0
        auto result = mapTx.insert(std::move(node_handle));
458
459
0
        Assume(result.inserted);
Line
Count
Source
118
0
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
460
0
        txiter it = result.position;
461
462
        // Now update the entry for ancestors/descendants.
463
0
        if (ancestors.has_value()) {
464
0
            addNewTransaction(it, *ancestors);
465
0
        } else {
466
0
            addNewTransaction(it);
467
0
        }
468
0
    }
469
0
}
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
0
{
479
0
    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
0
    cachedInnerUsage += entry.DynamicMemoryUsage();
485
486
0
    const CTransaction& tx = newit->GetTx();
487
0
    std::set<Txid> setParentTransactions;
488
0
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
489
0
        mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
490
0
        setParentTransactions.insert(tx.vin[i].prevout.hash);
491
0
    }
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
0
    for (const auto& pit : GetIterSet(setParentTransactions)) {
501
0
        UpdateParent(newit, pit, true);
502
0
    }
503
0
    UpdateAncestorsOf(true, newit, setAncestors);
504
0
    UpdateEntryForAncestors(newit, setAncestors);
505
506
0
    nTransactionsUpdated++;
507
0
    totalTxSize += entry.GetTxSize();
508
0
    m_total_fee += entry.GetFee();
509
510
0
    txns_randomized.emplace_back(newit->GetSharedTx());
511
0
    newit->idx_randomized = txns_randomized.size() - 1;
512
513
0
    TRACEPOINT(mempool, added,
514
0
        entry.GetTx().GetHash().data(),
515
0
        entry.GetTxSize(),
516
0
        entry.GetFee()
517
0
    );
518
0
}
519
520
void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
521
0
{
522
    // We increment mempool sequence value no matter removal reason
523
    // even if not directly reported below.
524
0
    uint64_t mempool_sequence = GetAndIncrementSequence();
525
526
0
    if (reason != MemPoolRemovalReason::BLOCK && m_opts.signals) {
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
0
        m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
532
0
    }
533
0
    TRACEPOINT(mempool, removed,
534
0
        it->GetTx().GetHash().data(),
535
0
        RemovalReasonToString(reason).c_str(),
536
0
        it->GetTxSize(),
537
0
        it->GetFee(),
538
0
        std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
539
0
    );
540
541
0
    for (const CTxIn& txin : it->GetTx().vin)
542
0
        mapNextTx.erase(txin.prevout);
543
544
0
    RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
545
546
0
    if (txns_randomized.size() > 1) {
547
        // Update idx_randomized of the to-be-moved entry.
548
0
        Assert(GetEntry(txns_randomized.back()->GetHash()))->idx_randomized = it->idx_randomized;
Line
Count
Source
106
0
#define Assert(val) inline_assertion_check<true>(val, __FILE__, __LINE__, __func__, #val)
549
        // Remove entry from txns_randomized by replacing it with the back and deleting the back.
550
0
        txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
551
0
        txns_randomized.pop_back();
552
0
        if (txns_randomized.size() * 2 < txns_randomized.capacity())
553
0
            txns_randomized.shrink_to_fit();
554
0
    } else
555
0
        txns_randomized.clear();
556
557
0
    totalTxSize -= it->GetTxSize();
558
0
    m_total_fee -= it->GetFee();
559
0
    cachedInnerUsage -= it->DynamicMemoryUsage();
560
0
    cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
561
0
    mapTx.erase(it);
562
0
    nTransactionsUpdated++;
563
0
}
564
565
// Calculates descendants of entry that are not already in setDescendants, and adds to
566
// setDescendants. Assumes entryit is already a tx in the mempool and CTxMemPoolEntry::m_children
567
// is correct for tx and all descendants.
568
// Also assumes that if an entry is in setDescendants already, then all
569
// in-mempool descendants of it are already in setDescendants as well, so that we
570
// can save time by not iterating over those entries.
571
void CTxMemPool::CalculateDescendants(txiter entryit, setEntries& setDescendants) const
572
0
{
573
0
    setEntries stage;
574
0
    if (setDescendants.count(entryit) == 0) {
575
0
        stage.insert(entryit);
576
0
    }
577
    // Traverse down the children of entry, only adding children that are not
578
    // accounted for in setDescendants already (because those children have either
579
    // already been walked, or will be walked in this iteration).
580
0
    while (!stage.empty()) {
581
0
        txiter it = *stage.begin();
582
0
        setDescendants.insert(it);
583
0
        stage.erase(it);
584
585
0
        const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
586
0
        for (const CTxMemPoolEntry& child : children) {
587
0
            txiter childiter = mapTx.iterator_to(child);
588
0
            if (!setDescendants.count(childiter)) {
589
0
                stage.insert(childiter);
590
0
            }
591
0
        }
592
0
    }
593
0
}
594
595
void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
596
0
{
597
    // Remove transaction from memory pool
598
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
599
0
    Assume(!m_have_changeset);
Line
Count
Source
118
0
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
600
0
        setEntries txToRemove;
601
0
        txiter origit = mapTx.find(origTx.GetHash());
602
0
        if (origit != mapTx.end()) {
603
0
            txToRemove.insert(origit);
604
0
        } else {
605
            // When recursively removing but origTx isn't in the mempool
606
            // be sure to remove any children that are in the pool. This can
607
            // happen during chain re-orgs if origTx isn't re-accepted into
608
            // the mempool for any reason.
609
0
            for (unsigned int i = 0; i < origTx.vout.size(); i++) {
610
0
                auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
611
0
                if (it == mapNextTx.end())
612
0
                    continue;
613
0
                txiter nextit = mapTx.find(it->second->GetHash());
614
0
                assert(nextit != mapTx.end());
615
0
                txToRemove.insert(nextit);
616
0
            }
617
0
        }
618
0
        setEntries setAllRemoves;
619
0
        for (txiter it : txToRemove) {
620
0
            CalculateDescendants(it, setAllRemoves);
621
0
        }
622
623
0
        RemoveStaged(setAllRemoves, false, reason);
624
0
}
625
626
void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
627
55
{
628
    // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
629
55
    AssertLockHeld(cs);
Line
Count
Source
142
55
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
630
55
    AssertLockHeld(::cs_main);
Line
Count
Source
142
55
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
631
55
    Assume(!m_have_changeset);
Line
Count
Source
118
55
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
632
633
55
    setEntries txToRemove;
634
55
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); 
it++0
) {
635
0
        if (check_final_and_mature(it)) txToRemove.insert(it);
636
0
    }
637
55
    setEntries setAllRemoves;
638
55
    for (txiter it : txToRemove) {
639
0
        CalculateDescendants(it, setAllRemoves);
640
0
    }
641
55
    RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
642
55
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); 
it++0
) {
643
0
        assert(TestLockPointValidity(chain, it->GetLockPoints()));
644
0
    }
645
55
}
646
647
void CTxMemPool::removeConflicts(const CTransaction &tx)
648
10.0M
{
649
    // Remove transactions which depend on inputs of tx, recursively
650
10.0M
    AssertLockHeld(cs);
Line
Count
Source
142
10.0M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
651
10.0M
    for (const CTxIn &txin : tx.vin) {
652
10.0M
        auto it = mapNextTx.find(txin.prevout);
653
10.0M
        if (it != mapNextTx.end()) {
654
0
            const CTransaction &txConflict = *it->second;
655
0
            if (txConflict != tx)
656
0
            {
657
0
                ClearPrioritisation(txConflict.GetHash());
658
0
                removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
659
0
            }
660
0
        }
661
10.0M
    }
662
10.0M
}
663
664
/**
665
 * Called when a block is connected. Removes from mempool.
666
 */
667
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
668
10.0M
{
669
10.0M
    AssertLockHeld(cs);
Line
Count
Source
142
10.0M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
670
10.0M
    Assume(!m_have_changeset);
Line
Count
Source
118
10.0M
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
671
10.0M
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
672
10.0M
    txs_removed_for_block.reserve(vtx.size());
673
10.0M
    for (const auto& tx : vtx)
674
10.0M
    {
675
10.0M
        txiter it = mapTx.find(tx->GetHash());
676
10.0M
        if (it != mapTx.end()) {
677
0
            setEntries stage;
678
0
            stage.insert(it);
679
0
            txs_removed_for_block.emplace_back(*it);
680
0
            RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
681
0
        }
682
10.0M
        removeConflicts(*tx);
683
10.0M
        ClearPrioritisation(tx->GetHash());
684
10.0M
    }
685
10.0M
    if (m_opts.signals) {
686
10.0M
        m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
687
10.0M
    }
688
10.0M
    lastRollingFeeUpdate = GetTime();
689
10.0M
    blockSinceLastRollingFeeBump = true;
690
10.0M
}
691
692
void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
693
10.0M
{
694
10.0M
    if (m_opts.check_ratio == 0) 
return0
;
695
696
10.0M
    if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) 
return0
;
697
698
10.0M
    AssertLockHeld(::cs_main);
Line
Count
Source
142
10.0M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
699
10.0M
    LOCK(cs);
Line
Count
Source
257
10.0M
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
10.0M
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
10.0M
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
10.0M
#define PASTE(x, y) x ## y
700
10.0M
    LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
Line
Count
Source
280
10.0M
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
273
10.0M
    do {                                                  \
274
10.0M
        if (LogAcceptCategory((category), (level))) {     \
275
0
            LogPrintLevel_(category, level, __VA_ARGS__); \
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
276
0
        }                                                 \
277
10.0M
    } while (0)
701
702
10.0M
    uint64_t checkTotal = 0;
703
10.0M
    CAmount check_total_fee{0};
704
10.0M
    uint64_t innerUsage = 0;
705
10.0M
    uint64_t prev_ancestor_count{0};
706
707
10.0M
    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
708
709
10.0M
    for (const auto& it : GetSortedDepthAndScore()) {
710
0
        checkTotal += it->GetTxSize();
711
0
        check_total_fee += it->GetFee();
712
0
        innerUsage += it->DynamicMemoryUsage();
713
0
        const CTransaction& tx = it->GetTx();
714
0
        innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
715
0
        CTxMemPoolEntry::Parents setParentCheck;
716
0
        for (const CTxIn &txin : tx.vin) {
717
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
718
0
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
719
0
            if (it2 != mapTx.end()) {
720
0
                const CTransaction& tx2 = it2->GetTx();
721
0
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
722
0
                setParentCheck.insert(*it2);
723
0
            }
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
0
            assert(mempoolDuplicate.HaveCoin(txin.prevout));
728
            // Check whether its inputs are marked in mapNextTx.
729
0
            auto it3 = mapNextTx.find(txin.prevout);
730
0
            assert(it3 != mapNextTx.end());
731
0
            assert(it3->first == &txin.prevout);
732
0
            assert(it3->second == &tx);
733
0
        }
734
0
        auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
735
0
            return a.GetTx().GetHash() == b.GetTx().GetHash();
736
0
        };
737
0
        assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
738
0
        assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
739
        // Verify ancestor state is correct.
740
0
        auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
741
0
        uint64_t nCountCheck = ancestors.size() + 1;
742
0
        int32_t nSizeCheck = it->GetTxSize();
743
0
        CAmount nFeesCheck = it->GetModifiedFee();
744
0
        int64_t nSigOpCheck = it->GetSigOpCost();
745
746
0
        for (txiter ancestorIt : ancestors) {
747
0
            nSizeCheck += ancestorIt->GetTxSize();
748
0
            nFeesCheck += ancestorIt->GetModifiedFee();
749
0
            nSigOpCheck += ancestorIt->GetSigOpCost();
750
0
        }
751
752
0
        assert(it->GetCountWithAncestors() == nCountCheck);
753
0
        assert(it->GetSizeWithAncestors() == nSizeCheck);
754
0
        assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
755
0
        assert(it->GetModFeesWithAncestors() == nFeesCheck);
756
        // Sanity check: we are walking in ascending ancestor count order.
757
0
        assert(prev_ancestor_count <= it->GetCountWithAncestors());
758
0
        prev_ancestor_count = it->GetCountWithAncestors();
759
760
        // Check children against mapNextTx
761
0
        CTxMemPoolEntry::Children setChildrenCheck;
762
0
        auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
763
0
        int32_t child_sizes{0};
764
0
        for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
765
0
            txiter childit = mapTx.find(iter->second->GetHash());
766
0
            assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
767
0
            if (setChildrenCheck.insert(*childit).second) {
768
0
                child_sizes += childit->GetTxSize();
769
0
            }
770
0
        }
771
0
        assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
772
0
        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
0
        assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
776
777
0
        TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
778
0
        CAmount txfee = 0;
779
0
        assert(!tx.IsCoinBase());
780
0
        assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
781
0
        for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
782
0
        AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
783
0
    }
784
10.0M
    for (auto it = mapNextTx.cbegin(); it != mapNextTx.cend(); 
it++0
) {
785
0
        uint256 hash = it->second->GetHash();
786
0
        indexed_transaction_set::const_iterator it2 = mapTx.find(hash);
787
0
        const CTransaction& tx = it2->GetTx();
788
0
        assert(it2 != mapTx.end());
789
0
        assert(&tx == it->second);
790
0
    }
791
792
10.0M
    assert(totalTxSize == checkTotal);
793
10.0M
    assert(m_total_fee == check_total_fee);
794
10.0M
    assert(innerUsage == cachedInnerUsage);
795
10.0M
}
796
797
bool CTxMemPool::CompareDepthAndScore(const uint256& hasha, const uint256& hashb, bool wtxid)
798
0
{
799
    /* Return `true` if hasha should be considered sooner than hashb. Namely when:
800
     *   a is not in the mempool, but b is
801
     *   both are in the mempool and a has fewer ancestors than b
802
     *   both are in the mempool and a has a higher score than b
803
     */
804
0
    LOCK(cs);
Line
Count
Source
257
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
805
0
    indexed_transaction_set::const_iterator j = wtxid ? get_iter_from_wtxid(hashb) : mapTx.find(hashb);
806
0
    if (j == mapTx.end()) return false;
807
0
    indexed_transaction_set::const_iterator i = wtxid ? get_iter_from_wtxid(hasha) : mapTx.find(hasha);
808
0
    if (i == mapTx.end()) return true;
809
0
    uint64_t counta = i->GetCountWithAncestors();
810
0
    uint64_t countb = j->GetCountWithAncestors();
811
0
    if (counta == countb) {
812
0
        return CompareTxMemPoolEntryByScore()(*i, *j);
813
0
    }
814
0
    return counta < countb;
815
0
}
816
817
namespace {
818
class DepthAndScoreComparator
819
{
820
public:
821
    bool operator()(const CTxMemPool::indexed_transaction_set::const_iterator& a, const CTxMemPool::indexed_transaction_set::const_iterator& b)
822
0
    {
823
0
        uint64_t counta = a->GetCountWithAncestors();
824
0
        uint64_t countb = b->GetCountWithAncestors();
825
0
        if (counta == countb) {
826
0
            return CompareTxMemPoolEntryByScore()(*a, *b);
827
0
        }
828
0
        return counta < countb;
829
0
    }
830
};
831
} // namespace
832
833
std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
834
10.0M
{
835
10.0M
    std::vector<indexed_transaction_set::const_iterator> iters;
836
10.0M
    AssertLockHeld(cs);
Line
Count
Source
142
10.0M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
837
838
10.0M
    iters.reserve(mapTx.size());
839
840
10.0M
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); 
++mi0
) {
841
0
        iters.push_back(mi);
842
0
    }
843
10.0M
    std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
844
10.0M
    return iters;
845
10.0M
}
846
847
0
static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it) {
848
0
    return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
849
0
}
850
851
std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
852
0
{
853
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
854
855
0
    std::vector<CTxMemPoolEntryRef> ret;
856
0
    ret.reserve(mapTx.size());
857
0
    for (const auto& it : GetSortedDepthAndScore()) {
858
0
        ret.emplace_back(*it);
859
0
    }
860
0
    return ret;
861
0
}
862
863
std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
864
0
{
865
0
    LOCK(cs);
Line
Count
Source
257
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
866
0
    auto iters = GetSortedDepthAndScore();
867
868
0
    std::vector<TxMempoolInfo> ret;
869
0
    ret.reserve(mapTx.size());
870
0
    for (auto it : iters) {
871
0
        ret.push_back(GetInfo(it));
872
0
    }
873
874
0
    return ret;
875
0
}
876
877
const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
878
0
{
879
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
880
0
    const auto i = mapTx.find(txid);
881
0
    return i == mapTx.end() ? nullptr : &(*i);
882
0
}
883
884
CTransactionRef CTxMemPool::get(const uint256& hash) const
885
0
{
886
0
    LOCK(cs);
Line
Count
Source
257
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
887
0
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
888
0
    if (i == mapTx.end())
889
0
        return nullptr;
890
0
    return i->GetSharedTx();
891
0
}
892
893
TxMempoolInfo CTxMemPool::info(const GenTxid& gtxid) const
894
0
{
895
0
    LOCK(cs);
Line
Count
Source
257
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
896
0
    indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
897
0
    if (i == mapTx.end())
898
0
        return TxMempoolInfo();
899
0
    return GetInfo(i);
900
0
}
901
902
TxMempoolInfo CTxMemPool::info_for_relay(const GenTxid& gtxid, uint64_t last_sequence) const
903
0
{
904
0
    LOCK(cs);
Line
Count
Source
257
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
905
0
    indexed_transaction_set::const_iterator i = (gtxid.IsWtxid() ? get_iter_from_wtxid(gtxid.GetHash()) : mapTx.find(gtxid.GetHash()));
906
0
    if (i != mapTx.end() && i->GetSequence() < last_sequence) {
907
0
        return GetInfo(i);
908
0
    } else {
909
0
        return TxMempoolInfo();
910
0
    }
911
0
}
912
913
void CTxMemPool::PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta)
914
0
{
915
0
    {
916
0
        LOCK(cs);
Line
Count
Source
257
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
917
0
        CAmount &delta = mapDeltas[hash];
918
0
        delta = SaturatingAdd(delta, nFeeDelta);
919
0
        txiter it = mapTx.find(hash);
920
0
        if (it != mapTx.end()) {
921
0
            mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
922
            // Now update all ancestors' modified fees with descendants
923
0
            auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
924
0
            for (txiter ancestorIt : ancestors) {
925
0
                mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
926
0
            }
927
            // Now update all descendants' modified fees with ancestors
928
0
            setEntries setDescendants;
929
0
            CalculateDescendants(it, setDescendants);
930
0
            setDescendants.erase(it);
931
0
            for (txiter descendantIt : setDescendants) {
932
0
                mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
933
0
            }
934
0
            ++nTransactionsUpdated;
935
0
        }
936
0
        if (delta == 0) {
937
0
            mapDeltas.erase(hash);
938
0
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
Line
Count
Source
266
0
#define LogPrintf(...) LogInfo(__VA_ARGS__)
Line
Count
Source
261
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
939
0
        } else {
940
0
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
Line
Count
Source
266
0
#define LogPrintf(...) LogInfo(__VA_ARGS__)
Line
Count
Source
261
0
#define LogInfo(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Info, __VA_ARGS__)
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
941
0
                      hash.ToString(),
942
0
                      it == mapTx.end() ? "not " : "",
943
0
                      FormatMoney(nFeeDelta),
944
0
                      FormatMoney(delta));
945
0
        }
946
0
    }
947
0
}
948
949
void CTxMemPool::ApplyDelta(const uint256& hash, CAmount &nFeeDelta) const
950
0
{
951
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
952
0
    std::map<uint256, CAmount>::const_iterator pos = mapDeltas.find(hash);
953
0
    if (pos == mapDeltas.end())
954
0
        return;
955
0
    const CAmount &delta = pos->second;
956
0
    nFeeDelta += delta;
957
0
}
958
959
void CTxMemPool::ClearPrioritisation(const uint256& hash)
960
10.0M
{
961
10.0M
    AssertLockHeld(cs);
Line
Count
Source
142
10.0M
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
962
10.0M
    mapDeltas.erase(hash);
963
10.0M
}
964
965
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
966
0
{
967
0
    AssertLockNotHeld(cs);
Line
Count
Source
147
0
#define AssertLockNotHeld(cs) AssertLockNotHeldInline(#cs, __FILE__, __LINE__, &cs)
968
0
    LOCK(cs);
Line
Count
Source
257
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
969
0
    std::vector<delta_info> result;
970
0
    result.reserve(mapDeltas.size());
971
0
    for (const auto& [txid, delta] : mapDeltas) {
972
0
        const auto iter{mapTx.find(txid)};
973
0
        const bool in_mempool{iter != mapTx.end()};
974
0
        std::optional<CAmount> modified_fee;
975
0
        if (in_mempool) modified_fee = iter->GetModifiedFee();
976
0
        result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
977
0
    }
978
0
    return result;
979
0
}
980
981
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
982
0
{
983
0
    const auto it = mapNextTx.find(prevout);
984
0
    return it == mapNextTx.end() ? nullptr : it->second;
985
0
}
986
987
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const uint256& txid) const
988
0
{
989
0
    auto it = mapTx.find(txid);
990
0
    if (it != mapTx.end()) return it;
991
0
    return std::nullopt;
992
0
}
993
994
CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
995
0
{
996
0
    CTxMemPool::setEntries ret;
997
0
    for (const auto& h : hashes) {
998
0
        const auto mi = GetIter(h);
999
0
        if (mi) ret.insert(*mi);
1000
0
    }
1001
0
    return ret;
1002
0
}
1003
1004
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<uint256>& txids) const
1005
0
{
1006
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1007
0
    std::vector<txiter> ret;
1008
0
    ret.reserve(txids.size());
1009
0
    for (const auto& txid : txids) {
1010
0
        const auto it{GetIter(txid)};
1011
0
        if (!it) return {};
1012
0
        ret.push_back(*it);
1013
0
    }
1014
0
    return ret;
1015
0
}
1016
1017
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
1018
0
{
1019
0
    for (unsigned int i = 0; i < tx.vin.size(); i++)
1020
0
        if (exists(GenTxid::Txid(tx.vin[i].prevout.hash)))
1021
0
            return false;
1022
0
    return true;
1023
0
}
1024
1025
0
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1026
1027
std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
1028
0
{
1029
    // Check to see if the inputs are made available by another tx in the package.
1030
    // These Coins would not be available in the underlying CoinsView.
1031
0
    if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1032
0
        return it->second;
1033
0
    }
1034
1035
    // If an entry in the mempool exists, always return that one, as it's guaranteed to never
1036
    // conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
1037
    // transactions. First checking the underlying cache risks returning a pruned entry instead.
1038
0
    CTransactionRef ptx = mempool.get(outpoint.hash);
1039
0
    if (ptx) {
1040
0
        if (outpoint.n < ptx->vout.size()) {
1041
0
            Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1042
0
            m_non_base_coins.emplace(outpoint);
1043
0
            return coin;
1044
0
        }
1045
0
        return std::nullopt;
1046
0
    }
1047
0
    return base->GetCoin(outpoint);
1048
0
}
1049
1050
void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1051
0
{
1052
0
    for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1053
0
        m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1054
0
        m_non_base_coins.emplace(tx->GetHash(), n);
1055
0
    }
1056
0
}
1057
void CCoinsViewMemPool::Reset()
1058
0
{
1059
0
    m_temp_added.clear();
1060
0
    m_non_base_coins.clear();
1061
0
}
1062
1063
30.0M
size_t CTxMemPool::DynamicMemoryUsage() const {
1064
30.0M
    LOCK(cs);
Line
Count
Source
257
30.0M
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
30.0M
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
30.0M
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
30.0M
#define PASTE(x, y) x ## y
1065
    // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1066
30.0M
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1067
30.0M
}
1068
1069
0
void CTxMemPool::RemoveUnbroadcastTx(const uint256& txid, const bool unchecked) {
1070
0
    LOCK(cs);
Line
Count
Source
257
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
1071
1072
0
    if (m_unbroadcast_txids.erase(txid))
1073
0
    {
1074
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
280
0
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
273
0
    do {                                                  \
274
0
        if (LogAcceptCategory((category), (level))) {     \
275
0
            LogPrintLevel_(category, level, __VA_ARGS__); \
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
276
0
        }                                                 \
277
0
    } while (0)
1075
0
    }
1076
0
}
1077
1078
110
void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1079
110
    AssertLockHeld(cs);
Line
Count
Source
142
110
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1080
110
    UpdateForRemoveFromMempool(stage, updateDescendants);
1081
110
    for (txiter it : stage) {
1082
0
        removeUnchecked(it, reason);
1083
0
    }
1084
110
}
1085
1086
int CTxMemPool::Expire(std::chrono::seconds time)
1087
55
{
1088
55
    AssertLockHeld(cs);
Line
Count
Source
142
55
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1089
55
    Assume(!m_have_changeset);
Line
Count
Source
118
55
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1090
55
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1091
55
    setEntries toremove;
1092
55
    while (it != mapTx.get<entry_time>().end() && 
it->GetTime() < time0
) {
1093
0
        toremove.insert(mapTx.project<0>(it));
1094
0
        it++;
1095
0
    }
1096
55
    setEntries stage;
1097
55
    for (txiter removeit : toremove) {
1098
0
        CalculateDescendants(removeit, stage);
1099
0
    }
1100
55
    RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1101
55
    return stage.size();
1102
55
}
1103
1104
void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1105
0
{
1106
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1107
0
    CTxMemPoolEntry::Children s;
1108
0
    if (add && entry->GetMemPoolChildren().insert(*child).second) {
1109
0
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1110
0
    } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1111
0
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1112
0
    }
1113
0
}
1114
1115
void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1116
0
{
1117
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1118
0
    CTxMemPoolEntry::Parents s;
1119
0
    if (add && entry->GetMemPoolParents().insert(*parent).second) {
1120
0
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1121
0
    } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1122
0
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1123
0
    }
1124
0
}
1125
1126
107k
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1127
107k
    LOCK(cs);
Line
Count
Source
257
107k
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
107k
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
107k
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
107k
#define PASTE(x, y) x ## y
1128
107k
    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1129
107k
        return CFeeRate(llround(rollingMinimumFeeRate));
1130
1131
0
    int64_t time = GetTime();
1132
0
    if (time > lastRollingFeeUpdate + 10) {
1133
0
        double halflife = ROLLING_FEE_HALFLIFE;
1134
0
        if (DynamicMemoryUsage() < sizelimit / 4)
1135
0
            halflife /= 4;
1136
0
        else if (DynamicMemoryUsage() < sizelimit / 2)
1137
0
            halflife /= 2;
1138
1139
0
        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1140
0
        lastRollingFeeUpdate = time;
1141
1142
0
        if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1143
0
            rollingMinimumFeeRate = 0;
1144
0
            return CFeeRate(0);
1145
0
        }
1146
0
    }
1147
0
    return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1148
0
}
1149
1150
0
void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1151
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1152
0
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1153
0
        rollingMinimumFeeRate = rate.GetFeePerK();
1154
0
        blockSinceLastRollingFeeBump = false;
1155
0
    }
1156
0
}
1157
1158
55
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1159
55
    AssertLockHeld(cs);
Line
Count
Source
142
55
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1160
55
    Assume(!m_have_changeset);
Line
Count
Source
118
55
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1161
1162
55
    unsigned nTxnRemoved = 0;
1163
55
    CFeeRate maxFeeRateRemoved(0);
1164
55
    while (!mapTx.empty() && 
DynamicMemoryUsage() > sizelimit0
) {
1165
0
        indexed_transaction_set::index<descendant_score>::type::iterator it = mapTx.get<descendant_score>().begin();
1166
1167
        // We set the new mempool min fee to the feerate of the removed set, plus the
1168
        // "minimum reasonable fee rate" (ie some value under which we consider txn
1169
        // to have 0 fee). This way, we don't allow txn to enter mempool with feerate
1170
        // equal to txn which were removed with no block in between.
1171
0
        CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1172
0
        removed += m_opts.incremental_relay_feerate;
1173
0
        trackPackageRemoved(removed);
1174
0
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1175
1176
0
        setEntries stage;
1177
0
        CalculateDescendants(mapTx.project<0>(it), stage);
1178
0
        nTxnRemoved += stage.size();
1179
1180
0
        std::vector<CTransaction> txn;
1181
0
        if (pvNoSpendsRemaining) {
1182
0
            txn.reserve(stage.size());
1183
0
            for (txiter iter : stage)
1184
0
                txn.push_back(iter->GetTx());
1185
0
        }
1186
0
        RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1187
0
        if (pvNoSpendsRemaining) {
1188
0
            for (const CTransaction& tx : txn) {
1189
0
                for (const CTxIn& txin : tx.vin) {
1190
0
                    if (exists(GenTxid::Txid(txin.prevout.hash))) continue;
1191
0
                    pvNoSpendsRemaining->push_back(txin.prevout);
1192
0
                }
1193
0
            }
1194
0
        }
1195
0
    }
1196
1197
55
    if (maxFeeRateRemoved > CFeeRate(0)) {
1198
0
        LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
Line
Count
Source
280
0
#define LogDebug(category, ...) LogPrintLevel(category, BCLog::Level::Debug, __VA_ARGS__)
Line
Count
Source
273
0
    do {                                                  \
274
0
        if (LogAcceptCategory((category), (level))) {     \
275
0
            LogPrintLevel_(category, level, __VA_ARGS__); \
Line
Count
Source
255
0
#define LogPrintLevel_(category, level, ...) LogPrintFormatInternal(__func__, __FILE__, __LINE__, category, level, __VA_ARGS__)
276
0
        }                                                 \
277
0
    } while (0)
1199
0
    }
1200
55
}
1201
1202
0
uint64_t CTxMemPool::CalculateDescendantMaximum(txiter entry) const {
1203
    // find parent with highest descendant count
1204
0
    std::vector<txiter> candidates;
1205
0
    setEntries counted;
1206
0
    candidates.push_back(entry);
1207
0
    uint64_t maximum = 0;
1208
0
    while (candidates.size()) {
1209
0
        txiter candidate = candidates.back();
1210
0
        candidates.pop_back();
1211
0
        if (!counted.insert(candidate).second) continue;
1212
0
        const CTxMemPoolEntry::Parents& parents = candidate->GetMemPoolParentsConst();
1213
0
        if (parents.size() == 0) {
1214
0
            maximum = std::max(maximum, candidate->GetCountWithDescendants());
1215
0
        } else {
1216
0
            for (const CTxMemPoolEntry& i : parents) {
1217
0
                candidates.push_back(mapTx.iterator_to(i));
1218
0
            }
1219
0
        }
1220
0
    }
1221
0
    return maximum;
1222
0
}
1223
1224
0
void CTxMemPool::GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* const ancestorsize, CAmount* const ancestorfees) const {
1225
0
    LOCK(cs);
Line
Count
Source
257
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
1226
0
    auto it = mapTx.find(txid);
1227
0
    ancestors = descendants = 0;
1228
0
    if (it != mapTx.end()) {
1229
0
        ancestors = it->GetCountWithAncestors();
1230
0
        if (ancestorsize) *ancestorsize = it->GetSizeWithAncestors();
1231
0
        if (ancestorfees) *ancestorfees = it->GetModFeesWithAncestors();
1232
0
        descendants = CalculateDescendantMaximum(it);
1233
0
    }
1234
0
}
1235
1236
bool CTxMemPool::GetLoadTried() const
1237
0
{
1238
0
    LOCK(cs);
Line
Count
Source
257
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
1239
0
    return m_load_tried;
1240
0
}
1241
1242
void CTxMemPool::SetLoadTried(bool load_tried)
1243
0
{
1244
0
    LOCK(cs);
Line
Count
Source
257
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
1245
0
    m_load_tried = load_tried;
1246
0
}
1247
1248
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<uint256>& txids) const
1249
0
{
1250
0
    AssertLockHeld(cs);
Line
Count
Source
142
0
#define AssertLockHeld(cs) AssertLockHeldInternal(#cs, __FILE__, __LINE__, &cs)
1251
0
    std::vector<txiter> clustered_txs{GetIterVec(txids)};
1252
    // Use epoch: visiting an entry means we have added it to the clustered_txs vector. It does not
1253
    // necessarily mean the entry has been processed.
1254
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
1255
0
    for (const auto& it : clustered_txs) {
1256
0
        visited(it);
1257
0
    }
1258
    // i = index of where the list of entries to process starts
1259
0
    for (size_t i{0}; i < clustered_txs.size(); ++i) {
1260
        // DoS protection: if there are 500 or more entries to process, just quit.
1261
0
        if (clustered_txs.size() > 500) return {};
1262
0
        const txiter& tx_iter = clustered_txs.at(i);
1263
0
        for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
1264
0
            for (const CTxMemPoolEntry& entry : entries) {
1265
0
                const auto entry_it = mapTx.iterator_to(entry);
1266
0
                if (!visited(entry_it)) {
1267
0
                    clustered_txs.push_back(entry_it);
1268
0
                }
1269
0
            }
1270
0
        }
1271
0
    }
1272
0
    return clustered_txs;
1273
0
}
1274
1275
std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1276
0
{
1277
0
    for (const auto& direct_conflict : direct_conflicts) {
1278
        // Ancestor and descendant counts are inclusive of the tx itself.
1279
0
        const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1280
0
        const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1281
0
        const bool has_ancestor{ancestor_count > 1};
1282
0
        const bool has_descendant{descendant_count > 1};
1283
0
        const auto& txid_string{direct_conflict->GetSharedTx()->GetHash().ToString()};
1284
        // The only allowed configurations are:
1285
        // 1 ancestor and 0 descendant
1286
        // 0 ancestor and 1 descendant
1287
        // 0 ancestor and 0 descendant
1288
0
        if (ancestor_count > 2) {
1289
0
            return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
Line
Count
Source
1172
0
#define strprintf tfm::format
1290
0
        } else if (descendant_count > 2) {
1291
0
            return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
Line
Count
Source
1172
0
#define strprintf tfm::format
1292
0
        } else if (has_ancestor && has_descendant) {
1293
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
1294
0
        }
1295
        // Additionally enforce that:
1296
        // If we have a child,  we are its only parent.
1297
        // If we have a parent, we are its only child.
1298
0
        if (has_descendant) {
1299
0
            const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1300
0
            if (our_child->get().GetCountWithAncestors() > 2) {
1301
0
                return strprintf("%s is not the only parent of child %s",
Line
Count
Source
1172
0
#define strprintf tfm::format
1302
0
                                 txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
1303
0
            }
1304
0
        } else if (has_ancestor) {
1305
0
            const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1306
0
            if (our_parent->get().GetCountWithDescendants() > 2) {
1307
0
                return strprintf("%s is not the only child of parent %s",
Line
Count
Source
1172
0
#define strprintf tfm::format
1308
0
                                 txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
1309
0
            }
1310
0
        }
1311
0
    }
1312
0
    return std::nullopt;
1313
0
}
1314
1315
util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1316
0
{
1317
0
    LOCK(m_pool->cs);
Line
Count
Source
257
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
1318
0
    FeeFrac replacement_feerate{0, 0};
1319
0
    for (auto it : m_entry_vec) {
1320
0
        replacement_feerate += {it->GetModifiedFee(), it->GetTxSize()};
1321
0
    }
1322
1323
0
    auto err_string{m_pool->CheckConflictTopology(m_to_remove)};
1324
0
    if (err_string.has_value()) {
1325
        // Unsupported topology for calculating a feerate diagram
1326
0
        return util::Error{Untranslated(err_string.value())};
1327
0
    }
1328
1329
    // new diagram will have chunks that consist of each ancestor of
1330
    // direct_conflicts that is at its own fee/size, along with the replacement
1331
    // tx/package at its own fee/size
1332
1333
    // old diagram will consist of the ancestors and descendants of each element of
1334
    // all_conflicts.  every such transaction will either be at its own feerate (followed
1335
    // by any descendant at its own feerate), or as a single chunk at the descendant's
1336
    // ancestor feerate.
1337
1338
0
    std::vector<FeeFrac> old_chunks;
1339
    // Step 1: build the old diagram.
1340
1341
    // The above clusters are all trivially linearized;
1342
    // they have a strict topology of 1 or two connected transactions.
1343
1344
    // OLD: Compute existing chunks from all affected clusters
1345
0
    for (auto txiter : m_to_remove) {
1346
        // Does this transaction have descendants?
1347
0
        if (txiter->GetCountWithDescendants() > 1) {
1348
            // Consider this tx when we consider the descendant.
1349
0
            continue;
1350
0
        }
1351
        // Does this transaction have ancestors?
1352
0
        FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
1353
0
        if (txiter->GetCountWithAncestors() > 1) {
1354
            // We'll add chunks for either the ancestor by itself and this tx
1355
            // by itself, or for a combined package.
1356
0
            FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
1357
0
            if (individual >> package) {
1358
                // The individual feerate is higher than the package, and
1359
                // therefore higher than the parent's fee. Chunk these
1360
                // together.
1361
0
                old_chunks.emplace_back(package);
1362
0
            } else {
1363
                // Add two points, one for the parent and one for this child.
1364
0
                old_chunks.emplace_back(package - individual);
1365
0
                old_chunks.emplace_back(individual);
1366
0
            }
1367
0
        } else {
1368
0
            old_chunks.emplace_back(individual);
1369
0
        }
1370
0
    }
1371
1372
    // No topology restrictions post-chunking; sort
1373
0
    std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1374
1375
0
    std::vector<FeeFrac> new_chunks;
1376
1377
    /* Step 2: build the NEW diagram
1378
     * CON = Conflicts of proposed chunk
1379
     * CNK = Proposed chunk
1380
     * NEW = OLD - CON + CNK: New diagram includes all chunks in OLD, minus
1381
     * the conflicts, plus the proposed chunk
1382
     */
1383
1384
    // OLD - CON: Add any parents of direct conflicts that are not conflicted themselves
1385
0
    for (auto direct_conflict : m_to_remove) {
1386
        // If a direct conflict has an ancestor that is not in all_conflicts,
1387
        // it can be affected by the replacement of the child.
1388
0
        if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
1389
            // Grab the parent.
1390
0
            const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1391
0
            if (!m_to_remove.contains(m_pool->mapTx.iterator_to(parent))) {
1392
                // This transaction would be left over, so add to the NEW
1393
                // diagram.
1394
0
                new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
1395
0
            }
1396
0
        }
1397
0
    }
1398
    // + CNK: Add the proposed chunk itself
1399
0
    new_chunks.emplace_back(replacement_feerate);
1400
1401
    // No topology restrictions post-chunking; sort
1402
0
    std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1403
0
    return std::make_pair(old_chunks, new_chunks);
1404
0
}
1405
1406
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)
1407
0
{
1408
0
    LOCK(m_pool->cs);
Line
Count
Source
257
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
1409
0
    Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
Line
Count
Source
118
0
#define Assume(val) inline_assertion_check<false>(val, __FILE__, __LINE__, __func__, #val)
1410
0
    auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1411
0
    CAmount delta{0};
1412
0
    m_pool->ApplyDelta(tx->GetHash(), delta);
1413
0
    if (delta) m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
1414
1415
0
    m_entry_vec.push_back(newit);
1416
0
    return newit;
1417
0
}
1418
1419
void CTxMemPool::ChangeSet::Apply()
1420
0
{
1421
0
    LOCK(m_pool->cs);
Line
Count
Source
257
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
1422
0
    m_pool->Apply(this);
1423
0
    m_to_add.clear();
1424
0
    m_to_remove.clear();
1425
0
    m_entry_vec.clear();
1426
0
    m_ancestors.clear();
1427
0
}