/ src / test / fuzz / coins_view.cpp
coins_view.cpp
  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>
 13  #include <test/fuzz/FuzzedDataProvider.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 TestingSetup* g_setup;
 31  const Coin EMPTY_COIN{};
 32  
 33  bool operator==(const Coin& a, const Coin& b)
 34  {
 35      if (a.IsSpent() && b.IsSpent()) return true;
 36      return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out;
 37  }
 38  } // namespace
 39  
 40  void initialize_coins_view()
 41  {
 42      static const auto testing_setup = MakeNoLogFileContext<const TestingSetup>();
 43      g_setup = testing_setup.get();
 44  }
 45  
 46  FUZZ_TARGET(coins_view, .init = initialize_coins_view)
 47  {
 48      FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
 49      bool good_data{true};
 50  
 51      CCoinsView backend_coins_view;
 52      CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
 53      COutPoint random_out_point;
 54      Coin random_coin;
 55      CMutableTransaction random_mutable_transaction;
 56      LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
 57      {
 58          CallOneOf(
 59              fuzzed_data_provider,
 60              [&] {
 61                  if (random_coin.IsSpent()) {
 62                      return;
 63                  }
 64                  Coin coin = random_coin;
 65                  bool expected_code_path = false;
 66                  const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
 67                  try {
 68                      coins_view_cache.AddCoin(random_out_point, std::move(coin), possible_overwrite);
 69                      expected_code_path = true;
 70                  } catch (const std::logic_error& e) {
 71                      if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
 72                          assert(!possible_overwrite);
 73                          expected_code_path = true;
 74                      }
 75                  }
 76                  assert(expected_code_path);
 77              },
 78              [&] {
 79                  (void)coins_view_cache.Flush();
 80              },
 81              [&] {
 82                  (void)coins_view_cache.Sync();
 83              },
 84              [&] {
 85                  coins_view_cache.SetBestBlock(ConsumeUInt256(fuzzed_data_provider));
 86              },
 87              [&] {
 88                  Coin move_to;
 89                  (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
 90              },
 91              [&] {
 92                  coins_view_cache.Uncache(random_out_point);
 93              },
 94              [&] {
 95                  if (fuzzed_data_provider.ConsumeBool()) {
 96                      backend_coins_view = CCoinsView{};
 97                  }
 98                  coins_view_cache.SetBackend(backend_coins_view);
 99              },
100              [&] {
101                  const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
102                  if (!opt_out_point) {
103                      good_data = false;
104                      return;
105                  }
106                  random_out_point = *opt_out_point;
107              },
108              [&] {
109                  const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
110                  if (!opt_coin) {
111                      good_data = false;
112                      return;
113                  }
114                  random_coin = *opt_coin;
115              },
116              [&] {
117                  const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
118                  if (!opt_mutable_transaction) {
119                      good_data = false;
120                      return;
121                  }
122                  random_mutable_transaction = *opt_mutable_transaction;
123              },
124              [&] {
125                  CCoinsMapMemoryResource resource;
126                  CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
127                  LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
128                  {
129                      CCoinsCacheEntry coins_cache_entry;
130                      coins_cache_entry.flags = fuzzed_data_provider.ConsumeIntegral<unsigned char>();
131                      if (fuzzed_data_provider.ConsumeBool()) {
132                          coins_cache_entry.coin = random_coin;
133                      } else {
134                          const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
135                          if (!opt_coin) {
136                              good_data = false;
137                              return;
138                          }
139                          coins_cache_entry.coin = *opt_coin;
140                      }
141                      coins_map.emplace(random_out_point, std::move(coins_cache_entry));
142                  }
143                  bool expected_code_path = false;
144                  try {
145                      coins_view_cache.BatchWrite(coins_map, fuzzed_data_provider.ConsumeBool() ? ConsumeUInt256(fuzzed_data_provider) : coins_view_cache.GetBestBlock());
146                      expected_code_path = true;
147                  } catch (const std::logic_error& e) {
148                      if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
149                          expected_code_path = true;
150                      }
151                  }
152                  assert(expected_code_path);
153              });
154      }
155  
156      {
157          const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
158          const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
159          const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
160          const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
161          Coin coin_using_get_coin;
162          const bool exists_using_get_coin = coins_view_cache.GetCoin(random_out_point, coin_using_get_coin);
163          if (exists_using_get_coin) {
164              assert(coin_using_get_coin == coin_using_access_coin);
165          }
166          assert((exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin && exists_using_get_coin) ||
167                 (!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin && !exists_using_get_coin));
168          // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
169          const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
170          if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
171              assert(exists_using_have_coin);
172          }
173          Coin coin_using_backend_get_coin;
174          if (backend_coins_view.GetCoin(random_out_point, coin_using_backend_get_coin)) {
175              assert(exists_using_have_coin_in_backend);
176              // Note we can't assert that `coin_using_get_coin == coin_using_backend_get_coin` because the coin in
177              // the cache may have been modified but not yet flushed.
178          } else {
179              assert(!exists_using_have_coin_in_backend);
180          }
181      }
182  
183      {
184          bool expected_code_path = false;
185          try {
186              (void)coins_view_cache.Cursor();
187          } catch (const std::logic_error&) {
188              expected_code_path = true;
189          }
190          assert(expected_code_path);
191          (void)coins_view_cache.DynamicMemoryUsage();
192          (void)coins_view_cache.EstimateSize();
193          (void)coins_view_cache.GetBestBlock();
194          (void)coins_view_cache.GetCacheSize();
195          (void)coins_view_cache.GetHeadBlocks();
196          (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
197      }
198  
199      {
200          std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
201          assert(!coins_view_cursor);
202          (void)backend_coins_view.EstimateSize();
203          (void)backend_coins_view.GetBestBlock();
204          (void)backend_coins_view.GetHeadBlocks();
205      }
206  
207      if (fuzzed_data_provider.ConsumeBool()) {
208          CallOneOf(
209              fuzzed_data_provider,
210              [&] {
211                  const CTransaction transaction{random_mutable_transaction};
212                  bool is_spent = false;
213                  for (const CTxOut& tx_out : transaction.vout) {
214                      if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
215                          is_spent = true;
216                      }
217                  }
218                  if (is_spent) {
219                      // Avoid:
220                      // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
221                      return;
222                  }
223                  bool expected_code_path = false;
224                  const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
225                  const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
226                  try {
227                      AddCoins(coins_view_cache, transaction, height, possible_overwrite);
228                      expected_code_path = true;
229                  } catch (const std::logic_error& e) {
230                      if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
231                          assert(!possible_overwrite);
232                          expected_code_path = true;
233                      }
234                  }
235                  assert(expected_code_path);
236              },
237              [&] {
238                  (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
239              },
240              [&] {
241                  TxValidationState state;
242                  CAmount tx_fee_out;
243                  const CTransaction transaction{random_mutable_transaction};
244                  if (ContainsSpentInput(transaction, coins_view_cache)) {
245                      // Avoid:
246                      // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
247                      return;
248                  }
249                  TxValidationState dummy;
250                  if (!CheckTransaction(transaction, dummy)) {
251                      // It is not allowed to call CheckTxInputs if CheckTransaction failed
252                      return;
253                  }
254                  if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
255                      assert(MoneyRange(tx_fee_out));
256                  }
257              },
258              [&] {
259                  const CTransaction transaction{random_mutable_transaction};
260                  if (ContainsSpentInput(transaction, coins_view_cache)) {
261                      // Avoid:
262                      // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
263                      return;
264                  }
265                  (void)GetP2SHSigOpCount(transaction, coins_view_cache);
266              },
267              [&] {
268                  const CTransaction transaction{random_mutable_transaction};
269                  if (ContainsSpentInput(transaction, coins_view_cache)) {
270                      // Avoid:
271                      // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
272                      return;
273                  }
274                  const auto flags{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
275                  if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
276                      // Avoid:
277                      // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness *, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
278                      return;
279                  }
280                  (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
281              },
282              [&] {
283                  (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
284              });
285      }
286  }