Bitcoin Core 30.99.0
P2P Digital Currency
coins_view.cpp
Go to the documentation of this file.
1// Copyright (c) 2020-present 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>
10#include <policy/policy.h>
12#include <script/interpreter.h>
14#include <test/fuzz/fuzz.h>
15#include <test/fuzz/util.h>
17#include <txdb.h>
18#include <util/hasher.h>
19
20#include <cassert>
21#include <cstdint>
22#include <limits>
23#include <memory>
24#include <optional>
25#include <stdexcept>
26#include <string>
27#include <utility>
28#include <vector>
29
30namespace {
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<>();
43}
44
45void TestCoinsView(FuzzedDataProvider& fuzzed_data_provider, CCoinsView& backend_coins_view, bool is_db)
46{
47 bool good_data{true};
48
49 CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
50 if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
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 {
58 [&] {
59 if (random_coin.IsSpent()) {
60 return;
61 }
62 COutPoint outpoint{random_out_point};
63 Coin coin{random_coin};
65 const bool possible_overwrite{fuzzed_data_provider.ConsumeBool()};
66 try {
67 coins_view_cache.AddCoin(outpoint, std::move(coin), possible_overwrite);
68 } catch (const std::logic_error& e) {
69 assert(e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"});
70 assert(!possible_overwrite);
71 }
72 } else {
73 coins_view_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
74 }
75 },
76 [&] {
77 coins_view_cache.Flush(/*reallocate_cache=*/fuzzed_data_provider.ConsumeBool());
78 },
79 [&] {
80 coins_view_cache.Sync();
81 },
82 [&] {
84 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
85 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
86 coins_view_cache.SetBestBlock(best_block);
87 },
88 [&] {
89 {
90 const auto reset_guard{coins_view_cache.CreateResetGuard()};
91 }
92 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
93 if (is_db) {
95 if (best_block.IsNull()) {
96 good_data = false;
97 return;
98 }
99 coins_view_cache.SetBestBlock(best_block);
100 }
101 },
102 [&] {
103 Coin move_to;
104 (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
105 },
106 [&] {
107 coins_view_cache.Uncache(random_out_point);
108 },
109 [&] {
111 backend_coins_view = CCoinsView{};
112 }
113 coins_view_cache.SetBackend(backend_coins_view);
114 },
115 [&] {
116 const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
117 if (!opt_out_point) {
118 good_data = false;
119 return;
120 }
121 random_out_point = *opt_out_point;
122 },
123 [&] {
124 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
125 if (!opt_coin) {
126 good_data = false;
127 return;
128 }
129 random_coin = *opt_coin;
130 },
131 [&] {
132 const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
133 if (!opt_mutable_transaction) {
134 good_data = false;
135 return;
136 }
137 random_mutable_transaction = *opt_mutable_transaction;
138 },
139 [&] {
140 CoinsCachePair sentinel{};
141 sentinel.second.SelfRef(sentinel);
143 CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
144 LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
145 {
146 CCoinsCacheEntry coins_cache_entry;
147 const auto dirty{fuzzed_data_provider.ConsumeBool()};
148 const auto fresh{fuzzed_data_provider.ConsumeBool()};
150 coins_cache_entry.coin = random_coin;
151 } else {
152 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
153 if (!opt_coin) {
154 good_data = false;
155 return;
156 }
157 coins_cache_entry.coin = *opt_coin;
158 }
159 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
160 if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
161 if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
162 }
163 bool expected_code_path = false;
164 try {
165 auto cursor{CoinsViewCacheCursor(sentinel, coins_map, /*will_erase=*/true)};
166 uint256 best_block{coins_view_cache.GetBestBlock()};
168 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
169 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
170 coins_view_cache.BatchWrite(cursor, best_block);
171 expected_code_path = true;
172 } catch (const std::logic_error& e) {
173 if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
174 expected_code_path = true;
175 }
176 }
177 assert(expected_code_path);
178 });
179 }
180
181 {
182 const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
183 const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
184 const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
185 const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
186 if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
187 assert(*coin == coin_using_access_coin);
188 assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
189 } else {
190 assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
191 }
192 // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
193 const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
194 if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
195 assert(exists_using_have_coin);
196 }
197 if (auto coin{backend_coins_view.GetCoin(random_out_point)}) {
198 assert(exists_using_have_coin_in_backend);
199 // Note we can't assert that `coin_using_get_coin == *coin` because the coin in
200 // the cache may have been modified but not yet flushed.
201 } else {
202 assert(!exists_using_have_coin_in_backend);
203 }
204 }
205
206 {
207 bool expected_code_path = false;
208 try {
209 (void)coins_view_cache.Cursor();
210 } catch (const std::logic_error&) {
211 expected_code_path = true;
212 }
213 assert(expected_code_path);
214 (void)coins_view_cache.DynamicMemoryUsage();
215 (void)coins_view_cache.EstimateSize();
216 (void)coins_view_cache.GetBestBlock();
217 (void)coins_view_cache.GetCacheSize();
218 (void)coins_view_cache.GetHeadBlocks();
219 (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
220 }
221
222 {
223 std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
224 assert(is_db == !!coins_view_cursor);
225 (void)backend_coins_view.EstimateSize();
226 (void)backend_coins_view.GetBestBlock();
227 (void)backend_coins_view.GetHeadBlocks();
228 }
229
231 CallOneOf(
233 [&] {
234 const CTransaction transaction{random_mutable_transaction};
235 bool is_spent = false;
236 for (const CTxOut& tx_out : transaction.vout) {
237 if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
238 is_spent = true;
239 }
240 }
241 if (is_spent) {
242 // Avoid:
243 // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
244 return;
245 }
246 bool expected_code_path = false;
247 const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
248 const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
249 try {
250 AddCoins(coins_view_cache, transaction, height, possible_overwrite);
251 expected_code_path = true;
252 } catch (const std::logic_error& e) {
253 if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
254 assert(!possible_overwrite);
255 expected_code_path = true;
256 }
257 }
258 assert(expected_code_path);
259 },
260 [&] {
261 (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
262 },
263 [&] {
264 TxValidationState state;
265 CAmount tx_fee_out;
266 const CTransaction transaction{random_mutable_transaction};
267 if (ContainsSpentInput(transaction, coins_view_cache)) {
268 // Avoid:
269 // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
270 return;
271 }
272 TxValidationState dummy;
273 if (!CheckTransaction(transaction, dummy)) {
274 // It is not allowed to call CheckTxInputs if CheckTransaction failed
275 return;
276 }
277 if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
278 assert(MoneyRange(tx_fee_out));
279 }
280 },
281 [&] {
282 const CTransaction transaction{random_mutable_transaction};
283 if (ContainsSpentInput(transaction, coins_view_cache)) {
284 // Avoid:
285 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
286 return;
287 }
288 (void)GetP2SHSigOpCount(transaction, coins_view_cache);
289 },
290 [&] {
291 const CTransaction transaction{random_mutable_transaction};
292 if (ContainsSpentInput(transaction, coins_view_cache)) {
293 // Avoid:
294 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
295 return;
296 }
298 if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
299 // Avoid:
300 // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness &, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
301 return;
302 }
303 (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
304 },
305 [&] {
306 (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
307 });
308 }
309}
310
312{
313 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
314 CCoinsView backend_coins_view;
315 TestCoinsView(fuzzed_data_provider, backend_coins_view, /*is_db=*/false);
316}
317
319{
320 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
321 auto db_params = DBParams{
322 .path = "",
323 .cache_bytes = 1_MiB,
324 .memory_only = true,
325 };
326 CCoinsViewDB coins_db{std::move(db_params), CoinsViewOptions{}};
327 TestCoinsView(fuzzed_data_provider, coins_db, /*is_db=*/true);
328}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
if(!SetupNetworking())
catch(const std::exception &e)
int flags
Definition: bitcoin-tx.cpp:529
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:355
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:35
Abstract view on the open txout dataset.
Definition: coins.h:302
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
An output of a transaction.
Definition: transaction.h:140
A UTXO entry.
Definition: coins.h:34
CTxOut out
unspent transaction output
Definition: coins.h:37
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:82
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:43
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:40
T ConsumeIntegralInRange(T min, T max)
static constexpr script_verify_flags from_int(value_type f)
Definition: verify_flags.h:35
256-bit opaque blob.
Definition: uint256.h:195
static const uint256 ONE
Definition: uint256.h:204
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:124
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:92
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< CoinsCachePair, sizeof(CoinsCachePair)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
Definition: coins.h:223
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:225
void TestCoinsView(FuzzedDataProvider &fuzzed_data_provider, CCoinsView &backend_coins_view, bool is_db)
Definition: coins_view.cpp:45
FUZZ_TARGET(coins_view,.init=initialize_coins_view)
Definition: coins_view.cpp:311
void initialize_coins_view()
Definition: coins_view.cpp:40
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
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
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:603
bool AreInputsStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
Definition: policy.cpp:213
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:251
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:109
Coin coin
Definition: coins.h:141
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:172
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:171
A mutable version of CTransaction.
Definition: transaction.h:358
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:260
User-controlled performance and debug options.
Definition: txdb.h:26
Application-specific storage settings.
Definition: dbwrapper.h:33
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:35
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
Definition: util.cpp:245
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:172
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
int64_t GetTransactionSigOpCost(const CTransaction &tx, const CCoinsViewCache &inputs, script_verify_flags flags)
Compute total signature operation cost of a transaction.
Definition: tx_verify.cpp:143
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
Definition: tx_verify.cpp:126
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition: fees.cpp:38