Bitcoin Core  24.99.0
P2P Digital Currency
coins_view.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 <chainparams.h>
6 #include <chainparamsbase.h>
7 #include <coins.h>
8 #include <consensus/amount.h>
9 #include <consensus/tx_check.h>
10 #include <consensus/tx_verify.h>
11 #include <consensus/validation.h>
12 #include <key.h>
13 #include <policy/policy.h>
14 #include <primitives/transaction.h>
15 #include <pubkey.h>
17 #include <test/fuzz/fuzz.h>
18 #include <test/fuzz/util.h>
19 #include <test/util/setup_common.h>
20 #include <validation.h>
21 
22 #include <cstdint>
23 #include <limits>
24 #include <optional>
25 #include <string>
26 #include <vector>
27 
28 namespace {
29 const TestingSetup* g_setup;
30 const Coin EMPTY_COIN{};
31 
32 bool operator==(const Coin& a, const Coin& b)
33 {
34  if (a.IsSpent() && b.IsSpent()) return true;
35  return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out;
36 }
37 } // namespace
38 
40 {
41  static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
42  g_setup = testing_setup.get();
43 }
44 
46 {
47  FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
48  CCoinsView backend_coins_view;
49  CCoinsViewCache coins_view_cache{&backend_coins_view};
50  COutPoint random_out_point;
51  Coin random_coin;
52  CMutableTransaction random_mutable_transaction;
53  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
54  CallOneOf(
55  fuzzed_data_provider,
56  [&] {
57  if (random_coin.IsSpent()) {
58  return;
59  }
60  Coin coin = random_coin;
61  bool expected_code_path = false;
62  const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
63  try {
64  coins_view_cache.AddCoin(random_out_point, std::move(coin), possible_overwrite);
65  expected_code_path = true;
66  } catch (const std::logic_error& e) {
67  if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
68  assert(!possible_overwrite);
69  expected_code_path = true;
70  }
71  }
72  assert(expected_code_path);
73  },
74  [&] {
75  (void)coins_view_cache.Flush();
76  },
77  [&] {
78  (void)coins_view_cache.Sync();
79  },
80  [&] {
81  coins_view_cache.SetBestBlock(ConsumeUInt256(fuzzed_data_provider));
82  },
83  [&] {
84  Coin move_to;
85  (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
86  },
87  [&] {
88  coins_view_cache.Uncache(random_out_point);
89  },
90  [&] {
91  if (fuzzed_data_provider.ConsumeBool()) {
92  backend_coins_view = CCoinsView{};
93  }
94  coins_view_cache.SetBackend(backend_coins_view);
95  },
96  [&] {
97  const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
98  if (!opt_out_point) {
99  return;
100  }
101  random_out_point = *opt_out_point;
102  },
103  [&] {
104  const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
105  if (!opt_coin) {
106  return;
107  }
108  random_coin = *opt_coin;
109  },
110  [&] {
111  const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider);
112  if (!opt_mutable_transaction) {
113  return;
114  }
115  random_mutable_transaction = *opt_mutable_transaction;
116  },
117  [&] {
118  CCoinsMap coins_map;
119  LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 10000) {
120  CCoinsCacheEntry coins_cache_entry;
121  coins_cache_entry.flags = fuzzed_data_provider.ConsumeIntegral<unsigned char>();
122  if (fuzzed_data_provider.ConsumeBool()) {
123  coins_cache_entry.coin = random_coin;
124  } else {
125  const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
126  if (!opt_coin) {
127  return;
128  }
129  coins_cache_entry.coin = *opt_coin;
130  }
131  coins_map.emplace(random_out_point, std::move(coins_cache_entry));
132  }
133  bool expected_code_path = false;
134  try {
135  coins_view_cache.BatchWrite(coins_map, fuzzed_data_provider.ConsumeBool() ? ConsumeUInt256(fuzzed_data_provider) : coins_view_cache.GetBestBlock());
136  expected_code_path = true;
137  } catch (const std::logic_error& e) {
138  if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
139  expected_code_path = true;
140  }
141  }
142  assert(expected_code_path);
143  });
144  }
145 
146  {
147  const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
148  const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
149  const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
150  const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
151  Coin coin_using_get_coin;
152  const bool exists_using_get_coin = coins_view_cache.GetCoin(random_out_point, coin_using_get_coin);
153  if (exists_using_get_coin) {
154  assert(coin_using_get_coin == coin_using_access_coin);
155  }
156  assert((exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin && exists_using_get_coin) ||
157  (!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin && !exists_using_get_coin));
158  const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
159  if (exists_using_have_coin_in_backend) {
160  assert(exists_using_have_coin);
161  }
162  Coin coin_using_backend_get_coin;
163  if (backend_coins_view.GetCoin(random_out_point, coin_using_backend_get_coin)) {
164  assert(exists_using_have_coin_in_backend);
165  assert(coin_using_get_coin == coin_using_backend_get_coin);
166  } else {
167  assert(!exists_using_have_coin_in_backend);
168  }
169  }
170 
171  {
172  bool expected_code_path = false;
173  try {
174  (void)coins_view_cache.Cursor();
175  } catch (const std::logic_error&) {
176  expected_code_path = true;
177  }
178  assert(expected_code_path);
179  (void)coins_view_cache.DynamicMemoryUsage();
180  (void)coins_view_cache.EstimateSize();
181  (void)coins_view_cache.GetBestBlock();
182  (void)coins_view_cache.GetCacheSize();
183  (void)coins_view_cache.GetHeadBlocks();
184  (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
185  }
186 
187  {
188  std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
189  assert(!coins_view_cursor);
190  (void)backend_coins_view.EstimateSize();
191  (void)backend_coins_view.GetBestBlock();
192  (void)backend_coins_view.GetHeadBlocks();
193  }
194 
195  if (fuzzed_data_provider.ConsumeBool()) {
196  CallOneOf(
197  fuzzed_data_provider,
198  [&] {
199  const CTransaction transaction{random_mutable_transaction};
200  bool is_spent = false;
201  for (const CTxOut& tx_out : transaction.vout) {
202  if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
203  is_spent = true;
204  }
205  }
206  if (is_spent) {
207  // Avoid:
208  // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
209  return;
210  }
211  bool expected_code_path = false;
212  const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
213  const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
214  try {
215  AddCoins(coins_view_cache, transaction, height, possible_overwrite);
216  expected_code_path = true;
217  } catch (const std::logic_error& e) {
218  if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
219  assert(!possible_overwrite);
220  expected_code_path = true;
221  }
222  }
223  assert(expected_code_path);
224  },
225  [&] {
226  (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
227  },
228  [&] {
229  TxValidationState state;
230  CAmount tx_fee_out;
231  const CTransaction transaction{random_mutable_transaction};
232  if (ContainsSpentInput(transaction, coins_view_cache)) {
233  // Avoid:
234  // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
235  return;
236  }
237  TxValidationState dummy;
238  if (!CheckTransaction(transaction, dummy)) {
239  // It is not allowed to call CheckTxInputs if CheckTransaction failed
240  return;
241  }
242  if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
243  assert(MoneyRange(tx_fee_out));
244  }
245  },
246  [&] {
247  const CTransaction transaction{random_mutable_transaction};
248  if (ContainsSpentInput(transaction, coins_view_cache)) {
249  // Avoid:
250  // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
251  return;
252  }
253  (void)GetP2SHSigOpCount(transaction, coins_view_cache);
254  },
255  [&] {
256  const CTransaction transaction{random_mutable_transaction};
257  if (ContainsSpentInput(transaction, coins_view_cache)) {
258  // Avoid:
259  // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
260  return;
261  }
262  const auto flags{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
263  if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
264  // Avoid:
265  // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness *, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
266  return;
267  }
268  (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
269  },
270  [&] {
271  (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
272  });
273  }
274 }
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
catch(const std::exception &e)
int flags
Definition: bitcoin-tx.cpp:525
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
Abstract view on the open txout dataset.
Definition: coins.h:157
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:19
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
An output of a transaction.
Definition: transaction.h:158
A UTXO entry.
Definition: coins.h:31
CTxOut out
unspent transaction output
Definition: coins.h:34
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:115
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
void initialize_coins_view()
Definition: coins_view.cpp:39
FUZZ_TARGET_INIT(coins_view, initialize_coins_view)
Definition: coins_view.cpp:45
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:18
@ SCRIPT_VERIFY_P2SH
Definition: interpreter.h:47
@ SCRIPT_VERIFY_WITNESS
Definition: interpreter.h:106
bool CheckTxInputs(const CTransaction &tx, TxValidationState &state, const CCoinsViewCache &inputs, int nSpendHeight, CAmount &txfee)
Check whether all inputs of this transaction are valid (no double spends and amounts) This does not m...
Definition: tx_verify.cpp:168
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:630
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs to mitigate two potential denial-of-service attacks:
Definition: policy.cpp:177
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:211
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:104
unsigned char flags
Definition: coins.h:106
Coin coin
Definition: coins.h:105
A mutable version of CTransaction.
Definition: transaction.h:380
Testing setup that configures a complete environment.
Definition: setup_common.h:108
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
Definition: util.cpp:196
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:149
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:36
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, uint32_t flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:147
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:130
assert(!tx.IsCoinBase())