Bitcoin Core  27.99.0
P2P Digital Currency
rbf.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-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 <node/mempool_args.h>
6 #include <policy/rbf.h>
8 #include <sync.h>
10 #include <test/fuzz/fuzz.h>
11 #include <test/fuzz/util.h>
12 #include <test/fuzz/util/mempool.h>
13 #include <test/util/setup_common.h>
14 #include <test/util/txmempool.h>
15 #include <txmempool.h>
16 #include <util/check.h>
17 #include <util/translation.h>
18 
19 #include <cstdint>
20 #include <optional>
21 #include <string>
22 #include <vector>
23 
24 namespace {
25 const BasicTestingSetup* g_setup;
26 } // namespace
27 
28 const int NUM_ITERS = 10000;
29 
30 std::vector<COutPoint> g_outpoints;
31 
33 {
34  static const auto testing_setup = MakeNoLogFileContext<>();
35  g_setup = testing_setup.get();
36 }
37 
39 {
40  static const auto testing_setup = MakeNoLogFileContext<>();
41  g_setup = testing_setup.get();
42 
43  // Create a fixed set of unique "UTXOs" to source parents from
44  // to avoid fuzzer giving circular references
45  for (int i = 0; i < NUM_ITERS; ++i) {
46  g_outpoints.emplace_back();
47  g_outpoints.back().n = i;
48  }
49 
50 }
51 
53 {
54  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
55  SetMockTime(ConsumeTime(fuzzed_data_provider));
56  std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
57  if (!mtx) {
58  return;
59  }
60 
61  bilingual_str error;
62  CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node), error};
63  Assert(error.empty());
64 
65  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), NUM_ITERS)
66  {
67  const std::optional<CMutableTransaction> another_mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
68  if (!another_mtx) {
69  break;
70  }
71  const CTransaction another_tx{*another_mtx};
72  if (fuzzed_data_provider.ConsumeBool() && !mtx->vin.empty()) {
73  mtx->vin[0].prevout = COutPoint{another_tx.GetHash(), 0};
74  }
75  LOCK2(cs_main, pool.cs);
76  pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, another_tx));
77  }
78  const CTransaction tx{*mtx};
79  if (fuzzed_data_provider.ConsumeBool()) {
80  LOCK2(cs_main, pool.cs);
81  pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, tx));
82  }
83  {
84  LOCK(pool.cs);
85  (void)IsRBFOptIn(tx, pool);
86  }
87 }
88 
90 {
91  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
92  SetMockTime(ConsumeTime(fuzzed_data_provider));
93 
94  // "Real" virtual size is not important for this test since ConsumeTxMemPoolEntry generates its own virtual size values
95  // so we construct small transactions for performance reasons. Child simply needs an input for later to perhaps connect to parent.
96  CMutableTransaction child;
97  child.vin.resize(1);
98 
99  bilingual_str error;
100  CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node), error};
101  Assert(error.empty());
102 
103  // Add a bunch of parent-child pairs to the mempool, and remember them.
104  std::vector<CTransaction> mempool_txs;
105  size_t iter{0};
106 
107  int32_t replacement_vsize = fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(1, 1000000);
108 
109  // Keep track of the total vsize of CTxMemPoolEntry's being added to the mempool to avoid overflow
110  // Add replacement_vsize since this is added to new diagram during RBF check
111  int64_t running_vsize_total{replacement_vsize};
112 
113  LOCK2(cs_main, pool.cs);
114 
115  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), NUM_ITERS)
116  {
117  // Make sure txns only have one input, and that a unique input is given to avoid circular references
118  CMutableTransaction parent;
119  assert(iter <= g_outpoints.size());
120  parent.vin.resize(1);
121  parent.vin[0].prevout = g_outpoints[iter++];
122  parent.vout.emplace_back(0, CScript());
123 
124  mempool_txs.emplace_back(parent);
125  const auto parent_entry = ConsumeTxMemPoolEntry(fuzzed_data_provider, mempool_txs.back());
126  running_vsize_total += parent_entry.GetTxSize();
127  if (running_vsize_total > std::numeric_limits<int32_t>::max()) {
128  // We aren't adding this final tx to mempool, so we don't want to conflict with it
129  mempool_txs.pop_back();
130  break;
131  }
132  pool.addUnchecked(parent_entry);
133  if (fuzzed_data_provider.ConsumeBool()) {
134  child.vin[0].prevout = COutPoint{mempool_txs.back().GetHash(), 0};
135  }
136  mempool_txs.emplace_back(child);
137  const auto child_entry = ConsumeTxMemPoolEntry(fuzzed_data_provider, mempool_txs.back());
138  running_vsize_total += child_entry.GetTxSize();
139  if (running_vsize_total > std::numeric_limits<int32_t>::max()) {
140  // We aren't adding this final tx to mempool, so we don't want to conflict with it
141  mempool_txs.pop_back();
142  break;
143  }
144  pool.addUnchecked(child_entry);
145 
146  if (fuzzed_data_provider.ConsumeBool()) {
147  pool.PrioritiseTransaction(mempool_txs.back().GetHash().ToUint256(), fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(-100000, 100000));
148  }
149  }
150 
151  // Pick some transactions at random to be the direct conflicts
152  CTxMemPool::setEntries direct_conflicts;
153  for (auto& tx : mempool_txs) {
154  if (fuzzed_data_provider.ConsumeBool()) {
155  direct_conflicts.insert(*pool.GetIter(tx.GetHash()));
156  }
157  }
158 
159  // Calculate all conflicts:
160  CTxMemPool::setEntries all_conflicts;
161  for (auto& txiter : direct_conflicts) {
162  pool.CalculateDescendants(txiter, all_conflicts);
163  }
164 
165  // Calculate the chunks for a replacement.
166  CAmount replacement_fees = ConsumeMoney(fuzzed_data_provider);
167  auto calc_results{pool.CalculateChunksForRBF(replacement_fees, replacement_vsize, direct_conflicts, all_conflicts)};
168 
169  if (calc_results.has_value()) {
170  // Sanity checks on the chunks.
171 
172  // Feerates are monotonically decreasing.
173  FeeFrac first_sum;
174  for (size_t i = 0; i < calc_results->first.size(); ++i) {
175  first_sum += calc_results->first[i];
176  if (i) assert(!(calc_results->first[i - 1] << calc_results->first[i]));
177  }
178  FeeFrac second_sum;
179  for (size_t i = 0; i < calc_results->second.size(); ++i) {
180  second_sum += calc_results->second[i];
181  if (i) assert(!(calc_results->second[i - 1] << calc_results->second[i]));
182  }
183 
184  FeeFrac replaced;
185  for (auto txiter : all_conflicts) {
186  replaced.fee += txiter->GetModifiedFee();
187  replaced.size += txiter->GetTxSize();
188  }
189  // The total fee & size of the new diagram minus replaced fee & size should be the total
190  // fee & size of the old diagram minus replacement fee & size.
191  assert((first_sum - replaced) == (second_sum - FeeFrac{replacement_fees, replacement_vsize}));
192  }
193 
194  // If internals report error, wrapper should too
195  auto err_tuple{ImprovesFeerateDiagram(pool, direct_conflicts, all_conflicts, replacement_fees, replacement_vsize)};
196  if (!calc_results.has_value()) {
197  assert(err_tuple.value().first == DiagramCheckError::UNCALCULABLE);
198  } else {
199  // Diagram check succeeded
200  auto old_sum = std::accumulate(calc_results->first.begin(), calc_results->first.end(), FeeFrac{});
201  auto new_sum = std::accumulate(calc_results->second.begin(), calc_results->second.end(), FeeFrac{});
202  if (!err_tuple.has_value()) {
203  // New diagram's final fee should always match or exceed old diagram's
204  assert(old_sum.fee <= new_sum.fee);
205  } else if (old_sum.fee > new_sum.fee) {
206  // Or it failed, and if old diagram had higher fees, it should be a failure
207  assert(err_tuple.value().first == DiagramCheckError::FAILURE);
208  }
209  }
210 }
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
#define Assert(val)
Identity function.
Definition: check.h:77
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
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const std::vector< CTxIn > vin
Definition: transaction.h:306
CTxMemPool stores valid-according-to-the-current-best-chain transactions that may be included in the ...
Definition: txmempool.h:304
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:394
T ConsumeIntegralInRange(T min, T max)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
std::optional< std::pair< DiagramCheckError, std::string > > ImprovesFeerateDiagram(CTxMemPool &pool, const CTxMemPool::setEntries &direct_conflicts, const CTxMemPool::setEntries &all_conflicts, CAmount replacement_fees, int64_t replacement_vsize)
The replacement transaction must improve the feerate diagram of the mempool.
Definition: rbf.cpp:187
RBFTransactionState IsRBFOptIn(const CTransaction &tx, const CTxMemPool &pool)
Determine whether an unconfirmed transaction is signaling opt-in to RBF according to BIP 125 This inv...
Definition: rbf.cpp:24
@ FAILURE
New diagram wasn't strictly superior
@ UNCALCULABLE
Unable to calculate due to topology or other reason.
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
Basic testing setup.
Definition: setup_common.h:63
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
Data structure storing a fee and size, ordered by increasing fee/size.
Definition: feefrac.h:39
int64_t fee
Definition: feefrac.h:63
int32_t size
Definition: feefrac.h:64
Bilingual messages:
Definition: translation.h:18
bool empty() const
Definition: translation.h:29
#define LOCK2(cs1, cs2)
Definition: sync.h:258
#define LOCK(cs)
Definition: sync.h:257
FUZZ_TARGET(rbf,.init=initialize_rbf)
Definition: rbf.cpp:52
std::vector< COutPoint > g_outpoints
Definition: rbf.cpp:30
const int NUM_ITERS
Definition: rbf.cpp:28
void initialize_rbf()
Definition: rbf.cpp:32
void initialize_package_rbf()
Definition: rbf.cpp:38
CTxMemPoolEntry ConsumeTxMemPoolEntry(FuzzedDataProvider &fuzzed_data_provider, const CTransaction &tx) noexcept
Definition: mempool.cpp:17
int64_t ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
Definition: util.cpp:34
CAmount ConsumeMoney(FuzzedDataProvider &fuzzed_data_provider, const std::optional< CAmount > &max) noexcept
Definition: util.cpp:29
CTxMemPool::Options MemPoolOptionsForTest(const NodeContext &node)
Definition: txmempool.cpp:20
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:32
assert(!tx.IsCoinBase())