Bitcoin Core  26.1.0
P2P Digital Currency
tx_pool.cpp
Go to the documentation of this file.
1 // Copyright (c) 2021-2022 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>
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 
22 using node::NodeContext;
23 
24 namespace {
25 
26 const TestingSetup* g_setup;
27 std::vector<COutPoint> g_outpoints_coinbase_init_mature;
28 std::vector<COutPoint> g_outpoints_coinbase_init_immature;
29 
30 struct MockedTxPool : public CTxMemPool {
31  void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
32  {
33  LOCK(cs);
34  lastRollingFeeUpdate = GetTime();
35  blockSinceLastRollingFeeBump = true;
36  }
37 };
38 
39 void initialize_tx_pool()
40 {
41  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
42  g_setup = testing_setup.get();
43 
44  for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
45  COutPoint prevout{MineBlock(g_setup->m_node, P2WSH_OP_TRUE)};
46  // Remember the txids to avoid expensive disk access later on
47  auto& outpoints = i < COINBASE_MATURITY ?
48  g_outpoints_coinbase_init_mature :
49  g_outpoints_coinbase_init_immature;
50  outpoints.push_back(prevout);
51  }
53 }
54 
55 struct TransactionsDelta final : public CValidationInterface {
56  std::set<CTransactionRef>& m_removed;
57  std::set<CTransactionRef>& m_added;
58 
59  explicit TransactionsDelta(std::set<CTransactionRef>& r, std::set<CTransactionRef>& a)
60  : m_removed{r}, m_added{a} {}
61 
62  void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t /* mempool_sequence */) override
63  {
64  Assert(m_added.insert(tx).second);
65  }
66 
67  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
68  {
69  Assert(m_removed.insert(tx).second);
70  }
71 };
72 
73 void SetMempoolConstraints(ArgsManager& args, FuzzedDataProvider& fuzzed_data_provider)
74 {
75  args.ForceSetArg("-limitancestorcount",
76  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
77  args.ForceSetArg("-limitancestorsize",
78  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
79  args.ForceSetArg("-limitdescendantcount",
80  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50)));
81  args.ForceSetArg("-limitdescendantsize",
82  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202)));
83  args.ForceSetArg("-maxmempool",
84  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200)));
85  args.ForceSetArg("-mempoolexpiry",
86  ToString(fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)));
87 }
88 
89 void Finish(FuzzedDataProvider& fuzzed_data_provider, MockedTxPool& tx_pool, Chainstate& chainstate)
90 {
91  WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
92  {
93  BlockAssembler::Options options;
94  options.nBlockMaxWeight = fuzzed_data_provider.ConsumeIntegralInRange(0U, MAX_BLOCK_WEIGHT);
95  options.blockMinFeeRate = CFeeRate{ConsumeMoney(fuzzed_data_provider, /*max=*/COIN)};
96  auto assembler = BlockAssembler{chainstate, &tx_pool, options};
97  auto block_template = assembler.CreateNewBlock(CScript{} << OP_TRUE);
98  Assert(block_template->block.vtx.size() >= 1);
99  }
100  const auto info_all = tx_pool.infoAll();
101  if (!info_all.empty()) {
102  const auto& tx_to_remove = *PickValue(fuzzed_data_provider, info_all).tx;
103  WITH_LOCK(tx_pool.cs, tx_pool.removeRecursive(tx_to_remove, MemPoolRemovalReason::BLOCK /* dummy */));
104  std::vector<uint256> all_txids;
105  tx_pool.queryHashes(all_txids);
106  assert(all_txids.size() < info_all.size());
107  WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
108  }
110 }
111 
112 void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
113 {
114  const auto time = ConsumeTime(fuzzed_data_provider,
115  chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
116  std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
117  SetMockTime(time);
118 }
119 
120 CTxMemPool MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
121 {
122  // Take the default options for tests...
124 
125  // ...override specific options for this specific fuzz suite
126  mempool_opts.estimator = nullptr;
127  mempool_opts.check_ratio = 1;
128  mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
129 
130  // ...and construct a CTxMemPool from it
131  return CTxMemPool{mempool_opts};
132 }
133 
134 FUZZ_TARGET(tx_pool_standard, .init = initialize_tx_pool)
135 {
136  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
137  const auto& node = g_setup->m_node;
138  auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
139 
140  MockTime(fuzzed_data_provider, chainstate);
141 
142  // All RBF-spendable outpoints
143  std::set<COutPoint> outpoints_rbf;
144  // All outpoints counting toward the total supply (subset of outpoints_rbf)
145  std::set<COutPoint> outpoints_supply;
146  for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
147  Assert(outpoints_supply.insert(outpoint).second);
148  }
149  outpoints_rbf = outpoints_supply;
150 
151  // The sum of the values of all spendable outpoints
152  constexpr CAmount SUPPLY_TOTAL{COINBASE_MATURITY * 50 * COIN};
153 
154  SetMempoolConstraints(*node.args, fuzzed_data_provider);
155  CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
156  MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
157 
158  chainstate.SetMempool(&tx_pool);
159 
160  // Helper to query an amount
161  const CCoinsViewMemPool amount_view{WITH_LOCK(::cs_main, return &chainstate.CoinsTip()), tx_pool};
162  const auto GetAmount = [&](const COutPoint& outpoint) {
163  Coin c;
164  Assert(amount_view.GetCoin(outpoint, c));
165  return c.out.nValue;
166  };
167 
168  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
169  {
170  {
171  // Total supply is the mempool fee + all outpoints
172  CAmount supply_now{WITH_LOCK(tx_pool.cs, return tx_pool.GetTotalFee())};
173  for (const auto& op : outpoints_supply) {
174  supply_now += GetAmount(op);
175  }
176  Assert(supply_now == SUPPLY_TOTAL);
177  }
178  Assert(!outpoints_supply.empty());
179 
180  // Create transaction to add to the mempool
181  const CTransactionRef tx = [&] {
182  CMutableTransaction tx_mut;
184  tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
185  const auto num_in = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size());
186  const auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, outpoints_rbf.size() * 2);
187 
188  CAmount amount_in{0};
189  for (int i = 0; i < num_in; ++i) {
190  // Pop random outpoint
191  auto pop = outpoints_rbf.begin();
192  std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints_rbf.size() - 1));
193  const auto outpoint = *pop;
194  outpoints_rbf.erase(pop);
195  amount_in += GetAmount(outpoint);
196 
197  // Create input
198  const auto sequence = ConsumeSequence(fuzzed_data_provider);
199  const auto script_sig = CScript{};
200  const auto script_wit_stack = std::vector<std::vector<uint8_t>>{WITNESS_STACK_ELEM_OP_TRUE};
201  CTxIn in;
202  in.prevout = outpoint;
203  in.nSequence = sequence;
204  in.scriptSig = script_sig;
205  in.scriptWitness.stack = script_wit_stack;
206 
207  tx_mut.vin.push_back(in);
208  }
209  const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1000, amount_in);
210  const auto amount_out = (amount_in - amount_fee) / num_out;
211  for (int i = 0; i < num_out; ++i) {
212  tx_mut.vout.emplace_back(amount_out, P2WSH_OP_TRUE);
213  }
214  auto tx = MakeTransactionRef(tx_mut);
215  // Restore previously removed outpoints
216  for (const auto& in : tx->vin) {
217  Assert(outpoints_rbf.insert(in.prevout).second);
218  }
219  return tx;
220  }();
221 
222  if (fuzzed_data_provider.ConsumeBool()) {
223  MockTime(fuzzed_data_provider, chainstate);
224  }
225  if (fuzzed_data_provider.ConsumeBool()) {
226  tx_pool.RollingFeeUpdate();
227  }
228  if (fuzzed_data_provider.ConsumeBool()) {
229  const auto& txid = fuzzed_data_provider.ConsumeBool() ?
230  tx->GetHash() :
231  PickValue(fuzzed_data_provider, outpoints_rbf).hash;
232  const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
233  tx_pool.PrioritiseTransaction(txid, delta);
234  }
235 
236  // Remember all removed and added transactions
237  std::set<CTransactionRef> removed;
238  std::set<CTransactionRef> added;
239  auto txr = std::make_shared<TransactionsDelta>(removed, added);
241  const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
242 
243  // Make sure ProcessNewPackage on one transaction works.
244  // The result is not guaranteed to be the same as what is returned by ATMP.
245  const auto result_package = WITH_LOCK(::cs_main,
246  return ProcessNewPackage(chainstate, tx_pool, {tx}, true));
247  // If something went wrong due to a package-specific policy, it might not return a
248  // validation result for the transaction.
249  if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
250  auto it = result_package.m_tx_results.find(tx->GetWitnessHash());
251  Assert(it != result_package.m_tx_results.end());
252  Assert(it->second.m_result_type == MempoolAcceptResult::ResultType::VALID ||
253  it->second.m_result_type == MempoolAcceptResult::ResultType::INVALID);
254  }
255 
256  const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), bypass_limits, /*test_accept=*/false));
257  const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
260 
261  Assert(accepted != added.empty());
262  Assert(accepted == res.m_state.IsValid());
263  Assert(accepted != res.m_state.IsInvalid());
264  if (accepted) {
265  Assert(added.size() == 1); // For now, no package acceptance
266  Assert(tx == *added.begin());
267  } else {
268  // Do not consider rejected transaction removed
269  removed.erase(tx);
270  }
271 
272  // Helper to insert spent and created outpoints of a tx into collections
273  using Sets = std::vector<std::reference_wrapper<std::set<COutPoint>>>;
274  const auto insert_tx = [](Sets created_by_tx, Sets consumed_by_tx, const auto& tx) {
275  for (size_t i{0}; i < tx.vout.size(); ++i) {
276  for (auto& set : created_by_tx) {
277  Assert(set.get().emplace(tx.GetHash(), i).second);
278  }
279  }
280  for (const auto& in : tx.vin) {
281  for (auto& set : consumed_by_tx) {
282  Assert(set.get().insert(in.prevout).second);
283  }
284  }
285  };
286  // Add created outpoints, remove spent outpoints
287  {
288  // Outpoints that no longer exist at all
289  std::set<COutPoint> consumed_erased;
290  // Outpoints that no longer count toward the total supply
291  std::set<COutPoint> consumed_supply;
292  for (const auto& removed_tx : removed) {
293  insert_tx(/*created_by_tx=*/{consumed_erased}, /*consumed_by_tx=*/{outpoints_supply}, /*tx=*/*removed_tx);
294  }
295  for (const auto& added_tx : added) {
296  insert_tx(/*created_by_tx=*/{outpoints_supply, outpoints_rbf}, /*consumed_by_tx=*/{consumed_supply}, /*tx=*/*added_tx);
297  }
298  for (const auto& p : consumed_erased) {
299  Assert(outpoints_supply.erase(p) == 1);
300  Assert(outpoints_rbf.erase(p) == 1);
301  }
302  for (const auto& p : consumed_supply) {
303  Assert(outpoints_supply.erase(p) == 1);
304  }
305  }
306  }
307  Finish(fuzzed_data_provider, tx_pool, chainstate);
308 }
309 
310 FUZZ_TARGET(tx_pool, .init = initialize_tx_pool)
311 {
312  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
313  const auto& node = g_setup->m_node;
314  auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
315 
316  MockTime(fuzzed_data_provider, chainstate);
317 
318  std::vector<uint256> txids;
319  txids.reserve(g_outpoints_coinbase_init_mature.size());
320  for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
321  txids.push_back(outpoint.hash);
322  }
323  for (int i{0}; i <= 3; ++i) {
324  // Add some immature and non-existent outpoints
325  txids.push_back(g_outpoints_coinbase_init_immature.at(i).hash);
326  txids.push_back(ConsumeUInt256(fuzzed_data_provider));
327  }
328 
329  SetMempoolConstraints(*node.args, fuzzed_data_provider);
330  CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
331  MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
332 
333  chainstate.SetMempool(&tx_pool);
334 
335  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
336  {
337  const auto mut_tx = ConsumeTransaction(fuzzed_data_provider, txids);
338 
339  if (fuzzed_data_provider.ConsumeBool()) {
340  MockTime(fuzzed_data_provider, chainstate);
341  }
342  if (fuzzed_data_provider.ConsumeBool()) {
343  tx_pool.RollingFeeUpdate();
344  }
345  if (fuzzed_data_provider.ConsumeBool()) {
346  const auto& txid = fuzzed_data_provider.ConsumeBool() ?
347  mut_tx.GetHash() :
348  PickValue(fuzzed_data_provider, txids);
349  const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
350  tx_pool.PrioritiseTransaction(txid, delta);
351  }
352 
353  const auto tx = MakeTransactionRef(mut_tx);
354  const bool bypass_limits = fuzzed_data_provider.ConsumeBool();
355  const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, tx, GetTime(), bypass_limits, /*test_accept=*/false));
356  const bool accepted = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
357  if (accepted) {
358  txids.push_back(tx->GetHash());
359  }
360  }
361  Finish(fuzzed_data_provider, tx_pool, chainstate);
362 }
363 } // namespace
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:575
CAmount nValue
Definition: transaction.h:160
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
assert(!tx.IsCoinBase())
Generate a new block, without valid proof-of-work.
Definition: miner.h:134
The package itself is invalid (e.g. too many transactions).
A UTXO entry.
Definition: coins.h:31
static void pool cs
std::vector< CTxIn > vin
Definition: transaction.h:381
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:80
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal...
int Height() const
Return the maximal height in the chain.
Definition: chain.h:487
CTxOut out
unspent transaction output
Definition: coins.h:35
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule) ...
Definition: consensus.h:19
std::vector< std::vector< unsigned char > > stack
Definition: script.h:568
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Definition: insert.h:14
uint32_t nTime
Definition: chain.h:199
void RegisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Register subscriber.
void ForceSetArg(const std::string &strArg, const std::string &strValue)
Definition: args.cpp:545
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:550
void UnregisterSharedValidationInterface(std::shared_ptr< CValidationInterface > callbacks)
Unregister subscriber.
Implement this to subscribe to events generated in validation.
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
MempoolAcceptResult AcceptToMemoryPool(Chainstate &active_chainstate, const CTransactionRef &tx, int64_t accept_time, bool bypass_limits, bool test_accept) EXCLUSIVE_LOCKS_REQUIRED(
Try to add a transaction to the mempool.
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:81
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:109
NodeContext struct containing references to chain state and connection state.
Definition: context.h:48
Definition: script.h:82
ArgsManager & args
Definition: bitcoind.cpp:269
Chainstate stores and provides an API to update our local knowledge of the current best chain...
Definition: validation.h:469
An input of a transaction.
Definition: transaction.h:74
#define LOCK(cs)
Definition: sync.h:258
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
Definition: script.h:11
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept)
Validate (and maybe submit) a package to the mempool.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:35
std::vector< CTxOut > vout
Definition: transaction.h:382
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:302
int64_t GetMedianTimePast() const
Definition: chain.h:289
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:422
COutPoint MineBlock(const NodeContext &node, const CScript &coinbase_scriptPubKey)
Returns the generated coin.
Definition: mining.cpp:63
Definition: init.h:25
CScript scriptSig
Definition: transaction.h:78
CBlockPolicyEstimator * estimator
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:35
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:301
Removed for block.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
uint32_t nSequence
Definition: transaction.h:79
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:30
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:458
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
A mutable version of CTransaction.
Definition: transaction.h:379
uint64_t sequence
CMutableTransaction ConsumeTransaction(FuzzedDataProvider &fuzzed_data_provider, const std::optional< std::vector< uint256 >> &prevout_txids, const int max_num_in, const int max_num_out) noexcept
Definition: util.cpp:43
Options struct containing options for constructing a CTxMemPool.
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:48
static const int32_t CURRENT_VERSION
Definition: transaction.h:298
T ConsumeIntegralInRange(T min, T max)
#define FUZZ_TARGET(...)
Definition: fuzz.h:34
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:170
int64_t GetTime()
DEPRECATED, see GetTime.
Definition: time.cpp:97
COutPoint prevout
Definition: transaction.h:77
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate...
Definition: cs_main.cpp:8
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:823
Testing setup that configures a complete environment.
Definition: setup_common.h:77
#define Assert(val)
Identity function.
Definition: check.h:73
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:156
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:17
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15