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