Coverage Report

Created: 2025-09-19 18:22

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/txmempool.h
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
#ifndef BITCOIN_TXMEMPOOL_H
7
#define BITCOIN_TXMEMPOOL_H
8
9
#include <coins.h>
10
#include <consensus/amount.h>
11
#include <indirectmap.h>
12
#include <kernel/cs_main.h>
13
#include <kernel/mempool_entry.h>          // IWYU pragma: export
14
#include <kernel/mempool_limits.h>         // IWYU pragma: export
15
#include <kernel/mempool_options.h>        // IWYU pragma: export
16
#include <kernel/mempool_removal_reason.h> // IWYU pragma: export
17
#include <policy/feerate.h>
18
#include <policy/packages.h>
19
#include <primitives/transaction.h>
20
#include <primitives/transaction_identifier.h>
21
#include <sync.h>
22
#include <util/epochguard.h>
23
#include <util/feefrac.h>
24
#include <util/hasher.h>
25
#include <util/result.h>
26
27
#include <boost/multi_index/hashed_index.hpp>
28
#include <boost/multi_index/identity.hpp>
29
#include <boost/multi_index/indexed_by.hpp>
30
#include <boost/multi_index/ordered_index.hpp>
31
#include <boost/multi_index/sequenced_index.hpp>
32
#include <boost/multi_index/tag.hpp>
33
#include <boost/multi_index_container.hpp>
34
35
#include <atomic>
36
#include <map>
37
#include <optional>
38
#include <set>
39
#include <string>
40
#include <string_view>
41
#include <utility>
42
#include <vector>
43
44
class CChain;
45
class ValidationSignals;
46
47
struct bilingual_str;
48
49
/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
50
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
51
52
/**
53
 * Test whether the LockPoints height and time are still valid on the current chain
54
 */
55
bool TestLockPointValidity(CChain& active_chain, const LockPoints& lp) EXCLUSIVE_LOCKS_REQUIRED(cs_main);
56
57
// extracts a transaction hash from CTxMemPoolEntry or CTransactionRef
58
struct mempoolentry_txid
59
{
60
    typedef Txid result_type;
61
    result_type operator() (const CTxMemPoolEntry &entry) const
62
36.1M
    {
63
36.1M
        return entry.GetTx().GetHash();
64
36.1M
    }
65
66
    result_type operator() (const CTransactionRef& tx) const
67
0
    {
68
0
        return tx->GetHash();
69
0
    }
70
};
71
72
// extracts a transaction witness-hash from CTxMemPoolEntry or CTransactionRef
73
struct mempoolentry_wtxid
74
{
75
    typedef Wtxid result_type;
76
    result_type operator() (const CTxMemPoolEntry &entry) const
77
34.5M
    {
78
34.5M
        return entry.GetTx().GetWitnessHash();
79
34.5M
    }
80
81
    result_type operator() (const CTransactionRef& tx) const
82
0
    {
83
0
        return tx->GetWitnessHash();
84
0
    }
85
};
86
87
88
/** \class CompareTxMemPoolEntryByDescendantScore
89
 *
90
 *  Sort an entry by max(score/size of entry's tx, score/size with all descendants).
91
 */
92
class CompareTxMemPoolEntryByDescendantScore
93
{
94
public:
95
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
96
129M
    {
97
129M
        FeeFrac f1 = GetModFeeAndSize(a);
98
129M
        FeeFrac f2 = GetModFeeAndSize(b);
99
100
129M
        if (FeeRateCompare(f1, f2) == 0) {
101
71.6M
            return a.GetTime() >= b.GetTime();
102
71.6M
        }
103
57.6M
        return f1 < f2;
104
129M
    }
105
106
    // Return the fee/size we're using for sorting this entry.
107
    FeeFrac GetModFeeAndSize(const CTxMemPoolEntry &a) const
108
258M
    {
109
        // Compare feerate with descendants to feerate of the transaction, and
110
        // return the fee/size for the max.
111
258M
        return std::max<FeeFrac>(
112
258M
            FeeFrac(a.GetModFeesWithDescendants(), a.GetSizeWithDescendants()),
113
258M
            FeeFrac(a.GetModifiedFee(), a.GetTxSize())
114
258M
        );
115
258M
    }
116
};
117
118
/** \class CompareTxMemPoolEntryByScore
119
 *
120
 *  Sort by feerate of entry (fee/size) in descending order
121
 *  This is only used for transaction relay, so we use GetFee()
122
 *  instead of GetModifiedFee() to avoid leaking prioritization
123
 *  information via the sort order.
124
 */
125
class CompareTxMemPoolEntryByScore
126
{
127
public:
128
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
129
0
    {
130
0
        FeeFrac f1(a.GetFee(), a.GetTxSize());
131
0
        FeeFrac f2(b.GetFee(), b.GetTxSize());
132
0
        if (FeeRateCompare(f1, f2) == 0) {
133
0
            return b.GetTx().GetHash() < a.GetTx().GetHash();
134
0
        }
135
0
        return f1 > f2;
136
0
    }
137
};
138
139
class CompareTxMemPoolEntryByEntryTime
140
{
141
public:
142
    bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
143
26.1M
    {
144
26.1M
        return a.GetTime() < b.GetTime();
145
26.1M
    }
146
};
147
148
/** \class CompareTxMemPoolEntryByAncestorScore
149
 *
150
 *  Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
151
 */
152
class CompareTxMemPoolEntryByAncestorFee
153
{
154
public:
155
    template<typename T>
156
    bool operator()(const T& a, const T& b) const
157
26.2M
    {
158
26.2M
        FeeFrac f1 = GetModFeeAndSize(a);
159
26.2M
        FeeFrac f2 = GetModFeeAndSize(b);
160
161
26.2M
        if (FeeRateCompare(f1, f2) == 0) {
162
9.20M
            return a.GetTx().GetHash() < b.GetTx().GetHash();
163
9.20M
        }
164
17.0M
        return f1 > f2;
165
26.2M
    }
Unexecuted instantiation: _ZNK34CompareTxMemPoolEntryByAncestorFeeclIN4node23CTxMemPoolModifiedEntryEEEbRKT_S5_
_ZNK34CompareTxMemPoolEntryByAncestorFeeclI15CTxMemPoolEntryEEbRKT_S4_
Line
Count
Source
157
26.2M
    {
158
26.2M
        FeeFrac f1 = GetModFeeAndSize(a);
159
26.2M
        FeeFrac f2 = GetModFeeAndSize(b);
160
161
26.2M
        if (FeeRateCompare(f1, f2) == 0) {
162
9.20M
            return a.GetTx().GetHash() < b.GetTx().GetHash();
163
9.20M
        }
164
17.0M
        return f1 > f2;
165
26.2M
    }
166
167
    // Return the fee/size we're using for sorting this entry.
168
    template <typename T>
169
    FeeFrac GetModFeeAndSize(const T &a) const
170
52.4M
    {
171
        // Compare feerate with ancestors to feerate of the transaction, and
172
        // return the fee/size for the min.
173
52.4M
        return std::min<FeeFrac>(
174
52.4M
            FeeFrac(a.GetModFeesWithAncestors(), a.GetSizeWithAncestors()),
175
52.4M
            FeeFrac(a.GetModifiedFee(), a.GetTxSize())
176
52.4M
        );
177
52.4M
    }
Unexecuted instantiation: _ZNK34CompareTxMemPoolEntryByAncestorFee16GetModFeeAndSizeIN4node23CTxMemPoolModifiedEntryEEE7FeeFracRKT_
_ZNK34CompareTxMemPoolEntryByAncestorFee16GetModFeeAndSizeI15CTxMemPoolEntryEE7FeeFracRKT_
Line
Count
Source
170
52.4M
    {
171
        // Compare feerate with ancestors to feerate of the transaction, and
172
        // return the fee/size for the min.
173
52.4M
        return std::min<FeeFrac>(
174
52.4M
            FeeFrac(a.GetModFeesWithAncestors(), a.GetSizeWithAncestors()),
175
52.4M
            FeeFrac(a.GetModifiedFee(), a.GetTxSize())
176
52.4M
        );
177
52.4M
    }
178
};
179
180
// Multi_index tag names
181
struct descendant_score {};
182
struct entry_time {};
183
struct ancestor_score {};
184
struct index_by_wtxid {};
185
186
/**
187
 * Information about a mempool transaction.
188
 */
189
struct TxMempoolInfo
190
{
191
    /** The transaction itself */
192
    CTransactionRef tx;
193
194
    /** Time the transaction entered the mempool. */
195
    std::chrono::seconds m_time;
196
197
    /** Fee of the transaction. */
198
    CAmount fee;
199
200
    /** Virtual size of the transaction. */
201
    int32_t vsize;
202
203
    /** The fee delta. */
204
    int64_t nFeeDelta;
205
};
206
207
/**
208
 * CTxMemPool stores valid-according-to-the-current-best-chain transactions
209
 * that may be included in the next block.
210
 *
211
 * Transactions are added when they are seen on the network (or created by the
212
 * local node), but not all transactions seen are added to the pool. For
213
 * example, the following new transactions will not be added to the mempool:
214
 * - a transaction which doesn't meet the minimum fee requirements.
215
 * - a new transaction that double-spends an input of a transaction already in
216
 * the pool where the new transaction does not meet the Replace-By-Fee
217
 * requirements as defined in doc/policy/mempool-replacements.md.
218
 * - a non-standard transaction.
219
 *
220
 * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
221
 *
222
 * mapTx is a boost::multi_index that sorts the mempool on 5 criteria:
223
 * - transaction hash (txid)
224
 * - witness-transaction hash (wtxid)
225
 * - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)]
226
 * - time in mempool
227
 * - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)]
228
 *
229
 * Note: the term "descendant" refers to in-mempool transactions that depend on
230
 * this one, while "ancestor" refers to in-mempool transactions that a given
231
 * transaction depends on.
232
 *
233
 * In order for the feerate sort to remain correct, we must update transactions
234
 * in the mempool when new descendants arrive.  To facilitate this, we track
235
 * the set of in-mempool direct parents and direct children in mapLinks.  Within
236
 * each CTxMemPoolEntry, we track the size and fees of all descendants.
237
 *
238
 * Usually when a new transaction is added to the mempool, it has no in-mempool
239
 * children (because any such children would be an orphan).  So in
240
 * addNewTransaction(), we:
241
 * - update a new entry's m_parents to include all in-mempool parents
242
 * - update each of those parent entries to include the new tx as a child
243
 * - update all ancestors of the transaction to include the new tx's size/fee
244
 *
245
 * When a transaction is removed from the mempool, we must:
246
 * - update all in-mempool parents to not track the tx in their m_children
247
 * - update all ancestors to not include the tx's size/fees in descendant state
248
 * - update all in-mempool children to not include it as a parent
249
 *
250
 * These happen in UpdateForRemoveFromMempool().  (Note that when removing a
251
 * transaction along with its descendants, we must calculate that set of
252
 * transactions to be removed before doing the removal, or else the mempool can
253
 * be in an inconsistent state where it's impossible to walk the ancestors of
254
 * a transaction.)
255
 *
256
 * In the event of a reorg, the assumption that a newly added tx has no
257
 * in-mempool children is false.  In particular, the mempool is in an
258
 * inconsistent state while new transactions are being added, because there may
259
 * be descendant transactions of a tx coming from a disconnected block that are
260
 * unreachable from just looking at transactions in the mempool (the linking
261
 * transactions may also be in the disconnected block, waiting to be added).
262
 * Because of this, there's not much benefit in trying to search for in-mempool
263
 * children in addNewTransaction().  Instead, in the special case of transactions
264
 * being added from a disconnected block, we require the caller to clean up the
265
 * state, to account for in-mempool, out-of-block descendants for all the
266
 * in-block transactions by calling UpdateTransactionsFromBlock().  Note that
267
 * until this is called, the mempool state is not consistent, and in particular
268
 * mapLinks may not be correct (and therefore functions like
269
 * CalculateMemPoolAncestors() and CalculateDescendants() that rely
270
 * on them to walk the mempool are not generally safe to use).
271
 *
272
 * Computational limits:
273
 *
274
 * Updating all in-mempool ancestors of a newly added transaction can be slow,
275
 * if no bound exists on how many in-mempool ancestors there may be.
276
 * CalculateMemPoolAncestors() takes configurable limits that are designed to
277
 * prevent these calculations from being too CPU intensive.
278
 *
279
 */
280
class CTxMemPool
281
{
282
protected:
283
    std::atomic<unsigned int> nTransactionsUpdated{0}; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
284
285
    uint64_t totalTxSize GUARDED_BY(cs){0};      //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
286
    CAmount m_total_fee GUARDED_BY(cs){0};       //!< sum of all mempool tx's fees (NOT modified fee)
287
    uint64_t cachedInnerUsage GUARDED_BY(cs){0}; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
288
289
    mutable int64_t lastRollingFeeUpdate GUARDED_BY(cs){GetTime()};
290
    mutable bool blockSinceLastRollingFeeBump GUARDED_BY(cs){false};
291
    mutable double rollingMinimumFeeRate GUARDED_BY(cs){0}; //!< minimum fee to get into the pool, decreases exponentially
292
    mutable Epoch m_epoch GUARDED_BY(cs){};
293
294
    // In-memory counter for external mempool tracking purposes.
295
    // This number is incremented once every time a transaction
296
    // is added or removed from the mempool for any reason.
297
    mutable uint64_t m_sequence_number GUARDED_BY(cs){1};
298
299
    void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
300
301
    bool m_load_tried GUARDED_BY(cs){false};
302
303
    CFeeRate GetMinFee(size_t sizelimit) const;
304
305
public:
306
307
    static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
308
309
    struct CTxMemPoolEntry_Indices final : boost::multi_index::indexed_by<
310
            // sorted by txid
311
            boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
312
            // sorted by wtxid
313
            boost::multi_index::hashed_unique<
314
                boost::multi_index::tag<index_by_wtxid>,
315
                mempoolentry_wtxid,
316
                SaltedWtxidHasher
317
            >,
318
            // sorted by fee rate
319
            boost::multi_index::ordered_non_unique<
320
                boost::multi_index::tag<descendant_score>,
321
                boost::multi_index::identity<CTxMemPoolEntry>,
322
                CompareTxMemPoolEntryByDescendantScore
323
            >,
324
            // sorted by entry time
325
            boost::multi_index::ordered_non_unique<
326
                boost::multi_index::tag<entry_time>,
327
                boost::multi_index::identity<CTxMemPoolEntry>,
328
                CompareTxMemPoolEntryByEntryTime
329
            >,
330
            // sorted by fee rate with ancestors
331
            boost::multi_index::ordered_non_unique<
332
                boost::multi_index::tag<ancestor_score>,
333
                boost::multi_index::identity<CTxMemPoolEntry>,
334
                CompareTxMemPoolEntryByAncestorFee
335
            >
336
        >
337
        {};
338
    typedef boost::multi_index_container<
339
        CTxMemPoolEntry,
340
        CTxMemPoolEntry_Indices
341
    > indexed_transaction_set;
342
343
    /**
344
     * This mutex needs to be locked when accessing `mapTx` or other members
345
     * that are guarded by it.
346
     *
347
     * @par Consistency guarantees
348
     * By design, it is guaranteed that:
349
     * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool
350
     *    that is consistent with current chain tip (`ActiveChain()` and
351
     *    `CoinsTip()`) and is fully populated. Fully populated means that if the
352
     *    current active chain is missing transactions that were present in a
353
     *    previously active chain, all the missing transactions will have been
354
     *    re-added to the mempool and should be present if they meet size and
355
     *    consistency constraints.
356
     * 2. Locking `mempool.cs` without `cs_main` will give a view of a mempool
357
     *    consistent with some chain that was active since `cs_main` was last
358
     *    locked, and that is fully populated as described above. It is ok for
359
     *    code that only needs to query or remove transactions from the mempool
360
     *    to lock just `mempool.cs` without `cs_main`.
361
     *
362
     * To provide these guarantees, it is necessary to lock both `cs_main` and
363
     * `mempool.cs` whenever adding transactions to the mempool and whenever
364
     * changing the chain tip. It's necessary to keep both mutexes locked until
365
     * the mempool is consistent with the new chain tip and fully populated.
366
     */
367
    mutable RecursiveMutex cs;
368
    indexed_transaction_set mapTx GUARDED_BY(cs);
369
370
    using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
371
    std::vector<std::pair<Wtxid, txiter>> txns_randomized GUARDED_BY(cs); //!< All transactions in mapTx with their wtxids, in arbitrary order
372
373
    typedef std::set<txiter, CompareIteratorByHash> setEntries;
374
375
    using Limits = kernel::MemPoolLimits;
376
377
    uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
378
private:
379
    typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
380
381
382
    void UpdateParent(txiter entry, txiter parent, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
383
    void UpdateChild(txiter entry, txiter child, bool add) EXCLUSIVE_LOCKS_REQUIRED(cs);
384
385
    std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
386
387
    /**
388
     * Track locally submitted transactions to periodically retry initial broadcast.
389
     */
390
    std::set<Txid> m_unbroadcast_txids GUARDED_BY(cs);
391
392
393
    /**
394
     * Helper function to calculate all in-mempool ancestors of staged_ancestors and apply ancestor
395
     * and descendant limits (including staged_ancestors themselves, entry_size and entry_count).
396
     *
397
     * @param[in]   entry_size          Virtual size to include in the limits.
398
     * @param[in]   entry_count         How many entries to include in the limits.
399
     * @param[in]   staged_ancestors    Should contain entries in the mempool.
400
     * @param[in]   limits              Maximum number and size of ancestors and descendants
401
     *
402
     * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit
403
     */
404
    util::Result<setEntries> CalculateAncestorsAndCheckLimits(int64_t entry_size,
405
                                                              size_t entry_count,
406
                                                              CTxMemPoolEntry::Parents &staged_ancestors,
407
                                                              const Limits& limits
408
                                                              ) const EXCLUSIVE_LOCKS_REQUIRED(cs);
409
410
    static TxMempoolInfo GetInfo(CTxMemPool::indexed_transaction_set::const_iterator it)
411
0
    {
412
0
        return TxMempoolInfo{it->GetSharedTx(), it->GetTime(), it->GetFee(), it->GetTxSize(), it->GetModifiedFee() - it->GetFee()};
413
0
    }
414
415
public:
416
    indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
417
    std::map<Txid, CAmount> mapDeltas GUARDED_BY(cs);
418
419
    using Options = kernel::MemPoolOptions;
420
421
    const Options m_opts;
422
423
    /** Create a new CTxMemPool.
424
     * Sanity checks will be off by default for performance, because otherwise
425
     * accepting transactions becomes O(N^2) where N is the number of transactions
426
     * in the pool.
427
     */
428
    explicit CTxMemPool(Options opts, bilingual_str& error);
429
430
    /**
431
     * If sanity-checking is turned on, check makes sure the pool is
432
     * consistent (does not contain two transactions that spend the same inputs,
433
     * all inputs are in the mapNextTx array). If sanity-checking is turned off,
434
     * check does nothing.
435
     */
436
    void check(const CCoinsViewCache& active_coins_tip, int64_t spendheight) const EXCLUSIVE_LOCKS_REQUIRED(::cs_main);
437
438
439
    void removeRecursive(const CTransaction& tx, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
440
    /** After reorg, filter the entries that would no longer be valid in the next block, and update
441
     * the entries' cached LockPoints if needed.  The mempool does not have any knowledge of
442
     * consensus rules. It just applies the callable function and removes the ones for which it
443
     * returns true.
444
     * @param[in]   filter_final_and_mature   Predicate that checks the relevant validation rules
445
     *                                        and updates an entry's LockPoints.
446
     * */
447
    void removeForReorg(CChain& chain, std::function<bool(txiter)> filter_final_and_mature) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main);
448
    void removeConflicts(const CTransaction& tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
449
    void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight) EXCLUSIVE_LOCKS_REQUIRED(cs);
450
451
    bool CompareDepthAndScore(const Wtxid& hasha, const Wtxid& hashb) const;
452
    bool isSpent(const COutPoint& outpoint) const;
453
    unsigned int GetTransactionsUpdated() const;
454
    void AddTransactionsUpdated(unsigned int n);
455
    /**
456
     * Check that none of this transactions inputs are in the mempool, and thus
457
     * the tx is not dependent on other mempool transactions to be included in a block.
458
     */
459
    bool HasNoInputsOf(const CTransaction& tx) const EXCLUSIVE_LOCKS_REQUIRED(cs);
460
461
    /** Affect CreateNewBlock prioritisation of transactions */
462
    void PrioritiseTransaction(const Txid& hash, const CAmount& nFeeDelta);
463
    void ApplyDelta(const Txid& hash, CAmount &nFeeDelta) const EXCLUSIVE_LOCKS_REQUIRED(cs);
464
    void ClearPrioritisation(const Txid& hash) EXCLUSIVE_LOCKS_REQUIRED(cs);
465
466
    struct delta_info {
467
        /** Whether this transaction is in the mempool. */
468
        const bool in_mempool;
469
        /** The fee delta added using PrioritiseTransaction(). */
470
        const CAmount delta;
471
        /** The modified fee (base fee + delta) of this entry. Only present if in_mempool=true. */
472
        std::optional<CAmount> modified_fee;
473
        /** The prioritised transaction's txid. */
474
        const Txid txid;
475
    };
476
    /** Return a vector of all entries in mapDeltas with their corresponding delta_info. */
477
    std::vector<delta_info> GetPrioritisedTransactions() const EXCLUSIVE_LOCKS_REQUIRED(!cs);
478
479
    /** Get the transaction in the pool that spends the same prevout */
480
    const CTransaction* GetConflictTx(const COutPoint& prevout) const EXCLUSIVE_LOCKS_REQUIRED(cs);
481
482
    /** Returns an iterator to the given hash, if found */
483
    std::optional<txiter> GetIter(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
484
    std::optional<txiter> GetIter(const Wtxid& wtxid) const EXCLUSIVE_LOCKS_REQUIRED(cs);
485
486
    /** Translate a set of hashes into a set of pool iterators to avoid repeated lookups.
487
     * Does not require that all of the hashes correspond to actual transactions in the mempool,
488
     * only returns the ones that exist. */
489
    setEntries GetIterSet(const std::set<Txid>& hashes) const EXCLUSIVE_LOCKS_REQUIRED(cs);
490
491
    /** Translate a list of hashes into a list of mempool iterators to avoid repeated lookups.
492
     * The nth element in txids becomes the nth element in the returned vector. If any of the txids
493
     * don't actually exist in the mempool, returns an empty vector. */
494
    std::vector<txiter> GetIterVec(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
495
496
    /** UpdateTransactionsFromBlock is called when adding transactions from a
497
     * disconnected block back to the mempool, new mempool entries may have
498
     * children in the mempool (which is generally not the case when otherwise
499
     * adding transactions).
500
     *  @post updated descendant state for descendants of each transaction in
501
     *        vHashesToUpdate (excluding any child transactions present in
502
     *        vHashesToUpdate, which are already accounted for). Updated state
503
     *        includes add fee/size information for such descendants to the
504
     *        parent and updated ancestor state to include the parent.
505
     *
506
     * @param[in] vHashesToUpdate          The set of txids from the
507
     *     disconnected block that have been accepted back into the mempool.
508
     */
509
    void UpdateTransactionsFromBlock(const std::vector<Txid>& vHashesToUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs, cs_main) LOCKS_EXCLUDED(m_epoch);
510
511
    /**
512
     * Try to calculate all in-mempool ancestors of entry.
513
     * (these are all calculated including the tx itself)
514
     *
515
     * @param[in]   entry               CTxMemPoolEntry of which all in-mempool ancestors are calculated
516
     * @param[in]   limits              Maximum number and size of ancestors and descendants
517
     * @param[in]   fSearchForParents   Whether to search a tx's vin for in-mempool parents, or look
518
     *                                  up parents from mapLinks. Must be true for entries not in
519
     *                                  the mempool
520
     *
521
     * @return all in-mempool ancestors, or an error if any ancestor or descendant limits were hit
522
     */
523
    util::Result<setEntries> CalculateMemPoolAncestors(const CTxMemPoolEntry& entry,
524
                                   const Limits& limits,
525
                                   bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
526
527
    /**
528
     * Same as CalculateMemPoolAncestors, but always returns a (non-optional) setEntries.
529
     * Should only be used when it is assumed CalculateMemPoolAncestors would not fail. If
530
     * CalculateMemPoolAncestors does unexpectedly fail, an empty setEntries is returned and the
531
     * error is logged to BCLog::MEMPOOL with level BCLog::Level::Error. In debug builds, failure
532
     * of CalculateMemPoolAncestors will lead to shutdown due to assertion failure.
533
     *
534
     * @param[in]   calling_fn_name     Name of calling function so we can properly log the call site
535
     *
536
     * @return a setEntries corresponding to the result of CalculateMemPoolAncestors or an empty
537
     *         setEntries if it failed
538
     *
539
     * @see CTXMemPool::CalculateMemPoolAncestors()
540
     */
541
    setEntries AssumeCalculateMemPoolAncestors(
542
        std::string_view calling_fn_name,
543
        const CTxMemPoolEntry &entry,
544
        const Limits& limits,
545
        bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
546
547
    /** Collect the entire cluster of connected transactions for each transaction in txids.
548
     * All txids must correspond to transaction entries in the mempool, otherwise this returns an
549
     * empty vector. This call will also exit early and return an empty vector if it collects 500 or
550
     * more transactions as a DoS protection. */
551
    std::vector<txiter> GatherClusters(const std::vector<Txid>& txids) const EXCLUSIVE_LOCKS_REQUIRED(cs);
552
553
    /** Calculate all in-mempool ancestors of a set of transactions not already in the mempool and
554
     * check ancestor and descendant limits. Heuristics are used to estimate the ancestor and
555
     * descendant count of all entries if the package were to be added to the mempool.  The limits
556
     * are applied to the union of all package transactions. For example, if the package has 3
557
     * transactions and limits.ancestor_count = 25, the union of all 3 sets of ancestors (including the
558
     * transactions themselves) must be <= 22.
559
     * @param[in]       package                 Transaction package being evaluated for acceptance
560
     *                                          to mempool. The transactions need not be direct
561
     *                                          ancestors/descendants of each other.
562
     * @param[in]       total_vsize             Sum of virtual sizes for all transactions in package.
563
     * @returns {} or the error reason if a limit is hit.
564
     */
565
    util::Result<void> CheckPackageLimits(const Package& package,
566
                                          int64_t total_vsize) const EXCLUSIVE_LOCKS_REQUIRED(cs);
567
568
    /** Populate setDescendants with all in-mempool descendants of hash.
569
     *  Assumes that setDescendants includes all in-mempool descendants of anything
570
     *  already in it.  */
571
    void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
572
573
    /** The minimum fee to get into the mempool, which may itself not be enough
574
     *  for larger-sized transactions.
575
     *  The m_incremental_relay_feerate policy variable is used to bound the time it
576
     *  takes the fee rate to go back down all the way to 0. When the feerate
577
     *  would otherwise be half of this, it is set to 0 instead.
578
     */
579
0
    CFeeRate GetMinFee() const {
580
0
        return GetMinFee(m_opts.max_size_bytes);
581
0
    }
582
583
    /** Remove transactions from the mempool until its dynamic size is <= sizelimit.
584
      *  pvNoSpendsRemaining, if set, will be populated with the list of outpoints
585
      *  which are not in mempool which no longer have any spends in this mempool.
586
      */
587
    void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs);
588
589
    /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
590
    int Expire(std::chrono::seconds time) EXCLUSIVE_LOCKS_REQUIRED(cs);
591
592
    /**
593
     * Calculate the ancestor and descendant count for the given transaction.
594
     * The counts include the transaction itself.
595
     * When ancestors is non-zero (ie, the transaction itself is in the mempool),
596
     * ancestorsize and ancestorfees will also be set to the appropriate values.
597
     */
598
    void GetTransactionAncestry(const Txid& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize = nullptr, CAmount* ancestorfees = nullptr) const;
599
600
    /**
601
     * @returns true if an initial attempt to load the persisted mempool was made, regardless of
602
     *          whether the attempt was successful or not
603
     */
604
    bool GetLoadTried() const;
605
606
    /**
607
     * Set whether or not an initial attempt to load the persisted mempool was made (regardless
608
     * of whether the attempt was successful or not)
609
     */
610
    void SetLoadTried(bool load_tried);
611
612
    unsigned long size() const
613
0
    {
614
0
        LOCK(cs);
615
0
        return mapTx.size();
616
0
    }
617
618
    uint64_t GetTotalTxSize() const EXCLUSIVE_LOCKS_REQUIRED(cs)
619
0
    {
620
0
        AssertLockHeld(cs);
621
0
        return totalTxSize;
622
0
    }
623
624
    CAmount GetTotalFee() const EXCLUSIVE_LOCKS_REQUIRED(cs)
625
0
    {
626
0
        AssertLockHeld(cs);
627
0
        return m_total_fee;
628
0
    }
629
630
    bool exists(const Txid& txid) const
631
158k
    {
632
158k
        LOCK(cs);
633
158k
        return (mapTx.count(txid) != 0);
634
158k
    }
635
636
    bool exists(const Wtxid& wtxid) const
637
0
    {
638
0
        LOCK(cs);
639
0
        return (mapTx.get<index_by_wtxid>().count(wtxid) != 0);
640
0
    }
641
642
    const CTxMemPoolEntry* GetEntry(const Txid& txid) const LIFETIMEBOUND EXCLUSIVE_LOCKS_REQUIRED(cs);
643
644
    CTransactionRef get(const Txid& hash) const;
645
646
    template <TxidOrWtxid T>
647
    TxMempoolInfo info(const T& id) const
648
0
    {
649
0
        LOCK(cs);
650
0
        auto i{GetIter(id)};
651
0
        return i.has_value() ? GetInfo(*i) : TxMempoolInfo{};
652
0
    }
Unexecuted instantiation: _ZNK10CTxMemPool4infoITk11TxidOrWtxid22transaction_identifierILb0EEEE13TxMempoolInfoRKT_
Unexecuted instantiation: _ZNK10CTxMemPool4infoITk11TxidOrWtxid22transaction_identifierILb1EEEE13TxMempoolInfoRKT_
653
654
    /** Returns info for a transaction if its entry_sequence < last_sequence */
655
    template <TxidOrWtxid T>
656
    TxMempoolInfo info_for_relay(const T& id, uint64_t last_sequence) const
657
0
    {
658
0
        LOCK(cs);
659
0
        auto i{GetIter(id)};
660
0
        return (i.has_value() && i.value()->GetSequence() < last_sequence) ? GetInfo(*i) : TxMempoolInfo{};
661
0
    }
Unexecuted instantiation: _ZNK10CTxMemPool14info_for_relayITk11TxidOrWtxid22transaction_identifierILb0EEEE13TxMempoolInfoRKT_m
Unexecuted instantiation: _ZNK10CTxMemPool14info_for_relayITk11TxidOrWtxid22transaction_identifierILb1EEEE13TxMempoolInfoRKT_m
662
663
    std::vector<CTxMemPoolEntryRef> entryAll() const EXCLUSIVE_LOCKS_REQUIRED(cs);
664
    std::vector<TxMempoolInfo> infoAll() const;
665
666
    size_t DynamicMemoryUsage() const;
667
668
    /** Adds a transaction to the unbroadcast set */
669
    void AddUnbroadcastTx(const Txid& txid)
670
0
    {
671
0
        LOCK(cs);
672
        // Sanity check the transaction is in the mempool & insert into
673
        // unbroadcast set.
674
0
        if (exists(txid)) m_unbroadcast_txids.insert(txid);
675
0
    };
676
677
    /** Removes a transaction from the unbroadcast set */
678
    void RemoveUnbroadcastTx(const Txid& txid, const bool unchecked = false);
679
680
    /** Returns transactions in unbroadcast set */
681
    std::set<Txid> GetUnbroadcastTxs() const
682
0
    {
683
0
        LOCK(cs);
684
0
        return m_unbroadcast_txids;
685
0
    }
686
687
    /** Returns whether a txid is in the unbroadcast set */
688
    bool IsUnbroadcastTx(const Txid& txid) const EXCLUSIVE_LOCKS_REQUIRED(cs)
689
0
    {
690
0
        AssertLockHeld(cs);
691
0
        return m_unbroadcast_txids.count(txid) != 0;
692
0
    }
693
694
    /** Guards this internal counter for external reporting */
695
0
    uint64_t GetAndIncrementSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
696
0
        return m_sequence_number++;
697
0
    }
698
699
0
    uint64_t GetSequence() const EXCLUSIVE_LOCKS_REQUIRED(cs) {
700
0
        return m_sequence_number;
701
0
    }
702
703
    /* Check that all direct conflicts are in a cluster size of two or less. Each
704
     * direct conflict may be in a separate cluster.
705
     */
706
    std::optional<std::string> CheckConflictTopology(const setEntries& direct_conflicts);
707
708
private:
709
    /** Remove a set of transactions from the mempool.
710
     *  If a transaction is in this set, then all in-mempool descendants must
711
     *  also be in the set, unless this transaction is being removed for being
712
     *  in a block.
713
     *  Set updateDescendants to true when removing a tx that was in a block, so
714
     *  that any in-mempool descendants have their ancestor state updated.
715
     */
716
    void RemoveStaged(setEntries& stage, bool updateDescendants, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
717
718
    /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
719
     *  the descendants for a single transaction that has been added to the
720
     *  mempool but may have child transactions in the mempool, eg during a
721
     *  chain reorg.
722
     *
723
     * @pre CTxMemPoolEntry::m_children is correct for the given tx and all
724
     *      descendants.
725
     * @pre cachedDescendants is an accurate cache where each entry has all
726
     *      descendants of the corresponding key, including those that should
727
     *      be removed for violation of ancestor limits.
728
     * @post if updateIt has any non-excluded descendants, cachedDescendants has
729
     *       a new cache line for updateIt.
730
     * @post descendants_to_remove has a new entry for any descendant which exceeded
731
     *       ancestor limits relative to updateIt.
732
     *
733
     * @param[in] updateIt the entry to update for its descendants
734
     * @param[in,out] cachedDescendants a cache where each line corresponds to all
735
     *     descendants. It will be updated with the descendants of the transaction
736
     *     being updated, so that future invocations don't need to walk the same
737
     *     transaction again, if encountered in another transaction chain.
738
     * @param[in] setExclude the set of descendant transactions in the mempool
739
     *     that must not be accounted for (because any descendants in setExclude
740
     *     were added to the mempool after the transaction being updated and hence
741
     *     their state is already reflected in the parent state).
742
     * @param[out] descendants_to_remove Populated with the txids of entries that
743
     *     exceed ancestor limits. It's the responsibility of the caller to
744
     *     removeRecursive them.
745
     */
746
    void UpdateForDescendants(txiter updateIt, cacheMap& cachedDescendants,
747
                              const std::set<Txid>& setExclude, std::set<Txid>& descendants_to_remove) EXCLUSIVE_LOCKS_REQUIRED(cs);
748
    /** Update ancestors of hash to add/remove it as a descendant transaction. */
749
    void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
750
    /** Set ancestor state for an entry */
751
    void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
752
    /** For each transaction being removed, update ancestors and any direct children.
753
      * If updateDescendants is true, then also update in-mempool descendants'
754
      * ancestor state. */
755
    void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
756
    /** Sever link between specified transaction and direct children. */
757
    void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs);
758
759
    /** Before calling removeUnchecked for a given transaction,
760
     *  UpdateForRemoveFromMempool must be called on the entire (dependent) set
761
     *  of transactions being removed at the same time.  We use each
762
     *  CTxMemPoolEntry's m_parents in order to walk ancestors of a
763
     *  given transaction that is removed, so we can't remove intermediate
764
     *  transactions in a chain before we've updated all the state for the
765
     *  removal.
766
     */
767
    void removeUnchecked(txiter entry, MemPoolRemovalReason reason) EXCLUSIVE_LOCKS_REQUIRED(cs);
768
public:
769
    /** visited marks a CTxMemPoolEntry as having been traversed
770
     * during the lifetime of the most recently created Epoch::Guard
771
     * and returns false if we are the first visitor, true otherwise.
772
     *
773
     * An Epoch::Guard must be held when visited is called or an assert will be
774
     * triggered.
775
     *
776
     */
777
    bool visited(const txiter it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
778
764k
    {
779
764k
        return m_epoch.visited(it->m_epoch_marker);
780
764k
    }
781
782
    bool visited(std::optional<txiter> it) const EXCLUSIVE_LOCKS_REQUIRED(cs, m_epoch)
783
0
    {
784
0
        assert(m_epoch.guarded()); // verify guard even when it==nullopt
785
0
        return !it || visited(*it);
786
0
    }
787
788
    /*
789
     * CTxMemPool::ChangeSet:
790
     *
791
     * This class is used for all mempool additions and associated removals (eg
792
     * due to rbf). Removals that don't need to be evaluated for acceptance,
793
     * such as removing transactions that appear in a block, or due to reorg,
794
     * or removals related to mempool limiting or expiry do not need to use
795
     * this.
796
     *
797
     * Callers can interleave calls to StageAddition()/StageRemoval(), and
798
     * removals may be invoked in any order, but additions must be done in a
799
     * topological order in the case of transaction packages (ie, parents must
800
     * be added before children).
801
     *
802
     * CalculateChunksForRBF() can be used to calculate the feerate diagram of
803
     * the proposed set of new transactions and compare with the existing
804
     * mempool.
805
     *
806
     * CalculateMemPoolAncestors() calculates the in-mempool (not including
807
     * what is in the change set itself) ancestors of a given transaction.
808
     *
809
     * Apply() will apply the removals and additions that are staged into the
810
     * mempool.
811
     *
812
     * Only one changeset may exist at a time. While a changeset is
813
     * outstanding, no removals or additions may be made directly to the
814
     * mempool.
815
     */
816
    class ChangeSet {
817
    public:
818
125k
        explicit ChangeSet(CTxMemPool* pool) : m_pool(pool) {}
819
125k
        ~ChangeSet() EXCLUSIVE_LOCKS_REQUIRED(m_pool->cs) { m_pool->m_have_changeset = false; }
820
821
        ChangeSet(const ChangeSet&) = delete;
822
        ChangeSet& operator=(const ChangeSet&) = delete;
823
824
        using TxHandle = CTxMemPool::txiter;
825
826
        TxHandle 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);
827
0
        void StageRemoval(CTxMemPool::txiter it) { m_to_remove.insert(it); }
828
829
0
        const CTxMemPool::setEntries& GetRemovals() const { return m_to_remove; }
830
831
        util::Result<CTxMemPool::setEntries> CalculateMemPoolAncestors(TxHandle tx, const Limits& limits)
832
125k
        {
833
            // Look up transaction in our cache first
834
125k
            auto it = m_ancestors.find(tx);
835
125k
            if (it != m_ancestors.end()) return it->second;
836
837
            // If not found, try to have the mempool calculate it, and cache
838
            // for later.
839
125k
            LOCK(m_pool->cs);
840
125k
            auto ret{m_pool->CalculateMemPoolAncestors(*tx, limits)};
841
125k
            if (ret) m_ancestors.try_emplace(tx, *ret);
842
125k
            return ret;
843
125k
        }
844
845
0
        std::vector<CTransactionRef> GetAddedTxns() const {
846
0
            std::vector<CTransactionRef> ret;
847
0
            ret.reserve(m_entry_vec.size());
848
0
            for (const auto& entry : m_entry_vec) {
849
0
                ret.emplace_back(entry->GetSharedTx());
850
0
            }
851
0
            return ret;
852
0
        }
853
854
        /**
855
         * Calculate the sorted chunks for the old and new mempool relating to the
856
         * clusters that would be affected by a potential replacement transaction.
857
         *
858
         * @return old and new diagram pair respectively, or an error string if the conflicts don't match a calculable topology
859
         */
860
        util::Result<std::pair<std::vector<FeeFrac>, std::vector<FeeFrac>>> CalculateChunksForRBF();
861
862
0
        size_t GetTxCount() const { return m_entry_vec.size(); }
863
0
        const CTransaction& GetAddedTxn(size_t index) const { return m_entry_vec.at(index)->GetTx(); }
864
865
        void Apply() EXCLUSIVE_LOCKS_REQUIRED(cs_main);
866
867
    private:
868
        CTxMemPool* m_pool;
869
        CTxMemPool::indexed_transaction_set m_to_add;
870
        std::vector<CTxMemPool::txiter> m_entry_vec; // track the added transactions' insertion order
871
        // map from the m_to_add index to the ancestors for the transaction
872
        std::map<CTxMemPool::txiter, CTxMemPool::setEntries, CompareIteratorByHash> m_ancestors;
873
        CTxMemPool::setEntries m_to_remove;
874
875
        friend class CTxMemPool;
876
    };
877
878
125k
    std::unique_ptr<ChangeSet> GetChangeSet() EXCLUSIVE_LOCKS_REQUIRED(cs) {
879
125k
        Assume(!m_have_changeset);
880
125k
        m_have_changeset = true;
881
125k
        return std::make_unique<ChangeSet>(this);
882
125k
    }
883
884
    bool m_have_changeset GUARDED_BY(cs){false};
885
886
    friend class CTxMemPool::ChangeSet;
887
888
private:
889
    // Apply the given changeset to the mempool, by removing transactions in
890
    // the to_remove set and adding transactions in the to_add set.
891
    void Apply(CTxMemPool::ChangeSet* changeset) EXCLUSIVE_LOCKS_REQUIRED(cs);
892
893
    // addNewTransaction must update state for all ancestors of a given transaction,
894
    // to track size/count of descendant transactions.  First version of
895
    // addNewTransaction can be used to have it call CalculateMemPoolAncestors(), and
896
    // then invoke the second version.
897
    // Note that addNewTransaction is ONLY called (via Apply()) from ATMP
898
    // outside of tests and any other callers may break wallet's in-mempool
899
    // tracking (due to lack of CValidationInterface::TransactionAddedToMempool
900
    // callbacks).
901
    void addNewTransaction(CTxMemPool::txiter it) EXCLUSIVE_LOCKS_REQUIRED(cs);
902
    void addNewTransaction(CTxMemPool::txiter it, CTxMemPool::setEntries& setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
903
};
904
905
/**
906
 * CCoinsView that brings transactions from a mempool into view.
907
 * It does not check for spendings by memory pool transactions.
908
 * Instead, it provides access to all Coins which are either unspent in the
909
 * base CCoinsView, are outputs from any mempool transaction, or are
910
 * tracked temporarily to allow transaction dependencies in package validation.
911
 * This allows transaction replacement to work as expected, as you want to
912
 * have all inputs "available" to check signatures, and any cycles in the
913
 * dependency graph are checked directly in AcceptToMemoryPool.
914
 * It also allows you to sign a double-spend directly in
915
 * signrawtransactionwithkey and signrawtransactionwithwallet,
916
 * as long as the conflicting transaction is not yet confirmed.
917
 */
918
class CCoinsViewMemPool : public CCoinsViewBacked
919
{
920
    /**
921
    * Coins made available by transactions being validated. Tracking these allows for package
922
    * validation, since we can access transaction outputs without submitting them to mempool.
923
    */
924
    std::unordered_map<COutPoint, Coin, SaltedOutpointHasher> m_temp_added;
925
926
    /**
927
     * Set of all coins that have been fetched from mempool or created using PackageAddTransaction
928
     * (not base). Used to track the origin of a coin, see GetNonBaseCoins().
929
     */
930
    mutable std::unordered_set<COutPoint, SaltedOutpointHasher> m_non_base_coins;
931
protected:
932
    const CTxMemPool& mempool;
933
934
public:
935
    CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
936
    /** GetCoin, returning whether it exists and is not spent. Also updates m_non_base_coins if the
937
     * coin is not fetched from base. */
938
    std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
939
    /** Add the coins created by this transaction. These coins are only temporarily stored in
940
     * m_temp_added and cannot be flushed to the back end. Only used for package validation. */
941
    void PackageAddTransaction(const CTransactionRef& tx);
942
    /** Get all coins in m_non_base_coins. */
943
0
    const std::unordered_set<COutPoint, SaltedOutpointHasher>& GetNonBaseCoins() const { return m_non_base_coins; }
944
    /** Clear m_temp_added and m_non_base_coins. */
945
    void Reset();
946
};
947
#endif // BITCOIN_TXMEMPOOL_H