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 
17 #include <cstdint>
18 #include <optional>
19 #include <string>
20 #include <vector>
21 
22 namespace {
23 const BasicTestingSetup* g_setup;
24 } // namespace
25 
26 const int NUM_ITERS = 10000;
27 
28 std::vector<COutPoint> g_outpoints;
29 
31 {
32  static const auto testing_setup = MakeNoLogFileContext<>();
33  g_setup = testing_setup.get();
34 }
35 
37 {
38  static const auto testing_setup = MakeNoLogFileContext<>();
39  g_setup = testing_setup.get();
40 
41  // Create a fixed set of unique "UTXOs" to source parents from
42  // to avoid fuzzer giving circular references
43  for (int i = 0; i < NUM_ITERS; ++i) {
44  g_outpoints.emplace_back();
45  g_outpoints.back().n = i;
46  }
47 
48 }
49 
51 {
52  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
53  SetMockTime(ConsumeTime(fuzzed_data_provider));
54  std::optional<CMutableTransaction> mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
55  if (!mtx) {
56  return;
57  }
58 
59  CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node)};
60 
61  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), NUM_ITERS)
62  {
63  const std::optional<CMutableTransaction> another_mtx = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
64  if (!another_mtx) {
65  break;
66  }
67  const CTransaction another_tx{*another_mtx};
68  if (fuzzed_data_provider.ConsumeBool() && !mtx->vin.empty()) {
69  mtx->vin[0].prevout = COutPoint{another_tx.GetHash(), 0};
70  }
71  LOCK2(cs_main, pool.cs);
72  pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, another_tx));
73  }
74  const CTransaction tx{*mtx};
75  if (fuzzed_data_provider.ConsumeBool()) {
76  LOCK2(cs_main, pool.cs);
77  pool.addUnchecked(ConsumeTxMemPoolEntry(fuzzed_data_provider, tx));
78  }
79  {
80  LOCK(pool.cs);
81  (void)IsRBFOptIn(tx, pool);
82  }
83 }
84 
85 void CheckDiagramConcave(std::vector<FeeFrac>& diagram)
86 {
87  // Diagrams are in monotonically-decreasing feerate order.
88  FeeFrac last_chunk = diagram.front();
89  for (size_t i = 1; i<diagram.size(); ++i) {
90  FeeFrac next_chunk = diagram[i] - diagram[i-1];
91  assert(next_chunk <= last_chunk);
92  last_chunk = next_chunk;
93  }
94 }
95 
97 {
98  FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
99  SetMockTime(ConsumeTime(fuzzed_data_provider));
100 
101  std::optional<CMutableTransaction> child = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
102  if (!child) return;
103 
104  CTxMemPool pool{MemPoolOptionsForTest(g_setup->m_node)};
105 
106  // Add a bunch of parent-child pairs to the mempool, and remember them.
107  std::vector<CTransaction> mempool_txs;
108  size_t iter{0};
109 
110  int64_t replacement_vsize = fuzzed_data_provider.ConsumeIntegralInRange<int64_t>(1, 1000000);
111 
112  // Keep track of the total vsize of CTxMemPoolEntry's being added to the mempool to avoid overflow
113  // Add replacement_vsize since this is added to new diagram during RBF check
114  int64_t running_vsize_total{replacement_vsize};
115 
116  LOCK2(cs_main, pool.cs);
117 
118  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), NUM_ITERS)
119  {
120  // Make sure txns only have one input, and that a unique input is given to avoid circular references
121  std::optional<CMutableTransaction> parent = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
122  if (!parent) {
123  return;
124  }
125  assert(iter <= g_outpoints.size());
126  parent->vin.resize(1);
127  parent->vin[0].prevout = g_outpoints[iter++];
128 
129  mempool_txs.emplace_back(*parent);
130  const auto parent_entry = ConsumeTxMemPoolEntry(fuzzed_data_provider, mempool_txs.back());
131  running_vsize_total += parent_entry.GetTxSize();
132  if (running_vsize_total > std::numeric_limits<int32_t>::max()) {
133  // We aren't adding this final tx to mempool, so we don't want to conflict with it
134  mempool_txs.pop_back();
135  break;
136  }
137  pool.addUnchecked(parent_entry);
138  if (fuzzed_data_provider.ConsumeBool() && !child->vin.empty()) {
139  child->vin[0].prevout = COutPoint{mempool_txs.back().GetHash(), 0};
140  }
141  mempool_txs.emplace_back(*child);
142  const auto child_entry = ConsumeTxMemPoolEntry(fuzzed_data_provider, mempool_txs.back());
143  running_vsize_total += child_entry.GetTxSize();
144  if (running_vsize_total > std::numeric_limits<int32_t>::max()) {
145  // We aren't adding this final tx to mempool, so we don't want to conflict with it
146  mempool_txs.pop_back();
147  break;
148  }
149  pool.addUnchecked(child_entry);
150 
151  if (fuzzed_data_provider.ConsumeBool()) {
152  pool.PrioritiseTransaction(mempool_txs.back().GetHash().ToUint256(), fuzzed_data_provider.ConsumeIntegralInRange<int32_t>(-100000, 100000));
153  }
154  }
155 
156  // Pick some transactions at random to be the direct conflicts
157  CTxMemPool::setEntries direct_conflicts;
158  for (auto& tx : mempool_txs) {
159  if (fuzzed_data_provider.ConsumeBool()) {
160  direct_conflicts.insert(*pool.GetIter(tx.GetHash()));
161  }
162  }
163 
164  // Calculate all conflicts:
165  CTxMemPool::setEntries all_conflicts;
166  for (auto& txiter : direct_conflicts) {
167  pool.CalculateDescendants(txiter, all_conflicts);
168  }
169 
170  // Calculate the feerate diagrams for a replacement.
171  CAmount replacement_fees = ConsumeMoney(fuzzed_data_provider);
172  auto calc_results{pool.CalculateFeerateDiagramsForRBF(replacement_fees, replacement_vsize, direct_conflicts, all_conflicts)};
173 
174  if (calc_results.has_value()) {
175  // Sanity checks on the diagrams.
176 
177  // Diagrams start at 0.
178  assert(calc_results->first.front().size == 0);
179  assert(calc_results->first.front().fee == 0);
180  assert(calc_results->second.front().size == 0);
181  assert(calc_results->second.front().fee == 0);
182 
183  CheckDiagramConcave(calc_results->first);
184  CheckDiagramConcave(calc_results->second);
185 
186  CAmount replaced_fee{0};
187  int64_t replaced_size{0};
188  for (auto txiter : all_conflicts) {
189  replaced_fee += txiter->GetModifiedFee();
190  replaced_size += txiter->GetTxSize();
191  }
192  // The total fee of the new diagram should be the total fee of the old
193  // diagram - replaced_fee + replacement_fees
194  assert(calc_results->first.back().fee - replaced_fee + replacement_fees == calc_results->second.back().fee);
195  assert(calc_results->first.back().size - replaced_size + replacement_vsize == calc_results->second.back().size);
196  }
197 
198  // If internals report error, wrapper should too
199  auto err_tuple{ImprovesFeerateDiagram(pool, direct_conflicts, all_conflicts, replacement_fees, replacement_vsize)};
200  if (!calc_results.has_value()) {
201  assert(err_tuple.value().first == DiagramCheckError::UNCALCULABLE);
202  } else {
203  // Diagram check succeeded
204  if (!err_tuple.has_value()) {
205  // New diagram's final fee should always match or exceed old diagram's
206  assert(calc_results->first.back().fee <= calc_results->second.back().fee);
207  } else if (calc_results->first.back().fee > calc_results->second.back().fee) {
208  // Or it failed, and if old diagram had higher fees, it should be a failure
209  assert(err_tuple.value().first == DiagramCheckError::FAILURE);
210  }
211  }
212 }
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
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:302
std::set< txiter, CompareIteratorByHash > setEntries
Definition: txmempool.h:396
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:23
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:52
Data structure storing a fee and size, ordered by increasing fee/size.
Definition: feefrac.h:39
#define LOCK2(cs1, cs2)
Definition: sync.h:258
#define LOCK(cs)
Definition: sync.h:257
FUZZ_TARGET(rbf,.init=initialize_rbf)
Definition: rbf.cpp:50
std::vector< COutPoint > g_outpoints
Definition: rbf.cpp:28
const int NUM_ITERS
Definition: rbf.cpp:26
void initialize_rbf()
Definition: rbf.cpp:30
void CheckDiagramConcave(std::vector< FeeFrac > &diagram)
Definition: rbf.cpp:85
void initialize_package_rbf()
Definition: rbf.cpp:36
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:19
void SetMockTime(int64_t nMockTimeIn)
DEPRECATED Use SetMockTime with chrono type.
Definition: time.cpp:32
assert(!tx.IsCoinBase())