Bitcoin Core  27.99.0
P2P Digital Currency
package_eval.cpp
Go to the documentation of this file.
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 <policy/v3_policy.h>
11 #include <test/fuzz/fuzz.h>
12 #include <test/fuzz/util.h>
13 #include <test/fuzz/util/mempool.h>
14 #include <test/util/mining.h>
15 #include <test/util/script.h>
16 #include <test/util/setup_common.h>
17 #include <test/util/txmempool.h>
18 #include <util/rbf.h>
19 #include <validation.h>
20 #include <validationinterface.h>
21 
22 using node::NodeContext;
23 
24 namespace {
25 
26 const TestingSetup* g_setup;
27 std::vector<COutPoint> g_outpoints_coinbase_init_mature;
28 
29 struct MockedTxPool : public CTxMemPool {
30  void RollingFeeUpdate() EXCLUSIVE_LOCKS_REQUIRED(!cs)
31  {
32  LOCK(cs);
33  lastRollingFeeUpdate = GetTime();
34  blockSinceLastRollingFeeBump = true;
35  }
36 };
37 
38 void initialize_tx_pool()
39 {
40  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
41  g_setup = testing_setup.get();
42 
43  for (int i = 0; i < 2 * COINBASE_MATURITY; ++i) {
44  COutPoint prevout{MineBlock(g_setup->m_node, P2WSH_EMPTY)};
45  if (i < COINBASE_MATURITY) {
46  // Remember the txids to avoid expensive disk access later on
47  g_outpoints_coinbase_init_mature.push_back(prevout);
48  }
49  }
50  g_setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
51 }
52 
53 struct OutpointsUpdater final : public CValidationInterface {
54  std::set<COutPoint>& m_mempool_outpoints;
55 
56  explicit OutpointsUpdater(std::set<COutPoint>& r)
57  : m_mempool_outpoints{r} {}
58 
59  void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
60  {
61  // for coins spent we always want to be able to rbf so they're not removed
62 
63  // outputs from this tx can now be spent
64  for (uint32_t index{0}; index < tx.info.m_tx->vout.size(); ++index) {
65  m_mempool_outpoints.insert(COutPoint{tx.info.m_tx->GetHash(), index});
66  }
67  }
68 
69  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
70  {
71  // outpoints spent by this tx are now available
72  for (const auto& input : tx->vin) {
73  // Could already exist if this was a replacement
74  m_mempool_outpoints.insert(input.prevout);
75  }
76  // outpoints created by this tx no longer exist
77  for (uint32_t index{0}; index < tx->vout.size(); ++index) {
78  m_mempool_outpoints.erase(COutPoint{tx->GetHash(), index});
79  }
80  }
81 };
82 
83 struct TransactionsDelta final : public CValidationInterface {
84  std::set<CTransactionRef>& m_added;
85 
86  explicit TransactionsDelta(std::set<CTransactionRef>& a)
87  : m_added{a} {}
88 
89  void TransactionAddedToMempool(const NewMempoolTransactionInfo& tx, uint64_t /* mempool_sequence */) override
90  {
91  // Transactions may be entered and booted any number of times
92  m_added.insert(tx.info.m_tx);
93  }
94 
95  void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t /* mempool_sequence */) override
96  {
97  // Transactions may be entered and booted any number of times
98  m_added.erase(tx);
99  }
100 };
101 
102 void MockTime(FuzzedDataProvider& fuzzed_data_provider, const Chainstate& chainstate)
103 {
104  const auto time = ConsumeTime(fuzzed_data_provider,
105  chainstate.m_chain.Tip()->GetMedianTimePast() + 1,
106  std::numeric_limits<decltype(chainstate.m_chain.Tip()->nTime)>::max());
107  SetMockTime(time);
108 }
109 
110 CTxMemPool MakeMempool(FuzzedDataProvider& fuzzed_data_provider, const NodeContext& node)
111 {
112  // Take the default options for tests...
114 
115 
116  // ...override specific options for this specific fuzz suite
117  mempool_opts.limits.ancestor_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
118  mempool_opts.limits.ancestor_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
119  mempool_opts.limits.descendant_count = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 50);
120  mempool_opts.limits.descendant_size_vbytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 202) * 1'000;
121  mempool_opts.max_size_bytes = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 200) * 1'000'000;
122  mempool_opts.expiry = std::chrono::hours{fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 999)};
123  // Only interested in 2 cases: sigop cost 0 or when single legacy sigop cost is >> 1KvB
124  nBytesPerSigOp = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, 1) * 10'000;
125 
126  mempool_opts.check_ratio = 1;
127  mempool_opts.require_standard = fuzzed_data_provider.ConsumeBool();
128 
129  // ...and construct a CTxMemPool from it
130  return CTxMemPool{mempool_opts};
131 }
132 
133 FUZZ_TARGET(tx_package_eval, .init = initialize_tx_pool)
134 {
135  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
136  const auto& node = g_setup->m_node;
137  auto& chainstate{static_cast<DummyChainState&>(node.chainman->ActiveChainstate())};
138 
139  MockTime(fuzzed_data_provider, chainstate);
140 
141  // All RBF-spendable outpoints outside of the unsubmitted package
142  std::set<COutPoint> mempool_outpoints;
143  std::map<COutPoint, CAmount> outpoints_value;
144  for (const auto& outpoint : g_outpoints_coinbase_init_mature) {
145  Assert(mempool_outpoints.insert(outpoint).second);
146  outpoints_value[outpoint] = 50 * COIN;
147  }
148 
149  auto outpoints_updater = std::make_shared<OutpointsUpdater>(mempool_outpoints);
150  node.validation_signals->RegisterSharedValidationInterface(outpoints_updater);
151 
152  CTxMemPool tx_pool_{MakeMempool(fuzzed_data_provider, node)};
153  MockedTxPool& tx_pool = *static_cast<MockedTxPool*>(&tx_pool_);
154 
155  chainstate.SetMempool(&tx_pool);
156 
157  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 300)
158  {
159  Assert(!mempool_outpoints.empty());
160 
161  std::vector<CTransactionRef> txs;
162 
163  // Make packages of 1-to-26 transactions
164  const auto num_txs = (size_t) fuzzed_data_provider.ConsumeIntegralInRange<int>(1, 26);
165  std::set<COutPoint> package_outpoints;
166  while (txs.size() < num_txs) {
167 
168  // Last transaction in a package needs to be a child of parents to get further in validation
169  // so the last transaction to be generated(in a >1 package) must spend all package-made outputs
170  // Note that this test currently only spends package outputs in last transaction.
171  bool last_tx = num_txs > 1 && txs.size() == num_txs - 1;
172 
173  // Create transaction to add to the mempool
174  const CTransactionRef tx = [&] {
175  CMutableTransaction tx_mut;
176  tx_mut.nVersion = fuzzed_data_provider.ConsumeBool() ? 3 : CTransaction::CURRENT_VERSION;
177  tx_mut.nLockTime = fuzzed_data_provider.ConsumeBool() ? 0 : fuzzed_data_provider.ConsumeIntegral<uint32_t>();
178  // Last tx will sweep all outpoints in package
179  const auto num_in = last_tx ? package_outpoints.size() : fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size());
180  auto num_out = fuzzed_data_provider.ConsumeIntegralInRange<int>(1, mempool_outpoints.size() * 2);
181 
182  auto& outpoints = last_tx ? package_outpoints : mempool_outpoints;
183 
184  Assert(!outpoints.empty());
185 
186  CAmount amount_in{0};
187  for (size_t i = 0; i < num_in; ++i) {
188  // Pop random outpoint
189  auto pop = outpoints.begin();
190  std::advance(pop, fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, outpoints.size() - 1));
191  const auto outpoint = *pop;
192  outpoints.erase(pop);
193  // no need to update or erase from outpoints_value
194  amount_in += outpoints_value.at(outpoint);
195 
196  // Create input
197  const auto sequence = ConsumeSequence(fuzzed_data_provider);
198  const auto script_sig = CScript{};
199  const auto script_wit_stack = fuzzed_data_provider.ConsumeBool() ? P2WSH_EMPTY_TRUE_STACK : P2WSH_EMPTY_TWO_STACK;
200 
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 
210  // Duplicate an input
211  bool dup_input = fuzzed_data_provider.ConsumeBool();
212  if (dup_input) {
213  tx_mut.vin.push_back(tx_mut.vin.back());
214  }
215 
216  // Refer to a non-existent input
217  if (fuzzed_data_provider.ConsumeBool()) {
218  tx_mut.vin.emplace_back();
219  }
220 
221  // Make a p2pk output to make sigops adjusted vsize to violate v3, potentially, which is never spent
222  if (last_tx && amount_in > 1000 && fuzzed_data_provider.ConsumeBool()) {
223  tx_mut.vout.emplace_back(1000, CScript() << std::vector<unsigned char>(33, 0x02) << OP_CHECKSIG);
224  // Don't add any other outputs.
225  num_out = 1;
226  amount_in -= 1000;
227  }
228 
229  const auto amount_fee = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(0, amount_in);
230  const auto amount_out = (amount_in - amount_fee) / num_out;
231  for (int i = 0; i < num_out; ++i) {
232  tx_mut.vout.emplace_back(amount_out, P2WSH_EMPTY);
233  }
234  auto tx = MakeTransactionRef(tx_mut);
235  // Restore previously removed outpoints, except in-package outpoints
236  if (!last_tx) {
237  for (const auto& in : tx->vin) {
238  // It's a fake input, or a new input, or a duplicate
239  Assert(in == CTxIn() || outpoints.insert(in.prevout).second || dup_input);
240  }
241  // Cache the in-package outpoints being made
242  for (size_t i = 0; i < tx->vout.size(); ++i) {
243  package_outpoints.emplace(tx->GetHash(), i);
244  }
245  }
246  // We need newly-created values for the duration of this run
247  for (size_t i = 0; i < tx->vout.size(); ++i) {
248  outpoints_value[COutPoint(tx->GetHash(), i)] = tx->vout[i].nValue;
249  }
250  return tx;
251  }();
252  txs.push_back(tx);
253  }
254 
255  if (fuzzed_data_provider.ConsumeBool()) {
256  MockTime(fuzzed_data_provider, chainstate);
257  }
258  if (fuzzed_data_provider.ConsumeBool()) {
259  tx_pool.RollingFeeUpdate();
260  }
261  if (fuzzed_data_provider.ConsumeBool()) {
262  const auto& txid = fuzzed_data_provider.ConsumeBool() ?
263  txs.back()->GetHash() :
264  PickValue(fuzzed_data_provider, mempool_outpoints).hash;
265  const auto delta = fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-50 * COIN, +50 * COIN);
266  tx_pool.PrioritiseTransaction(txid.ToUint256(), delta);
267  }
268 
269  // Remember all added transactions
270  std::set<CTransactionRef> added;
271  auto txr = std::make_shared<TransactionsDelta>(added);
272  node.validation_signals->RegisterSharedValidationInterface(txr);
273 
274  // When there are multiple transactions in the package, we call ProcessNewPackage(txs, test_accept=false)
275  // and AcceptToMemoryPool(txs.back(), test_accept=true). When there is only 1 transaction, we might flip it
276  // (the package is a test accept and ATMP is a submission).
277  auto single_submit = txs.size() == 1 && fuzzed_data_provider.ConsumeBool();
278 
279  // Exercise client_maxfeerate logic
280  std::optional<CFeeRate> client_maxfeerate{};
281  if (fuzzed_data_provider.ConsumeBool()) {
282  client_maxfeerate = CFeeRate(fuzzed_data_provider.ConsumeIntegralInRange<CAmount>(-1, 50 * COIN), 100);
283  }
284 
285  const auto result_package = WITH_LOCK(::cs_main,
286  return ProcessNewPackage(chainstate, tx_pool, txs, /*test_accept=*/single_submit, client_maxfeerate));
287 
288  // Always set bypass_limits to false because it is not supported in ProcessNewPackage and
289  // can be a source of divergence.
290  const auto res = WITH_LOCK(::cs_main, return AcceptToMemoryPool(chainstate, txs.back(), GetTime(),
291  /*bypass_limits=*/false, /*test_accept=*/!single_submit));
292  const bool passed = res.m_result_type == MempoolAcceptResult::ResultType::VALID;
293 
294  node.validation_signals->SyncWithValidationInterfaceQueue();
295  node.validation_signals->UnregisterSharedValidationInterface(txr);
296 
297  // There is only 1 transaction in the package. We did a test-package-accept and a ATMP
298  if (single_submit) {
299  Assert(passed != added.empty());
300  Assert(passed == res.m_state.IsValid());
301  if (passed) {
302  Assert(added.size() == 1);
303  Assert(txs.back() == *added.begin());
304  }
305  } else if (result_package.m_state.GetResult() != PackageValidationResult::PCKG_POLICY) {
306  // We don't know anything about the validity since transactions were randomly generated, so
307  // just use result_package.m_state here. This makes the expect_valid check meaningless, but
308  // we can still verify that the contents of m_tx_results are consistent with m_state.
309  const bool expect_valid{result_package.m_state.IsValid()};
310  Assert(!CheckPackageMempoolAcceptResult(txs, result_package, expect_valid, nullptr));
311  } else {
312  // This is empty if it fails early checks, or "full" if transactions are looked at deeper
313  Assert(result_package.m_tx_results.size() == txs.size() || result_package.m_tx_results.empty());
314  }
315 
316  CheckMempoolV3Invariants(tx_pool);
317  }
318 
319  node.validation_signals->UnregisterSharedValidationInterface(outpoints_updater);
320 
321  WITH_LOCK(::cs_main, tx_pool.check(chainstate.CoinsTip(), chainstate.m_chain.Height() + 1));
322 }
323 } // namespace
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
static constexpr CAmount COIN
The amount of satoshis in one BTC.
Definition: amount.h:15
#define Assert(val)
Identity function.
Definition: check.h:77
uint32_t nTime
Definition: chain.h:190
int64_t GetMedianTimePast() const
Definition: chain.h:279
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:434
int Height() const
Return the maximal height in the chain.
Definition: chain.h:463
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:33
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
static const int32_t CURRENT_VERSION
Definition: transaction.h:299
An input of a transaction.
Definition: transaction.h:67
uint32_t nSequence
Definition: transaction.h:71
CScript scriptSig
Definition: transaction.h:70
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:72
COutPoint prevout
Definition: transaction.h:69
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:302
Implement this to subscribe to events generated in validation and mempool.
virtual void TransactionRemovedFromMempool(const CTransactionRef &tx, MemPoolRemovalReason reason, uint64_t mempool_sequence)
Notifies listeners of a transaction leaving mempool.
virtual void TransactionAddedToMempool(const NewMempoolTransactionInfo &tx, uint64_t mempool_sequence)
Notifies listeners of a transaction having been added to mempool.
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:490
CChain m_chain
The current chain of blockheaders we consult and build on.
Definition: validation.h:570
CCoinsViewCache & CoinsTip() EXCLUSIVE_LOCKS_REQUIRED(
Definition: validation.h:596
T ConsumeIntegralInRange(T min, T max)
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define FUZZ_TARGET(...)
Definition: fuzz.h:36
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:23
uint64_t sequence
static void pool cs
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
Definition: init.h:25
@ PCKG_POLICY
The package itself is invalid (e.g. too many transactions).
unsigned int nBytesPerSigOp
Definition: settings.cpp:10
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ OP_CHECKSIG
Definition: script.h:189
node::NodeContext m_node
Definition: setup_common.h:54
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
std::vector< std::vector< unsigned char > > stack
Definition: script.h:569
Testing setup that configures a complete environment.
Definition: setup_common.h:83
const CTransactionRef m_tx
int64_t ancestor_count
The maximum allowed number of transactions in a package including the entry and its ancestors.
Options struct containing options for constructing a CTxMemPool.
NodeContext struct containing references to chain state and connection state.
Definition: context.h:49
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:77
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.cpp:155
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
Definition: util.h:47
COutPoint MineBlock(const NodeContext &node, const CScript &coinbase_scriptPubKey)
Returns the generated coin.
Definition: mining.cpp:63
static const std::vector< std::vector< uint8_t > > P2WSH_EMPTY_TRUE_STACK
Definition: script.h:30
static const std::vector< std::vector< uint8_t > > P2WSH_EMPTY_TWO_STACK
Definition: script.h:31
static const CScript P2WSH_EMPTY
Definition: script.h:22
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:19
std::optional< std::string > CheckPackageMempoolAcceptResult(const Package &txns, const PackageMempoolAcceptResult &result, bool expect_valid, const CTxMemPool *mempool)
Check expected properties for every PackageMempoolAcceptResult, regardless of value.
Definition: txmempool.cpp:42
void CheckMempoolV3Invariants(const CTxMemPool &tx_pool)
For every transaction in tx_pool, check v3 invariants:
Definition: txmempool.cpp:116
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
int64_t GetTime()
Definition: time.cpp:44
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:32
PackageMempoolAcceptResult ProcessNewPackage(Chainstate &active_chainstate, CTxMemPool &pool, const Package &package, bool test_accept, const std::optional< CFeeRate > &client_maxfeerate)
Validate (and maybe submit) a package to the mempool.
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.