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