Coverage Report

Created: 2025-09-08 17:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/txmempool.cpp
Line
Count
Source
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-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);
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
0
{
110
0
    AssertLockHeld(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
0
    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
0
    std::set<Txid> setAlreadyIncluded(vHashesToUpdate.begin(), vHashesToUpdate.end());
119
120
0
    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
0
    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);
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
0
    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
0
}
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
5.08M
{
169
5.08M
    int64_t totalSizeWithAncestors = entry_size;
170
5.08M
    setEntries ancestors;
171
172
31.7M
    while (!staged_ancestors.empty()) {
173
26.6M
        const CTxMemPoolEntry& stage = staged_ancestors.begin()->get();
174
26.6M
        txiter stageit = mapTx.iterator_to(stage);
175
176
26.6M
        ancestors.insert(stageit);
177
26.6M
        staged_ancestors.erase(stage);
178
26.6M
        totalSizeWithAncestors += stageit->GetTxSize();
179
180
26.6M
        if (stageit->GetSizeWithDescendants() + entry_size > limits.descendant_size_vbytes) {
181
12.6k
            return util::Error{Untranslated(strprintf("exceeds descendant size limit for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_size_vbytes))};
182
26.6M
        } else if (stageit->GetCountWithDescendants() + entry_count > static_cast<uint64_t>(limits.descendant_count)) {
183
9.59k
            return util::Error{Untranslated(strprintf("too many descendants for tx %s [limit: %u]", stageit->GetTx().GetHash().ToString(), limits.descendant_count))};
184
26.6M
        } else if (totalSizeWithAncestors > limits.ancestor_size_vbytes) {
185
5.96k
            return util::Error{Untranslated(strprintf("exceeds ancestor size limit [limit: %u]", limits.ancestor_size_vbytes))};
186
5.96k
        }
187
188
26.6M
        const CTxMemPoolEntry::Parents& parents = stageit->GetMemPoolParentsConst();
189
35.1M
        for (const CTxMemPoolEntry& parent : parents) {
190
35.1M
            txiter parent_it = mapTx.iterator_to(parent);
191
192
            // If this is a new ancestor, add it.
193
35.1M
            if (ancestors.count(parent_it) == 0) {
194
27.4M
                staged_ancestors.insert(parent);
195
27.4M
            }
196
35.1M
            if (staged_ancestors.size() + ancestors.size() + entry_count > static_cast<uint64_t>(limits.ancestor_count)) {
197
4.87k
                return util::Error{Untranslated(strprintf("too many unconfirmed ancestors [limit: %u]", limits.ancestor_count))};
198
4.87k
            }
199
35.1M
        }
200
26.6M
    }
201
202
5.05M
    return ancestors;
203
5.08M
}
204
205
util::Result<void> CTxMemPool::CheckPackageLimits(const Package& package,
206
                                                  const int64_t total_vsize) const
207
58.0k
{
208
58.0k
    size_t pack_count = package.size();
209
210
    // Package itself is busting mempool limits; should be rejected even if no staged_ancestors exist
211
58.0k
    if (pack_count > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
212
787
        return util::Error{Untranslated(strprintf("package count %u exceeds ancestor count limit [limit: %u]", pack_count, m_opts.limits.ancestor_count))};
213
57.2k
    } else if (pack_count > static_cast<uint64_t>(m_opts.limits.descendant_count)) {
214
445
        return util::Error{Untranslated(strprintf("package count %u exceeds descendant count limit [limit: %u]", pack_count, m_opts.limits.descendant_count))};
215
56.8k
    } else if (total_vsize > m_opts.limits.ancestor_size_vbytes) {
216
562
        return util::Error{Untranslated(strprintf("package size %u exceeds ancestor size limit [limit: %u]", total_vsize, m_opts.limits.ancestor_size_vbytes))};
217
56.2k
    } else if (total_vsize > m_opts.limits.descendant_size_vbytes) {
218
560
        return util::Error{Untranslated(strprintf("package size %u exceeds descendant size limit [limit: %u]", total_vsize, m_opts.limits.descendant_size_vbytes))};
219
560
    }
220
221
55.7k
    CTxMemPoolEntry::Parents staged_ancestors;
222
121k
    for (const auto& tx : package) {
223
300k
        for (const auto& input : tx->vin) {
224
300k
            std::optional<txiter> piter = GetIter(input.prevout.hash);
225
300k
            if (piter) {
226
57.0k
                staged_ancestors.insert(**piter);
227
57.0k
                if (staged_ancestors.size() + package.size() > static_cast<uint64_t>(m_opts.limits.ancestor_count)) {
228
614
                    return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", m_opts.limits.ancestor_count))};
229
614
                }
230
57.0k
            }
231
300k
        }
232
121k
    }
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
55.1k
    const auto ancestors{CalculateAncestorsAndCheckLimits(total_vsize, package.size(),
237
55.1k
                                                          staged_ancestors, m_opts.limits)};
238
    // It's possible to overestimate the ancestor/descendant totals.
239
55.1k
    if (!ancestors.has_value()) return util::Error{Untranslated("possibly " + util::ErrorString(ancestors).original)};
240
54.6k
    return {};
241
55.1k
}
242
243
util::Result<CTxMemPool::setEntries> CTxMemPool::CalculateMemPoolAncestors(
244
    const CTxMemPoolEntry &entry,
245
    const Limits& limits,
246
    bool fSearchForParents /* = true */) const
247
5.06M
{
248
5.06M
    CTxMemPoolEntry::Parents staged_ancestors;
249
5.06M
    const CTransaction &tx = entry.GetTx();
250
251
5.06M
    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
12.7M
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
256
9.06M
            std::optional<txiter> piter = GetIter(tx.vin[i].prevout.hash);
257
9.06M
            if (piter) {
258
4.74M
                staged_ancestors.insert(**piter);
259
4.74M
                if (staged_ancestors.size() + 1 > static_cast<uint64_t>(limits.ancestor_count)) {
260
36.7k
                    return util::Error{Untranslated(strprintf("too many unconfirmed parents [limit: %u]", limits.ancestor_count))};
261
36.7k
                }
262
4.74M
            }
263
9.06M
        }
264
3.75M
    } 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
1.31M
        txiter it = mapTx.iterator_to(entry);
268
1.31M
        staged_ancestors = it->GetMemPoolParentsConst();
269
1.31M
    }
270
271
5.03M
    return CalculateAncestorsAndCheckLimits(entry.GetTxSize(), /*entry_count=*/1, staged_ancestors,
272
5.03M
                                            limits);
273
5.06M
}
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
1.49M
{
281
1.49M
    auto result{CalculateMemPoolAncestors(entry, limits, fSearchForParents)};
282
1.49M
    if (!Assume(result)) {
283
0
        LogPrintLevel(BCLog::MEMPOOL, BCLog::Level::Error, "%s: CalculateMemPoolAncestors failed unexpectedly, continuing with empty ancestor set (%s)\n",
284
0
                      calling_fn_name, util::ErrorString(result).original);
285
0
    }
286
1.49M
    return std::move(result).value_or(CTxMemPool::setEntries{});
287
1.49M
}
288
289
void CTxMemPool::UpdateAncestorsOf(bool add, txiter it, setEntries &setAncestors)
290
2.99M
{
291
2.99M
    const CTxMemPoolEntry::Parents& parents = it->GetMemPoolParentsConst();
292
    // add or remove this tx as a child of each parent
293
2.99M
    for (const CTxMemPoolEntry& parent : parents) {
294
1.53M
        UpdateChild(mapTx.iterator_to(parent), it, add);
295
1.53M
    }
296
2.99M
    const int32_t updateCount = (add ? 1 : -1);
297
2.99M
    const int32_t updateSize{updateCount * it->GetTxSize()};
298
2.99M
    const CAmount updateFee = updateCount * it->GetModifiedFee();
299
24.5M
    for (txiter ancestorIt : setAncestors) {
300
24.5M
        mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e) { e.UpdateDescendantState(updateSize, updateFee, updateCount); });
301
24.5M
    }
302
2.99M
}
303
304
void CTxMemPool::UpdateEntryForAncestors(txiter it, const setEntries &setAncestors)
305
2.86M
{
306
2.86M
    int64_t updateCount = setAncestors.size();
307
2.86M
    int64_t updateSize = 0;
308
2.86M
    CAmount updateFee = 0;
309
2.86M
    int64_t updateSigOpsCost = 0;
310
24.4M
    for (txiter ancestorIt : setAncestors) {
311
24.4M
        updateSize += ancestorIt->GetTxSize();
312
24.4M
        updateFee += ancestorIt->GetModifiedFee();
313
24.4M
        updateSigOpsCost += ancestorIt->GetSigOpCost();
314
24.4M
    }
315
2.86M
    mapTx.modify(it, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(updateSize, updateFee, updateCount, updateSigOpsCost); });
316
2.86M
}
317
318
void CTxMemPool::UpdateChildrenForRemoval(txiter it)
319
130k
{
320
130k
    const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
321
130k
    for (const CTxMemPoolEntry& updateIt : children) {
322
0
        UpdateParent(mapTx.iterator_to(updateIt), it, false);
323
0
    }
324
130k
}
325
326
void CTxMemPool::UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants)
327
3.38M
{
328
    // For each entry, walk back all ancestors and decrement size associated with this
329
    // transaction
330
3.38M
    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
3.38M
    for (txiter removeIt : entriesToRemove) {
350
130k
        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
130k
        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
130k
        UpdateAncestorsOf(false, removeIt, ancestors);
374
130k
    }
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
3.38M
    for (txiter removeIt : entriesToRemove) {
379
130k
        UpdateChildrenForRemoval(removeIt);
380
130k
    }
381
3.38M
}
382
383
void CTxMemPoolEntry::UpdateDescendantState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount)
384
25.6M
{
385
25.6M
    nSizeWithDescendants += modifySize;
386
25.6M
    assert(nSizeWithDescendants > 0);
387
25.6M
    nModFeesWithDescendants = SaturatingAdd(nModFeesWithDescendants, modifyFee);
388
25.6M
    m_count_with_descendants += modifyCount;
389
25.6M
    assert(m_count_with_descendants > 0);
390
25.6M
}
391
392
void CTxMemPoolEntry::UpdateAncestorState(int32_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps)
393
2.98M
{
394
2.98M
    nSizeWithAncestors += modifySize;
395
2.98M
    assert(nSizeWithAncestors > 0);
396
2.98M
    nModFeesWithAncestors = SaturatingAdd(nModFeesWithAncestors, modifyFee);
397
2.98M
    m_count_with_ancestors += modifyCount;
398
2.98M
    assert(m_count_with_ancestors > 0);
399
2.98M
    nSigOpCostWithAncestors += modifySigOps;
400
2.98M
    assert(int(nSigOpCostWithAncestors) >= 0);
401
2.98M
}
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
28.8k
{
406
28.8k
    opts.check_ratio = std::clamp<int>(opts.check_ratio, 0, 1'000'000);
407
28.8k
    int64_t descendant_limit_bytes = opts.limits.descendant_size_vbytes * 40;
408
28.8k
    if (opts.max_size_bytes < 0 || opts.max_size_bytes < descendant_limit_bytes) {
409
1.90k
        error = strprintf(_("-maxmempool must be at least %d MB"), std::ceil(descendant_limit_bytes / 1'000'000.0));
410
1.90k
    }
411
28.8k
    return std::move(opts);
412
28.8k
}
413
414
CTxMemPool::CTxMemPool(Options opts, bilingual_str& error)
415
28.8k
    : m_opts{Flatten(std::move(opts), error)}
416
28.8k
{
417
28.8k
}
418
419
bool CTxMemPool::isSpent(const COutPoint& outpoint) const
420
17
{
421
17
    LOCK(cs);
422
17
    return mapNextTx.count(outpoint);
423
17
}
424
425
unsigned int CTxMemPool::GetTransactionsUpdated() const
426
0
{
427
0
    return nTransactionsUpdated;
428
0
}
429
430
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
431
230k
{
432
230k
    nTransactionsUpdated += n;
433
230k
}
434
435
void CTxMemPool::Apply(ChangeSet* changeset)
436
2.85M
{
437
2.85M
    AssertLockHeld(cs);
438
2.85M
    RemoveStaged(changeset->m_to_remove, false, MemPoolRemovalReason::REPLACED);
439
440
5.72M
    for (size_t i=0; i<changeset->m_entry_vec.size(); ++i) {
441
2.86M
        auto tx_entry = changeset->m_entry_vec[i];
442
2.86M
        std::optional<CTxMemPool::setEntries> ancestors;
443
2.86M
        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
2.85M
            ancestors = *Assume(changeset->CalculateMemPoolAncestors(tx_entry, Limits::NoLimits()));
454
2.85M
        }
455
        // First splice this entry into mapTx.
456
2.86M
        auto node_handle = changeset->m_to_add.extract(tx_entry);
457
2.86M
        auto result = mapTx.insert(std::move(node_handle));
458
459
2.86M
        Assume(result.inserted);
460
2.86M
        txiter it = result.position;
461
462
        // Now update the entry for ancestors/descendants.
463
2.86M
        if (ancestors.has_value()) {
464
2.85M
            addNewTransaction(it, *ancestors);
465
2.85M
        } else {
466
4.87k
            addNewTransaction(it);
467
4.87k
        }
468
2.86M
    }
469
2.85M
}
470
471
void CTxMemPool::addNewTransaction(CTxMemPool::txiter it)
472
4.87k
{
473
4.87k
    auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
474
4.87k
    return addNewTransaction(it, ancestors);
475
4.87k
}
476
477
void CTxMemPool::addNewTransaction(CTxMemPool::txiter newit, CTxMemPool::setEntries& setAncestors)
478
2.86M
{
479
2.86M
    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
2.86M
    cachedInnerUsage += entry.DynamicMemoryUsage();
485
486
2.86M
    const CTransaction& tx = newit->GetTx();
487
2.86M
    std::set<Txid> setParentTransactions;
488
8.10M
    for (unsigned int i = 0; i < tx.vin.size(); i++) {
489
5.24M
        mapNextTx.insert(std::make_pair(&tx.vin[i].prevout, &tx));
490
5.24M
        setParentTransactions.insert(tx.vin[i].prevout.hash);
491
5.24M
    }
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
2.86M
    for (const auto& pit : GetIterSet(setParentTransactions)) {
501
1.48M
        UpdateParent(newit, pit, true);
502
1.48M
    }
503
2.86M
    UpdateAncestorsOf(true, newit, setAncestors);
504
2.86M
    UpdateEntryForAncestors(newit, setAncestors);
505
506
2.86M
    nTransactionsUpdated++;
507
2.86M
    totalTxSize += entry.GetTxSize();
508
2.86M
    m_total_fee += entry.GetFee();
509
510
2.86M
    txns_randomized.emplace_back(tx.GetWitnessHash(), newit);
511
2.86M
    newit->idx_randomized = txns_randomized.size() - 1;
512
513
2.86M
    TRACEPOINT(mempool, added,
514
2.86M
        entry.GetTx().GetHash().data(),
515
2.86M
        entry.GetTxSize(),
516
2.86M
        entry.GetFee()
517
2.86M
    );
518
2.86M
}
519
520
void CTxMemPool::removeUnchecked(txiter it, MemPoolRemovalReason reason)
521
130k
{
522
    // We increment mempool sequence value no matter removal reason
523
    // even if not directly reported below.
524
130k
    uint64_t mempool_sequence = GetAndIncrementSequence();
525
526
130k
    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
121k
        m_opts.signals->TransactionRemovedFromMempool(it->GetSharedTx(), reason, mempool_sequence);
532
121k
    }
533
130k
    TRACEPOINT(mempool, removed,
534
130k
        it->GetTx().GetHash().data(),
535
130k
        RemovalReasonToString(reason).c_str(),
536
130k
        it->GetTxSize(),
537
130k
        it->GetFee(),
538
130k
        std::chrono::duration_cast<std::chrono::duration<std::uint64_t>>(it->GetTime()).count()
539
130k
    );
540
541
130k
    for (const CTxIn& txin : it->GetTx().vin)
542
214k
        mapNextTx.erase(txin.prevout);
543
544
130k
    RemoveUnbroadcastTx(it->GetTx().GetHash(), true /* add logging because unchecked */);
545
546
130k
    if (txns_randomized.size() > 1) {
547
        // Remove entry from txns_randomized by replacing it with the back and deleting the back.
548
107k
        txns_randomized[it->idx_randomized] = std::move(txns_randomized.back());
549
107k
        txns_randomized[it->idx_randomized].second->idx_randomized = it->idx_randomized;
550
107k
        txns_randomized.pop_back();
551
107k
        if (txns_randomized.size() * 2 < txns_randomized.capacity()) {
552
15.9k
            txns_randomized.shrink_to_fit();
553
15.9k
        }
554
107k
    } else {
555
22.7k
        txns_randomized.clear();
556
22.7k
    }
557
558
130k
    totalTxSize -= it->GetTxSize();
559
130k
    m_total_fee -= it->GetFee();
560
130k
    cachedInnerUsage -= it->DynamicMemoryUsage();
561
130k
    cachedInnerUsage -= memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
562
130k
    mapTx.erase(it);
563
130k
    nTransactionsUpdated++;
564
130k
}
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
3.30M
{
574
3.30M
    setEntries stage;
575
3.30M
    if (setDescendants.count(entryit) == 0) {
576
3.02M
        stage.insert(entryit);
577
3.02M
    }
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
57.7M
    while (!stage.empty()) {
582
54.4M
        txiter it = *stage.begin();
583
54.4M
        setDescendants.insert(it);
584
54.4M
        stage.erase(it);
585
586
54.4M
        const CTxMemPoolEntry::Children& children = it->GetMemPoolChildrenConst();
587
75.3M
        for (const CTxMemPoolEntry& child : children) {
588
75.3M
            txiter childiter = mapTx.iterator_to(child);
589
75.3M
            if (!setDescendants.count(childiter)) {
590
59.4M
                stage.insert(childiter);
591
59.4M
            }
592
75.3M
        }
593
54.4M
    }
594
3.30M
}
595
596
void CTxMemPool::removeRecursive(const CTransaction &origTx, MemPoolRemovalReason reason)
597
5.22k
{
598
    // Remove transaction from memory pool
599
5.22k
    AssertLockHeld(cs);
600
5.22k
    Assume(!m_have_changeset);
601
5.22k
        setEntries txToRemove;
602
5.22k
        txiter origit = mapTx.find(origTx.GetHash());
603
5.22k
        if (origit != mapTx.end()) {
604
5.22k
            txToRemove.insert(origit);
605
5.22k
        } 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
0
            for (unsigned int i = 0; i < origTx.vout.size(); i++) {
611
0
                auto it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
612
0
                if (it == mapNextTx.end())
613
0
                    continue;
614
0
                txiter nextit = mapTx.find(it->second->GetHash());
615
0
                assert(nextit != mapTx.end());
616
0
                txToRemove.insert(nextit);
617
0
            }
618
0
        }
619
5.22k
        setEntries setAllRemoves;
620
5.22k
        for (txiter it : txToRemove) {
621
5.22k
            CalculateDescendants(it, setAllRemoves);
622
5.22k
        }
623
624
5.22k
        RemoveStaged(setAllRemoves, false, reason);
625
5.22k
}
626
627
void CTxMemPool::removeForReorg(CChain& chain, std::function<bool(txiter)> check_final_and_mature)
628
0
{
629
    // Remove transactions spending a coinbase which are now immature and no-longer-final transactions
630
0
    AssertLockHeld(cs);
631
0
    AssertLockHeld(::cs_main);
632
0
    Assume(!m_have_changeset);
633
634
0
    setEntries txToRemove;
635
0
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
636
0
        if (check_final_and_mature(it)) txToRemove.insert(it);
637
0
    }
638
0
    setEntries setAllRemoves;
639
0
    for (txiter it : txToRemove) {
640
0
        CalculateDescendants(it, setAllRemoves);
641
0
    }
642
0
    RemoveStaged(setAllRemoves, false, MemPoolRemovalReason::REORG);
643
0
    for (indexed_transaction_set::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
644
0
        assert(TestLockPointValidity(chain, it->GetLockPoints()));
645
0
    }
646
0
}
647
648
void CTxMemPool::removeConflicts(const CTransaction &tx)
649
0
{
650
    // Remove transactions which depend on inputs of tx, recursively
651
0
    AssertLockHeld(cs);
652
0
    for (const CTxIn &txin : tx.vin) {
653
0
        auto it = mapNextTx.find(txin.prevout);
654
0
        if (it != mapNextTx.end()) {
655
0
            const CTransaction &txConflict = *it->second;
656
0
            if (Assume(txConflict.GetHash() != tx.GetHash()))
657
0
            {
658
0
                ClearPrioritisation(txConflict.GetHash());
659
0
                removeRecursive(txConflict, MemPoolRemovalReason::CONFLICT);
660
0
            }
661
0
        }
662
0
    }
663
0
}
664
665
void CTxMemPool::removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight)
666
230k
{
667
    // Remove confirmed txs and conflicts when a new block is connected, updating the fee logic
668
230k
    AssertLockHeld(cs);
669
230k
    Assume(!m_have_changeset);
670
230k
    std::vector<RemovedMempoolTransactionInfo> txs_removed_for_block;
671
230k
    if (mapTx.size() || mapNextTx.size() || mapDeltas.size()) {
672
0
        txs_removed_for_block.reserve(vtx.size());
673
0
        for (const auto& tx : vtx) {
674
0
            txiter it = mapTx.find(tx->GetHash());
675
0
            if (it != mapTx.end()) {
676
0
                setEntries stage;
677
0
                stage.insert(it);
678
0
                txs_removed_for_block.emplace_back(*it);
679
0
                RemoveStaged(stage, true, MemPoolRemovalReason::BLOCK);
680
0
            }
681
0
            removeConflicts(*tx);
682
0
            ClearPrioritisation(tx->GetHash());
683
0
        }
684
0
    }
685
230k
    if (m_opts.signals) {
686
230k
        m_opts.signals->MempoolTransactionsRemovedForBlock(txs_removed_for_block, nBlockHeight);
687
230k
    }
688
230k
    lastRollingFeeUpdate = GetTime();
689
230k
    blockSinceLastRollingFeeBump = true;
690
230k
}
691
692
void CTxMemPool::check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const
693
280k
{
694
280k
    if (m_opts.check_ratio == 0) return;
695
696
280k
    if (FastRandomContext().randrange(m_opts.check_ratio) >= 1) return;
697
698
280k
    AssertLockHeld(::cs_main);
699
280k
    LOCK(cs);
700
280k
    LogDebug(BCLog::MEMPOOL, "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
701
702
280k
    uint64_t checkTotal = 0;
703
280k
    CAmount check_total_fee{0};
704
280k
    uint64_t innerUsage = 0;
705
280k
    uint64_t prev_ancestor_count{0};
706
707
280k
    CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(&active_coins_tip));
708
709
280k
    for (const auto& it : GetSortedDepthAndScore()) {
710
176k
        checkTotal += it->GetTxSize();
711
176k
        check_total_fee += it->GetFee();
712
176k
        innerUsage += it->DynamicMemoryUsage();
713
176k
        const CTransaction& tx = it->GetTx();
714
176k
        innerUsage += memusage::DynamicUsage(it->GetMemPoolParentsConst()) + memusage::DynamicUsage(it->GetMemPoolChildrenConst());
715
176k
        CTxMemPoolEntry::Parents setParentCheck;
716
287k
        for (const CTxIn &txin : tx.vin) {
717
            // Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
718
287k
            indexed_transaction_set::const_iterator it2 = mapTx.find(txin.prevout.hash);
719
287k
            if (it2 != mapTx.end()) {
720
95.5k
                const CTransaction& tx2 = it2->GetTx();
721
95.5k
                assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
722
95.5k
                setParentCheck.insert(*it2);
723
95.5k
            }
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
287k
            assert(mempoolDuplicate.HaveCoin(txin.prevout));
728
            // Check whether its inputs are marked in mapNextTx.
729
287k
            auto it3 = mapNextTx.find(txin.prevout);
730
287k
            assert(it3 != mapNextTx.end());
731
287k
            assert(it3->first == &txin.prevout);
732
287k
            assert(it3->second == &tx);
733
287k
        }
734
176k
        auto comp = [](const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) -> bool {
735
140k
            return a.GetTx().GetHash() == b.GetTx().GetHash();
736
140k
        };
737
176k
        assert(setParentCheck.size() == it->GetMemPoolParentsConst().size());
738
176k
        assert(std::equal(setParentCheck.begin(), setParentCheck.end(), it->GetMemPoolParentsConst().begin(), comp));
739
        // Verify ancestor state is correct.
740
176k
        auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits())};
741
176k
        uint64_t nCountCheck = ancestors.size() + 1;
742
176k
        int32_t nSizeCheck = it->GetTxSize();
743
176k
        CAmount nFeesCheck = it->GetModifiedFee();
744
176k
        int64_t nSigOpCheck = it->GetSigOpCost();
745
746
176k
        for (txiter ancestorIt : ancestors) {
747
130k
            nSizeCheck += ancestorIt->GetTxSize();
748
130k
            nFeesCheck += ancestorIt->GetModifiedFee();
749
130k
            nSigOpCheck += ancestorIt->GetSigOpCost();
750
130k
        }
751
752
176k
        assert(it->GetCountWithAncestors() == nCountCheck);
753
176k
        assert(it->GetSizeWithAncestors() == nSizeCheck);
754
176k
        assert(it->GetSigOpCostWithAncestors() == nSigOpCheck);
755
176k
        assert(it->GetModFeesWithAncestors() == nFeesCheck);
756
        // Sanity check: we are walking in ascending ancestor count order.
757
176k
        assert(prev_ancestor_count <= it->GetCountWithAncestors());
758
176k
        prev_ancestor_count = it->GetCountWithAncestors();
759
760
        // Check children against mapNextTx
761
176k
        CTxMemPoolEntry::Children setChildrenCheck;
762
176k
        auto iter = mapNextTx.lower_bound(COutPoint(it->GetTx().GetHash(), 0));
763
176k
        int32_t child_sizes{0};
764
271k
        for (; iter != mapNextTx.end() && iter->first->hash == it->GetTx().GetHash(); ++iter) {
765
95.5k
            txiter childit = mapTx.find(iter->second->GetHash());
766
95.5k
            assert(childit != mapTx.end()); // mapNextTx points to in-mempool transactions
767
95.5k
            if (setChildrenCheck.insert(*childit).second) {
768
70.3k
                child_sizes += childit->GetTxSize();
769
70.3k
            }
770
95.5k
        }
771
176k
        assert(setChildrenCheck.size() == it->GetMemPoolChildrenConst().size());
772
176k
        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
176k
        assert(it->GetSizeWithDescendants() >= child_sizes + it->GetTxSize());
776
777
176k
        TxValidationState dummy_state; // Not used. CheckTxInputs() should always pass
778
176k
        CAmount txfee = 0;
779
176k
        assert(!tx.IsCoinBase());
780
176k
        assert(Consensus::CheckTxInputs(tx, dummy_state, mempoolDuplicate, spendheight, txfee));
781
287k
        for (const auto& input: tx.vin) mempoolDuplicate.SpendCoin(input.prevout);
782
176k
        AddCoins(mempoolDuplicate, tx, std::numeric_limits<int>::max());
783
176k
    }
784
287k
    for (const auto& [_, next_tx] : mapNextTx) {
785
287k
        auto it = mapTx.find(next_tx->GetHash());
786
287k
        const CTransaction& tx = it->GetTx();
787
287k
        assert(it != mapTx.end());
788
287k
        assert(&tx == next_tx);
789
287k
    }
790
791
280k
    assert(totalTxSize == checkTotal);
792
280k
    assert(m_total_fee == check_total_fee);
793
280k
    assert(innerUsage == cachedInnerUsage);
794
280k
}
795
796
bool CTxMemPool::CompareDepthAndScore(const Wtxid& hasha, const Wtxid& hashb) const
797
0
{
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
0
    LOCK(cs);
804
0
    auto j{GetIter(hashb)};
805
0
    if (!j.has_value()) return false;
806
0
    auto i{GetIter(hasha)};
807
0
    if (!i.has_value()) return true;
808
0
    uint64_t counta = i.value()->GetCountWithAncestors();
809
0
    uint64_t countb = j.value()->GetCountWithAncestors();
810
0
    if (counta == countb) {
811
0
        return CompareTxMemPoolEntryByScore()(*i.value(), *j.value());
812
0
    }
813
0
    return counta < countb;
814
0
}
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
120M
    {
822
120M
        uint64_t counta = a->GetCountWithAncestors();
823
120M
        uint64_t countb = b->GetCountWithAncestors();
824
120M
        if (counta == countb) {
825
79.8M
            return CompareTxMemPoolEntryByScore()(*a, *b);
826
79.8M
        }
827
40.3M
        return counta < countb;
828
120M
    }
829
};
830
} // namespace
831
832
std::vector<CTxMemPool::indexed_transaction_set::const_iterator> CTxMemPool::GetSortedDepthAndScore() const
833
1.47M
{
834
1.47M
    std::vector<indexed_transaction_set::const_iterator> iters;
835
1.47M
    AssertLockHeld(cs);
836
837
1.47M
    iters.reserve(mapTx.size());
838
839
21.5M
    for (indexed_transaction_set::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) {
840
20.1M
        iters.push_back(mi);
841
20.1M
    }
842
1.47M
    std::sort(iters.begin(), iters.end(), DepthAndScoreComparator());
843
1.47M
    return iters;
844
1.47M
}
845
846
std::vector<CTxMemPoolEntryRef> CTxMemPool::entryAll() const
847
64
{
848
64
    AssertLockHeld(cs);
849
850
64
    std::vector<CTxMemPoolEntryRef> ret;
851
64
    ret.reserve(mapTx.size());
852
64
    for (const auto& it : GetSortedDepthAndScore()) {
853
0
        ret.emplace_back(*it);
854
0
    }
855
64
    return ret;
856
64
}
857
858
std::vector<TxMempoolInfo> CTxMemPool::infoAll() const
859
1.19M
{
860
1.19M
    LOCK(cs);
861
1.19M
    auto iters = GetSortedDepthAndScore();
862
863
1.19M
    std::vector<TxMempoolInfo> ret;
864
1.19M
    ret.reserve(mapTx.size());
865
19.9M
    for (auto it : iters) {
866
19.9M
        ret.push_back(GetInfo(it));
867
19.9M
    }
868
869
1.19M
    return ret;
870
1.19M
}
871
872
const CTxMemPoolEntry* CTxMemPool::GetEntry(const Txid& txid) const
873
19.8M
{
874
19.8M
    AssertLockHeld(cs);
875
19.8M
    const auto i = mapTx.find(txid);
876
19.8M
    return i == mapTx.end() ? nullptr : &(*i);
877
19.8M
}
878
879
CTransactionRef CTxMemPool::get(const Txid& hash) const
880
46.8M
{
881
46.8M
    LOCK(cs);
882
46.8M
    indexed_transaction_set::const_iterator i = mapTx.find(hash);
883
46.8M
    if (i == mapTx.end())
884
21.8M
        return nullptr;
885
25.0M
    return i->GetSharedTx();
886
46.8M
}
887
888
void CTxMemPool::PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta)
889
2.31M
{
890
2.31M
    {
891
2.31M
        LOCK(cs);
892
2.31M
        CAmount &delta = mapDeltas[hash];
893
2.31M
        delta = SaturatingAdd(delta, nFeeDelta);
894
2.31M
        txiter it = mapTx.find(hash);
895
2.31M
        if (it != mapTx.end()) {
896
1.14M
            mapTx.modify(it, [&nFeeDelta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(nFeeDelta); });
897
            // Now update all ancestors' modified fees with descendants
898
1.14M
            auto ancestors{AssumeCalculateMemPoolAncestors(__func__, *it, Limits::NoLimits(), /*fSearchForParents=*/false)};
899
1.14M
            for (txiter ancestorIt : ancestors) {
900
1.13M
                mapTx.modify(ancestorIt, [=](CTxMemPoolEntry& e){ e.UpdateDescendantState(0, nFeeDelta, 0);});
901
1.13M
            }
902
            // Now update all descendants' modified fees with ancestors
903
1.14M
            setEntries setDescendants;
904
1.14M
            CalculateDescendants(it, setDescendants);
905
1.14M
            setDescendants.erase(it);
906
1.14M
            for (txiter descendantIt : setDescendants) {
907
123k
                mapTx.modify(descendantIt, [=](CTxMemPoolEntry& e){ e.UpdateAncestorState(0, nFeeDelta, 0, 0); });
908
123k
            }
909
1.14M
            ++nTransactionsUpdated;
910
1.14M
        }
911
2.31M
        if (delta == 0) {
912
14.1k
            mapDeltas.erase(hash);
913
14.1k
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) delta cleared\n", hash.ToString(), it == mapTx.end() ? "not " : "");
914
2.30M
        } else {
915
2.30M
            LogPrintf("PrioritiseTransaction: %s (%sin mempool) fee += %s, new delta=%s\n",
916
2.30M
                      hash.ToString(),
917
2.30M
                      it == mapTx.end() ? "not " : "",
918
2.30M
                      FormatMoney(nFeeDelta),
919
2.30M
                      FormatMoney(delta));
920
2.30M
        }
921
2.31M
    }
922
2.31M
}
923
924
void CTxMemPool::ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const
925
3.86M
{
926
3.86M
    AssertLockHeld(cs);
927
3.86M
    std::map<Txid, CAmount>::const_iterator pos = mapDeltas.find(hash);
928
3.86M
    if (pos == mapDeltas.end())
929
3.65M
        return;
930
215k
    const CAmount &delta = pos->second;
931
215k
    nFeeDelta += delta;
932
215k
}
933
934
void CTxMemPool::ClearPrioritisation(const Txid& hash)
935
0
{
936
0
    AssertLockHeld(cs);
937
0
    mapDeltas.erase(hash);
938
0
}
939
940
std::vector<CTxMemPool::delta_info> CTxMemPool::GetPrioritisedTransactions() const
941
28
{
942
28
    AssertLockNotHeld(cs);
943
28
    LOCK(cs);
944
28
    std::vector<delta_info> result;
945
28
    result.reserve(mapDeltas.size());
946
590
    for (const auto& [txid, delta] : mapDeltas) {
947
590
        const auto iter{mapTx.find(txid)};
948
590
        const bool in_mempool{iter != mapTx.end()};
949
590
        std::optional<CAmount> modified_fee;
950
590
        if (in_mempool) modified_fee = iter->GetModifiedFee();
951
590
        result.emplace_back(delta_info{in_mempool, delta, modified_fee, txid});
952
590
    }
953
28
    return result;
954
28
}
955
956
const CTransaction* CTxMemPool::GetConflictTx(const COutPoint& prevout) const
957
13.2M
{
958
13.2M
    const auto it = mapNextTx.find(prevout);
959
13.2M
    return it == mapNextTx.end() ? nullptr : it->second;
960
13.2M
}
961
962
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Txid& txid) const
963
18.1M
{
964
18.1M
    AssertLockHeld(cs);
965
18.1M
    auto it = mapTx.find(txid);
966
18.1M
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
967
18.1M
}
968
969
std::optional<CTxMemPool::txiter> CTxMemPool::GetIter(const Wtxid& wtxid) const
970
16.5k
{
971
16.5k
    AssertLockHeld(cs);
972
16.5k
    auto it{mapTx.project<0>(mapTx.get<index_by_wtxid>().find(wtxid))};
973
16.5k
    return it != mapTx.end() ? std::make_optional(it) : std::nullopt;
974
16.5k
}
975
976
CTxMemPool::setEntries CTxMemPool::GetIterSet(const std::set<Txid>& hashes) const
977
3.79M
{
978
3.79M
    CTxMemPool::setEntries ret;
979
3.96M
    for (const auto& h : hashes) {
980
3.96M
        const auto mi = GetIter(h);
981
3.96M
        if (mi) ret.insert(*mi);
982
3.96M
    }
983
3.79M
    return ret;
984
3.79M
}
985
986
std::vector<CTxMemPool::txiter> CTxMemPool::GetIterVec(const std::vector<Txid>& txids) const
987
4.93k
{
988
4.93k
    AssertLockHeld(cs);
989
4.93k
    std::vector<txiter> ret;
990
4.93k
    ret.reserve(txids.size());
991
327k
    for (const auto& txid : txids) {
992
327k
        const auto it{GetIter(txid)};
993
327k
        if (!it) return {};
994
327k
        ret.push_back(*it);
995
327k
    }
996
4.93k
    return ret;
997
4.93k
}
998
999
bool CTxMemPool::HasNoInputsOf(const CTransaction &tx) const
1000
245k
{
1001
487k
    for (unsigned int i = 0; i < tx.vin.size(); i++)
1002
327k
        if (exists(tx.vin[i].prevout.hash))
1003
85.0k
            return false;
1004
160k
    return true;
1005
245k
}
1006
1007
2.61M
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) { }
1008
1009
std::optional<Coin> CCoinsViewMemPool::GetCoin(const COutPoint& outpoint) const
1010
45.7M
{
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
45.7M
    if (auto it = m_temp_added.find(outpoint); it != m_temp_added.end()) {
1014
241k
        return it->second;
1015
241k
    }
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
45.4M
    CTransactionRef ptx = mempool.get(outpoint.hash);
1021
45.4M
    if (ptx) {
1022
24.6M
        if (outpoint.n < ptx->vout.size()) {
1023
24.6M
            Coin coin(ptx->vout[outpoint.n], MEMPOOL_HEIGHT, false);
1024
24.6M
            m_non_base_coins.emplace(outpoint);
1025
24.6M
            return coin;
1026
24.6M
        }
1027
1.79k
        return std::nullopt;
1028
24.6M
    }
1029
20.8M
    return base->GetCoin(outpoint);
1030
45.4M
}
1031
1032
void CCoinsViewMemPool::PackageAddTransaction(const CTransactionRef& tx)
1033
225k
{
1034
2.80M
    for (unsigned int n = 0; n < tx->vout.size(); ++n) {
1035
2.57M
        m_temp_added.emplace(COutPoint(tx->GetHash(), n), Coin(tx->vout[n], MEMPOOL_HEIGHT, false));
1036
2.57M
        m_non_base_coins.emplace(tx->GetHash(), n);
1037
2.57M
    }
1038
225k
}
1039
void CCoinsViewMemPool::Reset()
1040
1.39M
{
1041
1.39M
    m_temp_added.clear();
1042
1.39M
    m_non_base_coins.clear();
1043
1.39M
}
1044
1045
3.94M
size_t CTxMemPool::DynamicMemoryUsage() const {
1046
3.94M
    LOCK(cs);
1047
    // Estimate the overhead of mapTx to be 15 pointers + an allocation, as no exact formula for boost::multi_index_contained is implemented.
1048
3.94M
    return memusage::MallocUsage(sizeof(CTxMemPoolEntry) + 15 * sizeof(void*)) * mapTx.size() + memusage::DynamicUsage(mapNextTx) + memusage::DynamicUsage(mapDeltas) + memusage::DynamicUsage(txns_randomized) + cachedInnerUsage;
1049
3.94M
}
1050
1051
130k
void CTxMemPool::RemoveUnbroadcastTx(const Txid& txid, const bool unchecked) {
1052
130k
    LOCK(cs);
1053
1054
130k
    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" : ""));
1057
0
    }
1058
130k
}
1059
1060
3.38M
void CTxMemPool::RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason) {
1061
3.38M
    AssertLockHeld(cs);
1062
3.38M
    UpdateForRemoveFromMempool(stage, updateDescendants);
1063
3.38M
    for (txiter it : stage) {
1064
130k
        removeUnchecked(it, reason);
1065
130k
    }
1066
3.38M
}
1067
1068
int CTxMemPool::Expire(std::chrono::seconds time)
1069
486k
{
1070
486k
    AssertLockHeld(cs);
1071
486k
    Assume(!m_have_changeset);
1072
486k
    indexed_transaction_set::index<entry_time>::type::iterator it = mapTx.get<entry_time>().begin();
1073
486k
    setEntries toremove;
1074
533k
    while (it != mapTx.get<entry_time>().end() && it->GetTime() < time) {
1075
46.6k
        toremove.insert(mapTx.project<0>(it));
1076
46.6k
        it++;
1077
46.6k
    }
1078
486k
    setEntries stage;
1079
486k
    for (txiter removeit : toremove) {
1080
46.6k
        CalculateDescendants(removeit, stage);
1081
46.6k
    }
1082
486k
    RemoveStaged(stage, false, MemPoolRemovalReason::EXPIRY);
1083
486k
    return stage.size();
1084
486k
}
1085
1086
void CTxMemPool::UpdateChild(txiter entry, txiter child, bool add)
1087
1.53M
{
1088
1.53M
    AssertLockHeld(cs);
1089
1.53M
    CTxMemPoolEntry::Children s;
1090
1.53M
    if (add && entry->GetMemPoolChildren().insert(*child).second) {
1091
1.48M
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1092
1.48M
    } else if (!add && entry->GetMemPoolChildren().erase(*child)) {
1093
46.0k
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1094
46.0k
    }
1095
1.53M
}
1096
1097
void CTxMemPool::UpdateParent(txiter entry, txiter parent, bool add)
1098
1.48M
{
1099
1.48M
    AssertLockHeld(cs);
1100
1.48M
    CTxMemPoolEntry::Parents s;
1101
1.48M
    if (add && entry->GetMemPoolParents().insert(*parent).second) {
1102
1.48M
        cachedInnerUsage += memusage::IncrementalDynamicUsage(s);
1103
1.48M
    } else if (!add && entry->GetMemPoolParents().erase(*parent)) {
1104
0
        cachedInnerUsage -= memusage::IncrementalDynamicUsage(s);
1105
0
    }
1106
1.48M
}
1107
1108
658k
CFeeRate CTxMemPool::GetMinFee(size_t sizelimit) const {
1109
658k
    LOCK(cs);
1110
658k
    if (!blockSinceLastRollingFeeBump || rollingMinimumFeeRate == 0)
1111
614k
        return CFeeRate(llround(rollingMinimumFeeRate));
1112
1113
43.2k
    int64_t time = GetTime();
1114
43.2k
    if (time > lastRollingFeeUpdate + 10) {
1115
4.95k
        double halflife = ROLLING_FEE_HALFLIFE;
1116
4.95k
        if (DynamicMemoryUsage() < sizelimit / 4)
1117
0
            halflife /= 4;
1118
4.95k
        else if (DynamicMemoryUsage() < sizelimit / 2)
1119
0
            halflife /= 2;
1120
1121
4.95k
        rollingMinimumFeeRate = rollingMinimumFeeRate / pow(2.0, (time - lastRollingFeeUpdate) / halflife);
1122
4.95k
        lastRollingFeeUpdate = time;
1123
1124
4.95k
        if (rollingMinimumFeeRate < (double)m_opts.incremental_relay_feerate.GetFeePerK() / 2) {
1125
4.08k
            rollingMinimumFeeRate = 0;
1126
4.08k
            return CFeeRate(0);
1127
4.08k
        }
1128
4.95k
    }
1129
39.1k
    return std::max(CFeeRate(llround(rollingMinimumFeeRate)), m_opts.incremental_relay_feerate);
1130
43.2k
}
1131
1132
30.9k
void CTxMemPool::trackPackageRemoved(const CFeeRate& rate) {
1133
30.9k
    AssertLockHeld(cs);
1134
30.9k
    if (rate.GetFeePerK() > rollingMinimumFeeRate) {
1135
19.6k
        rollingMinimumFeeRate = rate.GetFeePerK();
1136
19.6k
        blockSinceLastRollingFeeBump = false;
1137
19.6k
    }
1138
30.9k
}
1139
1140
486k
void CTxMemPool::TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining) {
1141
486k
    AssertLockHeld(cs);
1142
486k
    Assume(!m_have_changeset);
1143
1144
486k
    unsigned nTxnRemoved = 0;
1145
486k
    CFeeRate maxFeeRateRemoved(0);
1146
517k
    while (!mapTx.empty() && DynamicMemoryUsage() > sizelimit) {
1147
30.9k
        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
30.9k
        CFeeRate removed(it->GetModFeesWithDescendants(), it->GetSizeWithDescendants());
1154
30.9k
        removed += m_opts.incremental_relay_feerate;
1155
30.9k
        trackPackageRemoved(removed);
1156
30.9k
        maxFeeRateRemoved = std::max(maxFeeRateRemoved, removed);
1157
1158
30.9k
        setEntries stage;
1159
30.9k
        CalculateDescendants(mapTx.project<0>(it), stage);
1160
30.9k
        nTxnRemoved += stage.size();
1161
1162
30.9k
        std::vector<CTransaction> txn;
1163
30.9k
        if (pvNoSpendsRemaining) {
1164
30.9k
            txn.reserve(stage.size());
1165
30.9k
            for (txiter iter : stage)
1166
33.3k
                txn.push_back(iter->GetTx());
1167
30.9k
        }
1168
30.9k
        RemoveStaged(stage, false, MemPoolRemovalReason::SIZELIMIT);
1169
30.9k
        if (pvNoSpendsRemaining) {
1170
33.3k
            for (const CTransaction& tx : txn) {
1171
51.5k
                for (const CTxIn& txin : tx.vin) {
1172
51.5k
                    if (exists(txin.prevout.hash)) continue;
1173
47.7k
                    pvNoSpendsRemaining->push_back(txin.prevout);
1174
47.7k
                }
1175
33.3k
            }
1176
30.9k
        }
1177
30.9k
    }
1178
1179
486k
    if (maxFeeRateRemoved > CFeeRate(0)) {
1180
14.6k
        LogDebug(BCLog::MEMPOOL, "Removed %u txn, rolling minimum fee bumped to %s\n", nTxnRemoved, maxFeeRateRemoved.ToString());
1181
14.6k
    }
1182
486k
}
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);
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
1
{
1220
1
    LOCK(cs);
1221
1
    return m_load_tried;
1222
1
}
1223
1224
void CTxMemPool::SetLoadTried(bool load_tried)
1225
2.18k
{
1226
2.18k
    LOCK(cs);
1227
2.18k
    m_load_tried = load_tried;
1228
2.18k
}
1229
1230
std::vector<CTxMemPool::txiter> CTxMemPool::GatherClusters(const std::vector<Txid>& txids) const
1231
4.93k
{
1232
4.93k
    AssertLockHeld(cs);
1233
4.93k
    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
4.93k
    WITH_FRESH_EPOCH(m_epoch);
1237
327k
    for (const auto& it : clustered_txs) {
1238
327k
        visited(it);
1239
327k
    }
1240
    // i = index of where the list of entries to process starts
1241
489k
    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
484k
        if (clustered_txs.size() > 500) return {};
1244
484k
        const txiter& tx_iter = clustered_txs.at(i);
1245
969k
        for (const auto& entries : {tx_iter->GetMemPoolParentsConst(), tx_iter->GetMemPoolChildrenConst()}) {
1246
1.22M
            for (const CTxMemPoolEntry& entry : entries) {
1247
1.22M
                const auto entry_it = mapTx.iterator_to(entry);
1248
1.22M
                if (!visited(entry_it)) {
1249
157k
                    clustered_txs.push_back(entry_it);
1250
157k
                }
1251
1.22M
            }
1252
969k
        }
1253
484k
    }
1254
4.93k
    return clustered_txs;
1255
4.93k
}
1256
1257
std::optional<std::string> CTxMemPool::CheckConflictTopology(const setEntries& direct_conflicts)
1258
16.6k
{
1259
2.76M
    for (const auto& direct_conflict : direct_conflicts) {
1260
        // Ancestor and descendant counts are inclusive of the tx itself.
1261
2.76M
        const auto ancestor_count{direct_conflict->GetCountWithAncestors()};
1262
2.76M
        const auto descendant_count{direct_conflict->GetCountWithDescendants()};
1263
2.76M
        const bool has_ancestor{ancestor_count > 1};
1264
2.76M
        const bool has_descendant{descendant_count > 1};
1265
2.76M
        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
2.76M
        if (ancestor_count > 2) {
1271
628
            return strprintf("%s has %u ancestors, max 1 allowed", txid_string, ancestor_count - 1);
1272
2.76M
        } else if (descendant_count > 2) {
1273
652
            return strprintf("%s has %u descendants, max 1 allowed", txid_string, descendant_count - 1);
1274
2.76M
        } else if (has_ancestor && has_descendant) {
1275
522
            return strprintf("%s has both ancestor and descendant, exceeding cluster limit of 2", txid_string);
1276
522
        }
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
2.76M
        if (has_descendant) {
1281
1.20M
            const auto& our_child = direct_conflict->GetMemPoolChildrenConst().begin();
1282
1.20M
            if (our_child->get().GetCountWithAncestors() > 2) {
1283
471
                return strprintf("%s is not the only parent of child %s",
1284
471
                                 txid_string, our_child->get().GetSharedTx()->GetHash().ToString());
1285
471
            }
1286
1.55M
        } else if (has_ancestor) {
1287
1.43M
            const auto& our_parent = direct_conflict->GetMemPoolParentsConst().begin();
1288
1.43M
            if (our_parent->get().GetCountWithDescendants() > 2) {
1289
409
                return strprintf("%s is not the only child of parent %s",
1290
409
                                 txid_string, our_parent->get().GetSharedTx()->GetHash().ToString());
1291
409
            }
1292
1.43M
        }
1293
2.76M
    }
1294
13.9k
    return std::nullopt;
1295
16.6k
}
1296
1297
util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CTxMemPool::ChangeSet::CalculateChunksForRBF()
1298
16.6k
{
1299
16.6k
    LOCK(m_pool->cs);
1300
16.6k
    FeeFrac replacement_feerate{0, 0};
1301
30.9k
    for (auto it : m_entry_vec) {
1302
30.9k
        replacement_feerate += {it->GetModifiedFee(), it->GetTxSize()};
1303
30.9k
    }
1304
1305
16.6k
    auto err_string{m_pool->CheckConflictTopology(m_to_remove)};
1306
16.6k
    if (err_string.has_value()) {
1307
        // Unsupported topology for calculating a feerate diagram
1308
2.68k
        return util::Error{Untranslated(err_string.value())};
1309
2.68k
    }
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
13.9k
    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
2.76M
    for (auto txiter : m_to_remove) {
1328
        // Does this transaction have descendants?
1329
2.76M
        if (txiter->GetCountWithDescendants() > 1) {
1330
            // Consider this tx when we consider the descendant.
1331
1.20M
            continue;
1332
1.20M
        }
1333
        // Does this transaction have ancestors?
1334
1.55M
        FeeFrac individual{txiter->GetModifiedFee(), txiter->GetTxSize()};
1335
1.55M
        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
1.43M
            FeeFrac package{txiter->GetModFeesWithAncestors(), static_cast<int32_t>(txiter->GetSizeWithAncestors())};
1339
1.43M
            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
706k
                old_chunks.emplace_back(package);
1344
726k
            } else {
1345
                // Add two points, one for the parent and one for this child.
1346
726k
                old_chunks.emplace_back(package - individual);
1347
726k
                old_chunks.emplace_back(individual);
1348
726k
            }
1349
1.43M
        } else {
1350
125k
            old_chunks.emplace_back(individual);
1351
125k
        }
1352
1.55M
    }
1353
1354
    // No topology restrictions post-chunking; sort
1355
13.9k
    std::sort(old_chunks.begin(), old_chunks.end(), std::greater());
1356
1357
13.9k
    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
2.76M
    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
2.76M
        if (direct_conflict->GetMemPoolParentsConst().size() > 0) {
1371
            // Grab the parent.
1372
1.43M
            const CTxMemPoolEntry& parent = direct_conflict->GetMemPoolParentsConst().begin()->get();
1373
1.43M
            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
223k
                new_chunks.emplace_back(parent.GetModifiedFee(), parent.GetTxSize());
1377
223k
            }
1378
1.43M
        }
1379
2.76M
    }
1380
    // + CNK: Add the proposed chunk itself
1381
13.9k
    new_chunks.emplace_back(replacement_feerate);
1382
1383
    // No topology restrictions post-chunking; sort
1384
13.9k
    std::sort(new_chunks.begin(), new_chunks.end(), std::greater());
1385
13.9k
    return std::make_pair(old_chunks, new_chunks);
1386
16.6k
}
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
3.86M
{
1390
3.86M
    LOCK(m_pool->cs);
1391
3.86M
    Assume(m_to_add.find(tx->GetHash()) == m_to_add.end());
1392
3.86M
    auto newit = m_to_add.emplace(tx, fee, time, entry_height, entry_sequence, spends_coinbase, sigops_cost, lp).first;
1393
3.86M
    CAmount delta{0};
1394
3.86M
    m_pool->ApplyDelta(tx->GetHash(), delta);
1395
3.86M
    if (delta) m_to_add.modify(newit, [&delta](CTxMemPoolEntry& e) { e.UpdateModifiedFee(delta); });
1396
1397
3.86M
    m_entry_vec.push_back(newit);
1398
3.86M
    return newit;
1399
3.86M
}
1400
1401
void CTxMemPool::ChangeSet::Apply()
1402
2.85M
{
1403
2.85M
    LOCK(m_pool->cs);
1404
2.85M
    m_pool->Apply(this);
1405
2.85M
    m_to_add.clear();
1406
2.85M
    m_to_remove.clear();
1407
2.85M
    m_entry_vec.clear();
1408
2.85M
    m_ancestors.clear();
1409
2.85M
}