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