Bitcoin Core 31.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
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 <algorithm>
22#include <cstdint>
23#include <functional>
24#include <limits>
25#include <memory>
26#include <optional>
27#include <ranges>
28#include <stdexcept>
29#include <string>
30#include <utility>
31#include <vector>
32
33namespace {
34const Coin EMPTY_COIN{};
35
36bool operator==(const Coin& a, const Coin& b)
37{
38 if (a.IsSpent() && b.IsSpent()) return true;
39 return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out;
40}
41
49class MutationGuardCoinsViewCache final : public CCoinsViewCache
50{
51private:
52 struct CacheCoinSnapshot {
53 COutPoint outpoint;
54 bool dirty{false};
55 bool fresh{false};
56 Coin coin;
57 bool operator==(const CacheCoinSnapshot&) const = default;
58 };
59
60 std::vector<CacheCoinSnapshot> ComputeCacheCoinsSnapshot() const
61 {
62 std::vector<CacheCoinSnapshot> snapshot;
63 snapshot.reserve(cacheCoins.size());
64
65 for (const auto& [outpoint, entry] : cacheCoins) {
66 snapshot.emplace_back(outpoint, entry.IsDirty(), entry.IsFresh(), entry.coin);
67 }
68
69 std::ranges::sort(snapshot, std::less<>{}, &CacheCoinSnapshot::outpoint);
70 return snapshot;
71 }
72
73 mutable std::vector<CacheCoinSnapshot> m_expected_snapshot{ComputeCacheCoinsSnapshot()};
74
75public:
76 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override
77 {
78 // Nothing must modify cacheCoins other than BatchWrite.
79 assert(ComputeCacheCoinsSnapshot() == m_expected_snapshot);
81 m_expected_snapshot = ComputeCacheCoinsSnapshot();
82 }
83
85};
86} // namespace
87
89{
90 static const auto testing_setup = MakeNoLogFileContext<>();
91}
92
94{
95 bool good_data{true};
96
97 if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
102 {
103 CallOneOf(
105 [&] {
106 if (random_coin.IsSpent()) {
107 return;
108 }
109 COutPoint outpoint{random_out_point};
110 Coin coin{random_coin};
112 // We can only skip the check if no unspent coin exists for this outpoint.
113 const bool possible_overwrite{coins_view_cache.PeekCoin(outpoint) || fuzzed_data_provider.ConsumeBool()};
114 coins_view_cache.AddCoin(outpoint, std::move(coin), possible_overwrite);
115 } else {
116 coins_view_cache.EmplaceCoinInternalDANGER(std::move(outpoint), std::move(coin));
117 }
118 },
119 [&] {
120 coins_view_cache.Flush(/*reallocate_cache=*/fuzzed_data_provider.ConsumeBool());
121 },
122 [&] {
123 coins_view_cache.Sync();
124 },
125 [&] {
127 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
128 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
129 coins_view_cache.SetBestBlock(best_block);
130 },
131 [&] {
132 {
133 const auto reset_guard{coins_view_cache.CreateResetGuard()};
134 }
135 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
136 if (is_db) {
138 if (best_block.IsNull()) {
139 good_data = false;
140 return;
141 }
142 coins_view_cache.SetBestBlock(best_block);
143 }
144 },
145 [&] {
148 },
149 [&] {
151 },
152 [&] {
155 }
157 },
158 [&] {
160 if (!opt_out_point) {
161 good_data = false;
162 return;
163 }
165 },
166 [&] {
167 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
168 if (!opt_coin) {
169 good_data = false;
170 return;
171 }
173 },
174 [&] {
177 good_data = false;
178 return;
179 }
181 },
182 [&] {
184 sentinel.second.SelfRef(sentinel);
185 size_t dirty_count{0};
187 CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
189 {
193 } else {
194 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
195 if (!opt_coin) {
196 good_data = false;
197 return;
198 }
200 }
201 // Avoid setting FRESH for an outpoint that already exists unspent in the parent view.
203 bool dirty{fresh || fuzzed_data_provider.ConsumeBool()};
204 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
205 if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
206 if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
207 dirty_count += dirty;
208 }
209 auto cursor{CoinsViewCacheCursor(dirty_count, sentinel, coins_map, /*will_erase=*/true)};
210 uint256 best_block{coins_view_cache.GetBestBlock()};
212 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
213 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
215 });
216 }
217
218 {
219 bool expected_code_path = false;
220 try {
221 (void)coins_view_cache.Cursor();
222 } catch (const std::logic_error&) {
223 expected_code_path = true;
224 }
226 (void)coins_view_cache.DynamicMemoryUsage();
227 (void)coins_view_cache.EstimateSize();
228 (void)coins_view_cache.GetBestBlock();
229 (void)coins_view_cache.GetCacheSize();
230 (void)coins_view_cache.GetHeadBlocks();
232 }
233
234 {
235 if (is_db) {
236 std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
238 }
239 (void)backend_coins_view.EstimateSize();
240 (void)backend_coins_view.GetBestBlock();
241 (void)backend_coins_view.GetHeadBlocks();
242 }
243
245 CallOneOf(
247 [&] {
249 bool is_spent = false;
250 for (const CTxOut& tx_out : transaction.vout) {
251 if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
252 is_spent = true;
253 }
254 }
255 if (is_spent) {
256 // Avoid:
257 // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
258 return;
259 }
260 const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
261 const bool check_for_overwrite{transaction.IsCoinBase() || [&] {
262 for (uint32_t i{0}; i < transaction.vout.size(); ++i) {
263 if (coins_view_cache.PeekCoin(COutPoint{transaction.GetHash(), i})) return true;
264 }
266 }()}; // We can only skip the check if the current txid has no unspent outputs
268 },
269 [&] {
271 },
272 [&] {
273 TxValidationState state;
277 // Avoid:
278 // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
279 return;
280 }
281 TxValidationState dummy;
282 if (!CheckTransaction(transaction, dummy)) {
283 // It is not allowed to call CheckTxInputs if CheckTransaction failed
284 return;
285 }
286 if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
288 }
289 },
290 [&] {
293 // Avoid:
294 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
295 return;
296 }
298 },
299 [&] {
302 // Avoid:
303 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
304 return;
305 }
307 if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
308 // Avoid:
309 // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness &, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
310 return;
311 }
313 },
314 [&] {
316 });
317 }
318
319 {
324 if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
327 } else {
329 }
330 // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
334 }
335 if (auto coin{backend_coins_view.GetCoin(random_out_point)}) {
337 // Note we can't assert that `coin_using_get_coin == *coin` because the coin in
338 // the cache may have been modified but not yet flushed.
339 } else {
341 }
342 }
343}
344
352
354{
355 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
356 auto db_params = DBParams{
357 .path = "",
358 .cache_bytes = 1_MiB,
359 .memory_only = true,
360 };
362 CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
364}
365
366// Creates a CoinsViewOverlay and a MutationGuardCoinsViewCache as the base.
367// This allows us to exercise all methods on a CoinsViewOverlay, while also
368// ensuring that nothing can mutate the underlying cache until Flush or Sync is
369// called.
371{
372 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
374 MutationGuardCoinsViewCache backend_cache{&backend_base_coins_view, /*deterministic=*/true};
375 CoinsViewOverlay coins_view_cache{&backend_cache, /*deterministic=*/true};
377}
bool MoneyRange(const CAmount &nValue)
Definition amount.h:27
int64_t CAmount
Amount in satoshis (Can be negative)
Definition amount.h:12
int flags
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:368
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition coins.cpp:52
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition coins.cpp:208
CCoinsView backed by the coin database (chainstate/)
Definition txdb.h:35
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.
bool IsCoinBase() const
An output of a transaction.
A UTXO entry.
Definition coins.h:35
bool IsCoinBase() const
Definition coins.h:59
CTxOut out
unspent transaction output
Definition coins.h:38
bool IsSpent() const
Either this coin never existed (see e.g.
Definition coins.h:83
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition coins.h:44
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition coins.h:41
CCoinsViewCache overlay that avoids populating/mutating parent cache layers on cache misses.
Definition coins.h:539
T ConsumeIntegralInRange(T min, T max)
static constexpr script_verify_flags from_int(value_type f)
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:142
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:219
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition coins.h:226
void initialize_coins_view()
void TestCoinsView(FuzzedDataProvider &fuzzed_data_provider, CCoinsViewCache &coins_view_cache, CCoinsView &backend_coins_view, bool is_db)
#define FUZZ_TARGET(...)
Definition fuzz.h:35
#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...
bool operator==(const CNetAddr &a, const CNetAddr &b)
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
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.
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: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:167
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.
unsigned int GetP2SHSigOpCount(const CTransaction &tx, const CCoinsViewCache &inputs)
Count ECDSA signature operations in pay-to-script-hash inputs.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:73
assert(!tx.IsCoinBase())
FuzzedDataProvider & fuzzed_data_provider
Definition fees.cpp:38