|
| 1 | +// Copyright (c) 2023 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 <consensus/validation.h> |
| 6 | +#include <node/context.h> |
| 7 | +#include <node/mempool_args.h> |
| 8 | +#include <node/miner.h> |
| 9 | +#include <test/fuzz/FuzzedDataProvider.h> |
| 10 | +#include <test/fuzz/fuzz.h> |
| 11 | +#include <test/fuzz/util.h> |
| 12 | +#include <test/fuzz/util/mempool.h> |
| 13 | +#include <test/util/mining.h> |
| 14 | +#include <test/util/script.h> |
| 15 | +#include <test/util/setup_common.h> |
| 16 | +#include <test/util/txmempool.h> |
| 17 | +#include <util/rbf.h> |
| 18 | +#include <validation.h> |
| 19 | +#include <validationinterface.h> |
| 20 | + |
| 21 | +using node::NodeContext; |
| 22 | + |
| 23 | +namespace { |
| 24 | + |
| 25 | +const TestingSetup* g_setup; |
| 26 | +std::vector<COutPoint> g_outpoints_coinbase_init_mature; |
| 27 | + |
| 28 | +struct MockedTxPool : public CTxMemPool { |
| 29 | + void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs) |
| 30 | + { |
| 31 | + LOCK(cs); |
| 32 | + lastRollingFeeUpdate = GetTime(); |
| 33 | + blockSinceLastRollingFeeBump = true; |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +void initialize_tx_pool() |
| 38 | +{ |
| 39 | + static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>(); |
| 40 | + g_setup = testing_setup.get(); |
| 41 | + |
| 42 | + for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) { |
| 43 | + COutPoint prevout{MineBlock(g_setup->m_node, P2WSH_OP_TRUE)}; |
| 44 | + if (i < COINBASE_MATURITY) { |
| 45 | + // Remember the txids to avoid expensive disk access later on |
| 46 | + g_outpoints_coinbase_init_mature.push_back(prevout); |
| 47 | + } |
| 48 | + } |
| 49 | + SyncWithValidationInterfaceQueue(); |
| 50 | +} |
| 51 | + |
| 52 | +struct OutpointsUpdater final : public CValidationInterface { |
| 53 | + std::set<COutPoint>& m_mempool_outpoints; |
| 54 | + |
| 55 | + explicit OutpointsUpdater(std::set<COutPoint>& r) |
| 56 | + : m_mempool_outpoints{r} {} |
| 57 | + |
| 58 | + void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override |
| 59 | + { |
| 60 | + // for coins spent we always want to be able to rbf so they're not removed |
| 61 | + |
| 62 | + // outputs from this tx can now be spent |
| 63 | + for (uint32_t index{0}; index < tx->vout.size(); ++index) { |
| 64 | + m_mempool_outpoints.insert(COutPoint{tx->GetHash(), index}); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override |
| 69 | + { |
| 70 | + // outpoints spent by this tx are now available |
| 71 | + for (const auto& input : tx->vin) { |
| 72 | + // Could already exist if this was a replacement |
| 73 | + m_mempool_outpoints.insert(input.prevout); |
| 74 | + } |
| 75 | + // outpoints created by this tx no longer exist |
| 76 | + for (uint32_t index{0}; index < tx->vout.size(); ++index) { |
| 77 | + m_mempool_outpoints.erase(COutPoint{tx->GetHash(), index}); |
| 78 | + } |
| 79 | + } |
| 80 | +}; |
| 81 | + |
| 82 | +struct TransactionsDelta final : public CValidationInterface { |
| 83 | + std::set<CTransactionRef>& m_added; |
| 84 | + |
| 85 | + explicit TransactionsDelta(std::set<CTransactionRef>& a) |
| 86 | + : m_added{a} {} |
| 87 | + |
| 88 | + void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override |
| 89 | + { |
| 90 | + // Transactions may be entered and booted any number of times |
| 91 | + m_added.insert(tx); |
| 92 | + } |
| 93 | + |
| 94 | + void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override |
| 95 | + { |
| 96 | + // Transactions may be entered and booted any number of times |
| 97 | + m_added.erase(tx); |
| 98 | + } |
| 99 | +}; |
| 100 | + |
| 101 | +void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate) |
| 102 | +{ |
| 103 | + const auto time = ConsumeTime(fuzzed_data_provider, |
| 104 | + chainstate.m_chain.Tip()->GetMedianTimePast() + 1, |
| 105 | + std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max()); |
| 106 | + SetMockTime(time); |
| 107 | +} |
| 108 | + |
| 109 | +CTxMemPool MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node) |
| 110 | +{ |
| 111 | + // Take the default options for tests... |
| 112 | + CTxMemPool::Options mempool_opts{MemPoolOptionsForTest(node)}; |
| 113 | + |
| 114 | + |
| 115 | + // ...override specific options for this specific fuzz suite |
| 116 | + mempool_opts.limits.ancestor_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50); |
| 117 | + mempool_opts.limits.ancestor_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000; |
| 118 | + mempool_opts.limits.descendant_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50); |
| 119 | + mempool_opts.limits.descendant_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000; |
| 120 | + mempool_opts.max_size_bytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200) * 1'000'000; |
| 121 | + mempool_opts.expiry = std::chrono::hours{fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)}; |
| 122 | + nBytesPerSigOp = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(1, 999); |
| 123 | + |
| 124 | + mempool_opts.estimator = nullptr; |
| 125 | + mempool_opts.check_ratio = 1; |
| 126 | + mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool(); |
| 127 | + |
| 128 | + // ...and construct a CTxMemPool from it |
| 129 | + return CTxMemPool{mempool_opts}; |
| 130 | +} |
| 131 | + |
| 132 | +FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool) |
| 133 | +{ |
| 134 | + FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); |
| 135 | + const auto& node = g_setup->m_node; |
| 136 | + auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())}; |
| 137 | + |
| 138 | + MockTime(fuzzed_data_provider, chainstate); |
| 139 | + |
| 140 | + // All RBF-spendable outpoints outside of the unsubmitted package |
| 141 | + std::set<COutPoint> mempool_outpoints; |
| 142 | + std::map<COutPoint, CAmount> outpoints_value; |
| 143 | + for (const auto& outpoint : g_outpoints_coinbase_init_mature) { |
| 144 | + Assert(mempool_outpoints.insert(outpoint).second); |
| 145 | + outpoints_value[outpoint] = 50 * COIN; |
| 146 | + } |
| 147 | + |
| 148 | + auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints); |
| 149 | + RegisterSharedValidationInterface(outpoints_updater); |
| 150 | + |
| 151 | + CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)}; |
| 152 | + MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_); |
| 153 | + |
| 154 | + chainstate.SetMempool(&tx_pool); |
| 155 | + |
| 156 | + LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300) |
| 157 | + { |
| 158 | + Assert(!mempool_outpoints.empty()); |
| 159 | + |
| 160 | + std::vector<CTransactionRef> txs; |
| 161 | + |
| 162 | + // Make packages of 1-to-26 transactions |
| 163 | + const auto num_txs = (size_t) fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 26); |
| 164 | + std::set<COutPoint> package_outpoints; |
| 165 | + while (txs.size() < num_txs) { |
| 166 | + |
| 167 | + // Last transaction in a package needs to be a child of parents to get further in validation |
| 168 | + // so the last transaction to be generated(in a >1 package) must spend all package-made outputs |
| 169 | + // Note that this test currently only spends package outputs in last transaction. |
| 170 | + bool last_tx = num_txs > 1 && txs.size() == num_txs - 1; |
| 171 | + |
| 172 | + // Create transaction to add to the mempool |
| 173 | + const CTransactionRef tx = [&] { |
| 174 | + CMutableTransaction tx_mut; |
| 175 | + tx_mut.nVersion = CTransaction::CURRENT_VERSION; |
| 176 | + tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>(); |
| 177 | + // Last tx will sweep all outpoints in package |
| 178 | + const auto num_in = last_tx ? package_outpoints.size() : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size()); |
| 179 | + const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2); |
| 180 | + |
| 181 | + auto& outpoints = last_tx ? package_outpoints : mempool_outpoints; |
| 182 | + |
| 183 | + Assert(!outpoints.empty()); |
| 184 | + |
| 185 | + CAmount amount_in{0}; |
| 186 | + for (size_t i = 0; i < num_in; ++i) { |
| 187 | + // Pop random outpoint |
| 188 | + auto pop = outpoints.begin(); |
| 189 | + std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1)); |
| 190 | + const auto outpoint = *pop; |
| 191 | + outpoints.erase(pop); |
| 192 | + // no need to update or erase from outpoints_value |
| 193 | + amount_in += outpoints_value.at(outpoint); |
| 194 | + |
| 195 | + // Create input |
| 196 | + const auto sequence = ConsumeSequence(fuzzed_data_provider); |
| 197 | + const auto script_sig = CScript{}; |
| 198 | + const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE}; |
| 199 | + CTxIn in; |
| 200 | + in.prevout = outpoint; |
| 201 | + in.nSequence = sequence; |
| 202 | + in.scriptSig = script_sig; |
| 203 | + in.scriptWitness.stack = script_wit_stack; |
| 204 | + |
| 205 | + tx_mut.vin.push_back(in); |
| 206 | + } |
| 207 | + const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in); |
| 208 | + const auto amount_out = (amount_in - amount_fee) / num_out; |
| 209 | + for (int i = 0; i < num_out; ++i) { |
| 210 | + tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE); |
| 211 | + } |
| 212 | + // TODO vary transaction sizes to catch size-related issues |
| 213 | + auto tx = MakeTransactionRef(tx_mut); |
| 214 | + // Restore previously removed outpoints, except in-package outpoints |
| 215 | + if (!last_tx) { |
| 216 | + for (const auto& in : tx->vin) { |
| 217 | + Assert(outpoints.insert(in.prevout).second); |
| 218 | + } |
| 219 | + // Cache the in-package outpoints being made |
| 220 | + for (size_t i = 0; i < tx->vout.size(); ++i) { |
| 221 | + package_outpoints.emplace(tx->GetHash(), i); |
| 222 | + } |
| 223 | + } |
| 224 | + // We need newly-created values for the duration of this run |
| 225 | + for (size_t i = 0; i < tx->vout.size(); ++i) { |
| 226 | + outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue; |
| 227 | + } |
| 228 | + return tx; |
| 229 | + }(); |
| 230 | + txs.push_back(tx); |
| 231 | + } |
| 232 | + |
| 233 | + if (fuzzed_data_provider.ConsumeBool()) { |
| 234 | + MockTime(fuzzed_data_provider, chainstate); |
| 235 | + } |
| 236 | + if (fuzzed_data_provider.ConsumeBool()) { |
| 237 | + tx_pool.RollingFeeUpdate(); |
| 238 | + } |
| 239 | + if (fuzzed_data_provider.ConsumeBool()) { |
| 240 | + const auto& txid = fuzzed_data_provider.ConsumeBool() ? |
| 241 | + txs.back()->GetHash() : |
| 242 | + PickValue(fuzzed_data_provider, mempool_outpoints).hash; |
| 243 | + const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN); |
| 244 | + tx_pool.PrioritiseTransaction(txid, delta); |
| 245 | + } |
| 246 | + |
| 247 | + // Remember all added transactions |
| 248 | + std::set<CTransactionRef> added; |
| 249 | + auto txr = std::make_shared<TransactionsDelta>(added); |
| 250 | + RegisterSharedValidationInterface(txr); |
| 251 | + const bool bypass_limits = fuzzed_data_provider.ConsumeBool(); |
| 252 | + |
| 253 | + // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false) |
| 254 | + // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it |
| 255 | + // (the package is a test accept and ATMP is a submission). |
| 256 | + auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool(); |
| 257 | + |
| 258 | + const auto result_package = WITH_LOCK(::cs_main, |
| 259 | + return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit)); |
| 260 | + // If something went wrong due to a package-specific policy, it might not return a |
| 261 | + // validation result for the transaction. |
| 262 | + if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) { |
| 263 | + auto it = result_package.m_tx_results.find(txs.back()->GetWitnessHash()); |
| 264 | + Assert(it != result_package.m_tx_results.end()); |
| 265 | + Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID || |
| 266 | + it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID || |
| 267 | + it->second.m_result_type == MempoolAcceptResult::ResultType::MEMPOOL_ENTRY); |
| 268 | + } |
| 269 | + |
| 270 | + const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(), bypass_limits, /*test_accept=*/!single_submit)); |
| 271 | + const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID; |
| 272 | + |
| 273 | + SyncWithValidationInterfaceQueue(); |
| 274 | + UnregisterSharedValidationInterface(txr); |
| 275 | + |
| 276 | + // There is only 1 transaction in the package. We did a test-package-accept and a ATMP |
| 277 | + if (single_submit) { |
| 278 | + Assert(accepted != added.empty()); |
| 279 | + Assert(accepted == res.m_state.IsValid()); |
| 280 | + if (accepted) { |
| 281 | + Assert(added.size() == 1); |
| 282 | + Assert(txs.back() == *added.begin()); |
| 283 | + } |
| 284 | + } else { |
| 285 | + // This is empty if it fails early checks, or "full" if transactions are looked at deeper |
| 286 | + Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty()); |
| 287 | + } |
| 288 | + } |
| 289 | + |
| 290 | + UnregisterSharedValidationInterface(outpoints_updater); |
| 291 | + |
| 292 | + WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1)); |
| 293 | +} |
| 294 | +} // namespace |
0 commit comments