Bitcoin Core 31.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 <kernel/cs_main.h>
11#include <policy/policy.h>
13#include <script/interpreter.h>
15#include <test/fuzz/fuzz.h>
16#include <test/fuzz/util.h>
18#include <txdb.h>
19#include <util/hasher.h>
20
21#include <cassert>
22#include <algorithm>
23#include <cstdint>
24#include <functional>
25#include <limits>
26#include <memory>
27#include <optional>
28#include <ranges>
29#include <stdexcept>
30#include <string>
31#include <utility>
32#include <vector>
33
34namespace {
35const Coin EMPTY_COIN{};
36
37bool 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
50class MutationGuardCoinsViewCache final : public CCoinsViewCache
51{
52private:
53 struct CacheCoinSnapshot {
54 COutPoint outpoint;
55 bool dirty{false};
56 bool fresh{false};
57 Coin coin;
58 bool operator==(const CacheCoinSnapshot&) const = default;
59 };
60
61 std::vector<CacheCoinSnapshot> ComputeCacheCoinsSnapshot() const
62 {
63 std::vector<CacheCoinSnapshot> snapshot;
64 snapshot.reserve(cacheCoins.size());
65
66 for (const auto& [outpoint, entry] : cacheCoins) {
67 snapshot.emplace_back(outpoint, entry.IsDirty(), entry.IsFresh(), entry.coin);
68 }
69
70 std::ranges::sort(snapshot, std::less<>{}, &CacheCoinSnapshot::outpoint);
71 return snapshot;
72 }
73
74 mutable std::vector<CacheCoinSnapshot> m_expected_snapshot{ComputeCacheCoinsSnapshot()};
75
76public:
77 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override
78 {
79 // Nothing must modify cacheCoins other than BatchWrite.
80 assert(ComputeCacheCoinsSnapshot() == m_expected_snapshot);
81 CCoinsViewCache::BatchWrite(cursor, block_hash);
82 m_expected_snapshot = ComputeCacheCoinsSnapshot();
83 }
84
86};
87} // namespace
88
90{
91 static const auto testing_setup = MakeNoLogFileContext<>();
92}
93
95{
96 auto* const db{dynamic_cast<CCoinsViewDB*>(backend_coins_view)};
97 const bool is_db{db != nullptr};
98 bool good_data{true};
99 auto* original_backend{backend_coins_view};
100
101 if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
102 COutPoint random_out_point;
103 Coin random_coin;
104 CMutableTransaction random_mutable_transaction;
105 LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
106 {
107 CallOneOf(
109 [&] {
110 if (random_coin.IsSpent()) {
111 return;
112 }
113 COutPoint outpoint{random_out_point};
114 Coin coin{random_coin};
116 // We can only skip the check if no unspent coin exists for this outpoint.
117 const bool possible_overwrite{coins_view_cache.PeekCoin(outpoint) || fuzzed_data_provider.ConsumeBool()};
118 coins_view_cache.AddCoin(outpoint, std::move(coin), possible_overwrite);
119 } else {
120 coins_view_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
121 }
122 },
123 [&] {
124 coins_view_cache.Flush(/*reallocate_cache=*/fuzzed_data_provider.ConsumeBool());
125 },
126 [&] {
127 coins_view_cache.Sync();
128 },
129 [&] {
130 if (db) WITH_LOCK(::cs_main, (void)db->CompactFullAsync());
131 },
132 [&] {
134 // `CCoinsViewDB::BatchWrite()` requires a non-null best block.
135 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
136 coins_view_cache.SetBestBlock(best_block);
137 },
138 [&] {
139 (void)coins_view_cache.CreateResetGuard();
140 // Reset() clears the best block, so reseed db-backed caches.
141 if (is_db) {
143 if (best_block.IsNull()) {
144 good_data = false;
145 return;
146 }
147 coins_view_cache.SetBestBlock(best_block);
148 }
149 },
150 [&] {
151 Coin move_to;
152 (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
153 },
154 [&] {
155 coins_view_cache.Uncache(random_out_point);
156 },
157 [&] {
158 const bool use_original_backend{fuzzed_data_provider.ConsumeBool()};
159 if (use_original_backend && backend_coins_view != original_backend) {
160 // FRESH flags valid against the empty backend may be invalid
161 // against the original backend, so reset before restoring it.
162 (void)coins_view_cache.CreateResetGuard();
163 // Reset() clears the best block; db backends require a non-null hash.
164 if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
165 }
166 backend_coins_view = use_original_backend ? original_backend : &CoinsViewEmpty::Get();
167 coins_view_cache.SetBackend(*backend_coins_view);
168 },
169 [&] {
170 const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
171 if (!opt_out_point) {
172 good_data = false;
173 return;
174 }
175 random_out_point = *opt_out_point;
176 },
177 [&] {
178 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
179 if (!opt_coin) {
180 good_data = false;
181 return;
182 }
183 random_coin = *opt_coin;
184 },
185 [&] {
186 const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
187 if (!opt_mutable_transaction) {
188 good_data = false;
189 return;
190 }
191 random_mutable_transaction = *opt_mutable_transaction;
192 },
193 [&] {
194 CoinsCachePair sentinel{};
195 sentinel.second.SelfRef(sentinel);
196 size_t dirty_count{0};
198 CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
199 LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
200 {
201 CCoinsCacheEntry coins_cache_entry;
203 coins_cache_entry.coin = random_coin;
204 } else {
205 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
206 if (!opt_coin) {
207 good_data = false;
208 return;
209 }
210 coins_cache_entry.coin = *opt_coin;
211 }
212 // Avoid setting FRESH for an outpoint that already exists unspent in the parent view.
213 bool fresh{!coins_view_cache.PeekCoin(random_out_point) && fuzzed_data_provider.ConsumeBool()};
214 bool dirty{fresh || fuzzed_data_provider.ConsumeBool()};
215 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
216 if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
217 if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
218 dirty_count += dirty;
219 }
220 auto cursor{CoinsViewCacheCursor(dirty_count, sentinel, coins_map, /*will_erase=*/true)};
221 uint256 best_block{coins_view_cache.GetBestBlock()};
223 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
224 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
225 coins_view_cache.BatchWrite(cursor, best_block);
226 });
227 }
228
229 {
230 bool expected_code_path = false;
231 try {
232 (void)coins_view_cache.Cursor();
233 } catch (const std::logic_error&) {
234 expected_code_path = true;
235 }
236 assert(expected_code_path);
237 (void)coins_view_cache.DynamicMemoryUsage();
238 (void)coins_view_cache.EstimateSize();
239 (void)coins_view_cache.GetBestBlock();
240 (void)coins_view_cache.GetCacheSize();
241 (void)coins_view_cache.GetHeadBlocks();
242 (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
243 }
244
245 {
246 if (is_db && backend_coins_view == original_backend) {
247 assert(backend_coins_view->Cursor());
248 }
249 (void)backend_coins_view->EstimateSize();
250 (void)backend_coins_view->GetBestBlock();
251 (void)backend_coins_view->GetHeadBlocks();
252 }
253
255 CallOneOf(
257 [&] {
258 const CTransaction transaction{random_mutable_transaction};
259 bool is_spent = false;
260 for (const CTxOut& tx_out : transaction.vout) {
261 if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
262 is_spent = true;
263 }
264 }
265 if (is_spent) {
266 // Avoid:
267 // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
268 return;
269 }
270 const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
271 const bool check_for_overwrite{transaction.IsCoinBase() || [&] {
272 for (uint32_t i{0}; i < transaction.vout.size(); ++i) {
273 if (coins_view_cache.PeekCoin(COutPoint{transaction.GetHash(), i})) return true;
274 }
276 }()}; // We can only skip the check if the current txid has no unspent outputs
277 AddCoins(coins_view_cache, transaction, height, check_for_overwrite);
278 },
279 [&] {
280 (void)ValidateInputsStandardness(CTransaction{random_mutable_transaction}, coins_view_cache);
281 },
282 [&] {
283 TxValidationState state;
284 CAmount tx_fee_out;
285 const CTransaction transaction{random_mutable_transaction};
286 if (ContainsSpentInput(transaction, coins_view_cache)) {
287 // Avoid:
288 // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
289 return;
290 }
291 TxValidationState dummy;
292 if (!CheckTransaction(transaction, dummy)) {
293 // It is not allowed to call CheckTxInputs if CheckTransaction failed
294 return;
295 }
296 if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
297 assert(MoneyRange(tx_fee_out));
298 }
299 },
300 [&] {
301 const CTransaction transaction{random_mutable_transaction};
302 if (ContainsSpentInput(transaction, coins_view_cache)) {
303 // Avoid:
304 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
305 return;
306 }
307 (void)GetP2SHSigOpCount(transaction, coins_view_cache);
308 },
309 [&] {
310 const CTransaction transaction{random_mutable_transaction};
311 if (ContainsSpentInput(transaction, coins_view_cache)) {
312 // Avoid:
313 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
314 return;
315 }
317 if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
318 // Avoid:
319 // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness &, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
320 return;
321 }
322 (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
323 },
324 [&] {
325 (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
326 });
327 }
328
329 {
330 const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
331 const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
332 const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
333 const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
334 if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
335 assert(*coin == coin_using_access_coin);
336 assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
337 } else {
338 assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
339 }
340 // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
341 const bool exists_using_have_coin_in_backend = backend_coins_view->HaveCoin(random_out_point);
342 if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
343 assert(exists_using_have_coin);
344 }
345 if (auto coin{backend_coins_view->GetCoin(random_out_point)}) {
346 assert(exists_using_have_coin_in_backend);
347 // Note we can't assert that `coin_using_get_coin == *coin` because the coin in
348 // the cache may have been modified but not yet flushed.
349 } else {
350 assert(!exists_using_have_coin_in_backend);
351 }
352 }
353}
354
356{
357 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
358 CCoinsViewCache coins_view_cache{&CoinsViewEmpty::Get(), /*deterministic=*/true};
360}
361
363{
364 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
365 auto db_params = DBParams{
366 .path = "",
367 .cache_bytes = 1_MiB,
368 .memory_only = true,
369 };
370 CCoinsViewDB backend_coins_view{std::move(db_params), CoinsViewOptions{}};
371 CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
372 TestCoinsView(fuzzed_data_provider, coins_view_cache, &backend_coins_view);
373}
374
375// Creates a CoinsViewOverlay and a MutationGuardCoinsViewCache as the base.
376// This allows us to exercise all methods on a CoinsViewOverlay, while also
377// ensuring that nothing can mutate the underlying cache until Flush or Sync is
378// called.
380{
381 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
382 MutationGuardCoinsViewCache backend_cache{&CoinsViewEmpty::Get(), /*deterministic=*/true};
383 CoinsViewOverlay coins_view_cache{&backend_cache, /*deterministic=*/true};
384 TestCoinsView(fuzzed_data_provider, coins_view_cache, &backend_cache);
385}
bool MoneyRange(const CAmount &nValue)
Definition: amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
if(!SetupNetworking())
int flags
Definition: bitcoin-tx.cpp:530
void SetBackend(CCoinsView &in_view)
Definition: coins.h:379
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:394
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:272
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:132
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
Definition: coins.h:545
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:291
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:68
CCoinsViewCache(CCoinsView *in_base, bool deterministic=false)
Definition: coins.cpp:31
void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:260
void SetBestBlock(const uint256 &block_hash)
Definition: coins.cpp:184
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:178
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:189
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
Definition: coins.cpp:23
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:111
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:37
Pure abstract view on the open txout dataset.
Definition: coins.h:308
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:35
CTxOut out
unspent transaction output
Definition: coins.h:38
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:83
bool fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:41
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:44
static CoinsViewEmpty & Get()
Definition: coins.cpp:17
CCoinsViewCache overlay that avoids populating/mutating parent cache layers on cache misses.
Definition: coins.h:565
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:196
static const uint256 ONE
Definition: uint256.h:205
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:121
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:93
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:224
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:226
void TestCoinsView(FuzzedDataProvider &fuzzed_data_provider, CCoinsViewCache &coins_view_cache, CCoinsView *backend_coins_view)
Definition: coins_view.cpp:94
FUZZ_TARGET(coins_view,.init=initialize_coins_view)
Definition: coins_view.cpp:355
void initialize_coins_view()
Definition: coins_view.cpp:89
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
#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
Definition: basic.cpp:8
bool operator==(const CNetAddr &a, const CNetAddr &b)
Definition: netaddress.cpp:603
TxValidationState ValidateInputsStandardness(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check transaction inputs.
Definition: policy.cpp:214
bool IsWitnessStandard(const CTransaction &tx, const CCoinsViewCache &mapInputs)
Check if the transaction is over standard P2WSH resources limit: 3600bytes witnessScript size,...
Definition: policy.cpp:265
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:110
Coin coin
Definition: coins.h:142
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:173
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:172
A mutable version of CTransaction.
Definition: transaction.h:358
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:261
User-controlled performance and debug options.
Definition: txdb.h:28
Application-specific storage settings.
Definition: dbwrapper.h:38
fs::path path
Location in the filesystem where leveldb data will be stored.
Definition: dbwrapper.h:40
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:299
CDBWrapper db
Definition: dbwrapper.cpp:372
bool ContainsSpentInput(const CTransaction &tx, const CCoinsViewCache &inputs) noexcept
Definition: util.cpp:240
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:191
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:37
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:39