Coverage Report

Created: 2026-06-12 16:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/test/util/txmempool.cpp
Line
Count
Source
1
// Copyright (c) 2022-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <test/util/txmempool.h>
6
7
#include <chainparams.h>
8
#include <node/context.h>
9
#include <node/mempool_args.h>
10
#include <policy/rbf.h>
11
#include <policy/truc_policy.h>
12
#include <txmempool.h>
13
#include <test/util/transaction_utils.h>
14
#include <util/check.h>
15
#include <util/time.h>
16
#include <util/translation.h>
17
#include <validation.h>
18
19
using node::NodeContext;
20
21
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext& node)
22
0
{
23
0
    CTxMemPool::Options mempool_opts{
24
        // Default to always checking mempool regardless of
25
        // chainparams.DefaultConsistencyChecks for tests
26
0
        .check_ratio = 1,
27
0
        .signals = node.validation_signals.get(),
28
0
    };
29
0
    const auto result{ApplyArgsManOptions(*node.args, ::Params(), mempool_opts)};
30
0
    Assert(result);
31
0
    return mempool_opts;
32
0
}
33
34
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction& tx) const
35
0
{
36
0
    return FromTx(MakeTransactionRef(tx));
37
0
}
38
39
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx) const
40
0
{
41
0
    return CTxMemPoolEntry{tx, nFee, TicksSinceEpoch<std::chrono::seconds>(time), nHeight, m_sequence, spendsCoinbase, sigOpCost, lp};
42
0
}
43
44
std::optional<std::string> CheckPackageMempoolAcceptResult(const Package& txns,
45
                                                           const PackageMempoolAcceptResult& result,
46
                                                           bool expect_valid,
47
                                                           const CTxMemPool* mempool)
48
0
{
49
0
    if (expect_valid) {
  Branch (49:9): [True: 0, False: 0]
50
0
        if (result.m_state.IsInvalid()) {
  Branch (50:13): [True: 0, False: 0]
51
0
            return strprintf("Package validation unexpectedly failed: %s", result.m_state.ToString());
52
0
        }
53
0
    } else {
54
0
        if (result.m_state.IsValid()) {
  Branch (54:13): [True: 0, False: 0]
55
0
            return strprintf("Package validation unexpectedly succeeded. %s", result.m_state.ToString());
56
0
        }
57
0
    }
58
0
    if (result.m_state.GetResult() != PackageValidationResult::PCKG_POLICY && txns.size() != result.m_tx_results.size()) {
  Branch (58:9): [True: 0, False: 0]
  Branch (58:79): [True: 0, False: 0]
59
0
        return strprintf("txns size %u does not match tx results size %u", txns.size(), result.m_tx_results.size());
60
0
    }
61
0
    for (const auto& tx : txns) {
  Branch (61:25): [True: 0, False: 0]
62
0
        const auto& wtxid = tx->GetWitnessHash();
63
0
        if (!result.m_tx_results.contains(wtxid)) {
  Branch (63:13): [True: 0, False: 0]
64
0
            return strprintf("result not found for tx %s", wtxid.ToString());
65
0
        }
66
67
0
        const auto& atmp_result = result.m_tx_results.at(wtxid);
68
0
        const bool valid{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID};
69
0
        if (expect_valid && atmp_result.m_state.IsInvalid()) {
  Branch (69:13): [True: 0, False: 0]
  Branch (69:29): [True: 0, False: 0]
70
0
            return strprintf("tx %s unexpectedly failed: %s", wtxid.ToString(), atmp_result.m_state.ToString());
71
0
        }
72
73
        // Each subpackage is allowed MAX_REPLACEMENT_CANDIDATES replacements (only checking individually here)
74
0
        if (atmp_result.m_replaced_transactions.size() > MAX_REPLACEMENT_CANDIDATES) {
  Branch (74:13): [True: 0, False: 0]
75
0
            return strprintf("tx %s result replaced too many transactions",
76
0
                                wtxid.ToString());
77
0
        }
78
79
        // Replacements can't happen for subpackages larger than 2
80
0
        if (!atmp_result.m_replaced_transactions.empty() &&
  Branch (80:13): [True: 0, False: 0]
81
0
            atmp_result.m_wtxids_fee_calculations.has_value() && atmp_result.m_wtxids_fee_calculations.value().size() > 2) {
  Branch (81:13): [True: 0, False: 0]
  Branch (81:66): [True: 0, False: 0]
82
0
             return strprintf("tx %s was part of a too-large package RBF subpackage",
83
0
                                wtxid.ToString());
84
0
        }
85
86
0
        if (!atmp_result.m_replaced_transactions.empty() && mempool) {
  Branch (86:13): [True: 0, False: 0]
  Branch (86:61): [True: 0, False: 0]
87
0
            LOCK(mempool->cs);
88
            // If replacements occurred and it used 2 transactions, this is a package RBF and should result in a cluster of size 2
89
0
            if (atmp_result.m_wtxids_fee_calculations.has_value() && atmp_result.m_wtxids_fee_calculations.value().size() == 2) {
  Branch (89:17): [True: 0, False: 0]
  Branch (89:70): [True: 0, False: 0]
90
0
                const auto cluster = mempool->GatherClusters({tx->GetHash()});
91
0
                if (cluster.size() != 2) return strprintf("tx %s has too many ancestors or descendants for a package rbf", wtxid.ToString());
  Branch (91:21): [True: 0, False: 0]
92
0
            }
93
0
        }
94
95
        // m_vsize and m_base_fees should exist iff the result was VALID or MEMPOOL_ENTRY
96
0
        const bool mempool_entry{atmp_result.m_result_type == MempoolAcceptResult::ResultType::MEMPOOL_ENTRY};
97
0
        if (atmp_result.m_base_fees.has_value() != (valid || mempool_entry)) {
  Branch (97:13): [True: 0, False: 0]
  Branch (97:53): [True: 0, False: 0]
  Branch (97:62): [True: 0, False: 0]
98
0
            return strprintf("tx %s result should %shave m_base_fees", wtxid.ToString(), valid || mempool_entry ? "" : "not ");
  Branch (98:90): [True: 0, False: 0]
  Branch (98:99): [True: 0, False: 0]
99
0
        }
100
0
        if (atmp_result.m_vsize.has_value() != (valid || mempool_entry)) {
  Branch (100:13): [True: 0, False: 0]
  Branch (100:49): [True: 0, False: 0]
  Branch (100:58): [True: 0, False: 0]
101
0
            return strprintf("tx %s result should %shave m_vsize", wtxid.ToString(), valid || mempool_entry ? "" : "not ");
  Branch (101:86): [True: 0, False: 0]
  Branch (101:95): [True: 0, False: 0]
102
0
        }
103
104
        // m_other_wtxid should exist iff the result was DIFFERENT_WITNESS
105
0
        const bool diff_witness{atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS};
106
0
        if (atmp_result.m_other_wtxid.has_value() != diff_witness) {
  Branch (106:13): [True: 0, False: 0]
107
0
            return strprintf("tx %s result should %shave m_other_wtxid", wtxid.ToString(), diff_witness ? "" : "not ");
  Branch (107:92): [True: 0, False: 0]
108
0
        }
109
110
        // m_effective_feerate and m_wtxids_fee_calculations should exist iff the result was valid
111
        // or if the failure was TX_RECONSIDERABLE
112
0
        const bool valid_or_reconsiderable{atmp_result.m_result_type == MempoolAcceptResult::ResultType::VALID ||
  Branch (112:44): [True: 0, False: 0]
113
0
                    atmp_result.m_state.GetResult() == TxValidationResult::TX_RECONSIDERABLE};
  Branch (113:21): [True: 0, False: 0]
114
0
        if (atmp_result.m_effective_feerate.has_value() != valid_or_reconsiderable) {
  Branch (114:13): [True: 0, False: 0]
115
0
            return strprintf("tx %s result should %shave m_effective_feerate",
116
0
                                    wtxid.ToString(), valid ? "" : "not ");
  Branch (116:55): [True: 0, False: 0]
117
0
        }
118
0
        if (atmp_result.m_wtxids_fee_calculations.has_value() != valid_or_reconsiderable) {
  Branch (118:13): [True: 0, False: 0]
119
0
            return strprintf("tx %s result should %shave m_effective_feerate",
120
0
                                    wtxid.ToString(), valid ? "" : "not ");
  Branch (120:55): [True: 0, False: 0]
121
0
        }
122
123
0
        if (mempool) {
  Branch (123:13): [True: 0, False: 0]
124
            // The tx by txid should be in the mempool iff the result was not INVALID.
125
0
            const bool txid_in_mempool{atmp_result.m_result_type != MempoolAcceptResult::ResultType::INVALID};
126
0
            if (mempool->exists(tx->GetHash()) != txid_in_mempool) {
  Branch (126:17): [True: 0, False: 0]
127
0
                return strprintf("tx %s should %sbe in mempool", wtxid.ToString(), txid_in_mempool ? "" : "not ");
  Branch (127:84): [True: 0, False: 0]
128
0
            }
129
            // Additionally, if the result was DIFFERENT_WITNESS, we shouldn't be able to find the tx in mempool by wtxid.
130
0
            if (tx->HasWitness() && atmp_result.m_result_type == MempoolAcceptResult::ResultType::DIFFERENT_WITNESS) {
  Branch (130:17): [True: 0, False: 0]
  Branch (130:37): [True: 0, False: 0]
131
0
                if (mempool->exists(wtxid)) {
  Branch (131:21): [True: 0, False: 0]
132
0
                    return strprintf("wtxid %s should not be in mempool", wtxid.ToString());
133
0
                }
134
0
            }
135
0
            for (const auto& tx_ref : atmp_result.m_replaced_transactions) {
  Branch (135:37): [True: 0, False: 0]
136
0
                if (mempool->exists(tx_ref->GetHash())) {
  Branch (136:21): [True: 0, False: 0]
137
0
                    return strprintf("tx %s should not be in mempool as it was replaced", tx_ref->GetWitnessHash().ToString());
138
0
                }
139
0
            }
140
0
        }
141
0
    }
142
0
    return std::nullopt;
143
0
}
144
145
void CheckMempoolEphemeralInvariants(const CTxMemPool& tx_pool)
146
0
{
147
0
    LOCK(tx_pool.cs);
148
0
    for (const auto& tx_info : tx_pool.infoAll()) {
  Branch (148:30): [True: 0, False: 0]
149
0
        const auto& entry = *Assert(tx_pool.GetEntry(tx_info.tx->GetHash()));
150
151
0
        std::vector<uint32_t> dust_indexes = GetDust(*tx_info.tx, tx_pool.m_opts.dust_relay_feerate);
152
153
0
        Assert(dust_indexes.size() < 2);
154
155
0
        if (dust_indexes.empty()) continue;
  Branch (155:13): [True: 0, False: 0]
156
157
        // Transaction must have no base fee
158
0
        Assert(entry.GetFee() == 0 && entry.GetModifiedFee() == 0);
159
160
        // Transaction has single dust; make sure it's swept or will not be mined
161
0
        const auto& children = tx_pool.GetChildren(entry);
162
163
        // Multiple children should never happen as non-dust-spending child
164
        // can get mined as package
165
0
        Assert(children.size() < 2);
166
167
0
        if (children.empty()) {
  Branch (167:13): [True: 0, False: 0]
168
            // No children and no fees; modified fees aside won't get mined so it's fine
169
            // Happens naturally if child spend is RBF cycled away.
170
0
            continue;
171
0
        }
172
173
        // Only-child should be spending the dust
174
0
        const auto& only_child = children.begin()->get().GetTx();
175
0
        COutPoint dust_outpoint{tx_info.tx->GetHash(), dust_indexes[0]};
176
0
        Assert(std::any_of(only_child.vin.begin(), only_child.vin.end(), [&dust_outpoint](const CTxIn& txin) {
177
0
            return txin.prevout == dust_outpoint;
178
0
            }));
179
0
    }
180
0
}
181
182
void CheckMempoolTRUCInvariants(const CTxMemPool& tx_pool)
183
0
{
184
0
    LOCK(tx_pool.cs);
185
0
    for (const auto& tx_info : tx_pool.infoAll()) {
  Branch (185:30): [True: 0, False: 0]
186
0
        const auto& entry = *Assert(tx_pool.GetEntry(tx_info.tx->GetHash()));
187
0
        auto [desc_count, desc_size, desc_fees] = tx_pool.CalculateDescendantData(entry);
188
0
        auto [anc_count, anc_size, anc_fees] = tx_pool.CalculateAncestorData(entry);
189
190
0
        if (tx_info.tx->version == TRUC_VERSION) {
  Branch (190:13): [True: 0, False: 0]
191
            // Check that special maximum virtual size is respected
192
0
            Assert(entry.GetTxSize() <= TRUC_MAX_VSIZE);
193
194
            // Check that special TRUC ancestor/descendant limits and rules are always respected
195
0
            Assert(desc_count <= TRUC_DESCENDANT_LIMIT);
196
0
            Assert(anc_count <= TRUC_ANCESTOR_LIMIT);
197
0
            Assert(desc_size <= TRUC_MAX_VSIZE + TRUC_CHILD_MAX_VSIZE);
198
0
            Assert(anc_size <= TRUC_MAX_VSIZE + TRUC_CHILD_MAX_VSIZE);
199
            // If this transaction has at least 1 ancestor, it's a "child" and has restricted weight.
200
0
            if (anc_count > 1) {
  Branch (200:17): [True: 0, False: 0]
201
0
                Assert(entry.GetTxSize() <= TRUC_CHILD_MAX_VSIZE);
202
                // All TRUC transactions must only have TRUC unconfirmed parents.
203
0
                const auto& parents = tx_pool.GetParents(entry);
204
0
                Assert(parents.begin()->get().GetSharedTx()->version == TRUC_VERSION);
205
0
            }
206
0
        } else if (anc_count > 1) {
  Branch (206:20): [True: 0, False: 0]
207
            // All non-TRUC transactions must only have non-TRUC unconfirmed parents.
208
0
            for (const auto& parent : tx_pool.GetParents(entry)) {
  Branch (208:37): [True: 0, False: 0]
209
0
                Assert(parent.get().GetSharedTx()->version != TRUC_VERSION);
210
0
            }
211
0
        }
212
0
    }
213
0
}
214
215
void TryAddToMempool(CTxMemPool& tx_pool, const CTxMemPoolEntry& entry)
216
0
{
217
0
    LOCK2(cs_main, tx_pool.cs);
218
0
    auto changeset = tx_pool.GetChangeSet();
219
0
    changeset->StageAddition(entry.GetSharedTx(), entry.GetFee(),
220
0
            entry.GetTime().count(), entry.GetHeight(), entry.GetSequence(),
221
0
            entry.GetSpendsCoinbase(), entry.GetSigOpCost(), entry.GetLockPoints());
222
0
    if (changeset->CheckMemPoolPolicyLimits()) changeset->Apply();
  Branch (222:9): [True: 0, False: 0]
223
0
}
224
225
void MockMempoolMinFee(const CFeeRate& target_feerate, CTxMemPool& mempool)
226
0
{
227
0
    LOCK2(cs_main, mempool.cs);
228
    // Transactions in the mempool will affect the new minimum feerate.
229
0
    assert(mempool.size() == 0);
  Branch (229:5): [True: 0, False: 0]
230
    // The target feerate cannot be too low...
231
    // ...otherwise the transaction's feerate will need to be negative.
232
0
    assert(target_feerate > mempool.m_opts.incremental_relay_feerate);
  Branch (232:5): [True: 0, False: 0]
233
    // ...otherwise this is not meaningful. The feerate policy uses the maximum of both feerates.
234
0
    assert(target_feerate > mempool.m_opts.min_relay_feerate);
  Branch (234:5): [True: 0, False: 0]
235
236
    // Manually create an invalid transaction. Manually set the fee in the CTxMemPoolEntry to
237
    // achieve the exact target feerate.
238
0
    CMutableTransaction mtx{};
239
0
    mtx.vin.emplace_back(COutPoint{Txid::FromUint256(uint256{123}), 0});
240
0
    mtx.vout.emplace_back(1 * COIN, GetScriptForDestination(WitnessV0ScriptHash(CScript() << OP_TRUE)));
241
    // Set a large size so that the fee evaluated at target_feerate (which is usually in sats/kvB) is an integer.
242
    // Otherwise, GetMinFee() may end up slightly different from target_feerate.
243
0
    BulkTransaction(mtx, 4000);
244
0
    const auto tx{MakeTransactionRef(mtx)};
245
0
    LockPoints lp;
246
    // The new mempool min feerate is equal to the removed package's feerate + incremental feerate.
247
0
    const auto tx_fee = target_feerate.GetFee(GetVirtualTransactionSize(*tx)) -
248
0
        mempool.m_opts.incremental_relay_feerate.GetFee(GetVirtualTransactionSize(*tx));
249
0
    {
250
0
        auto changeset = mempool.GetChangeSet();
251
0
        changeset->StageAddition(tx, /*fee=*/tx_fee,
252
0
                /*time=*/0, /*entry_height=*/1, /*entry_sequence=*/0,
253
0
                /*spends_coinbase=*/true, /*sigops_cost=*/1, lp);
254
0
        changeset->Apply();
255
0
    }
256
0
    mempool.TrimToSize(0);
257
    assert(mempool.GetMinFee() == target_feerate);
  Branch (257:5): [True: 0, False: 0]
258
0
}