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 (void)coins_view_cache.Flush();
78 },
79 [&] {
80 (void)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 Coin move_to;
90 (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
91 },
92 [&] {
93 coins_view_cache.Uncache(random_out_point);
94 },
95 [&] {
97 backend_coins_view = CCoinsView{};
98 }
99 coins_view_cache.SetBackend(backend_coins_view);
100 },
101 [&] {
102 const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
103 if (!opt_out_point) {
104 good_data = false;
105 return;
106 }
107 random_out_point = *opt_out_point;
108 },
109 [&] {
110 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
111 if (!opt_coin) {
112 good_data = false;
113 return;
114 }
115 random_coin = *opt_coin;
116 },
117 [&] {
118 const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
119 if (!opt_mutable_transaction) {
120 good_data = false;
121 return;
122 }
123 random_mutable_transaction = *opt_mutable_transaction;
124 },
125 [&] {
126 CoinsCachePair sentinel{};
127 sentinel.second.SelfRef(sentinel);
129 CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
130 LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
131 {
132 CCoinsCacheEntry coins_cache_entry;
133 const auto dirty{fuzzed_data_provider.ConsumeBool()};
134 const auto fresh{fuzzed_data_provider.ConsumeBool()};
136 coins_cache_entry.coin = random_coin;
137 } else {
138 const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
139 if (!opt_coin) {
140 good_data = false;
141 return;
142 }
143 coins_cache_entry.coin = *opt_coin;
144 }
145 auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
146 if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
147 if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
148 }
149 bool expected_code_path = false;
150 try {
151 auto cursor{CoinsViewCacheCursor(sentinel, coins_map, /*will_erase=*/true)};
152 uint256 best_block{coins_view_cache.GetBestBlock()};
154 // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
155 if (is_db && best_block.IsNull()) best_block = uint256::ONE;
156 coins_view_cache.BatchWrite(cursor, best_block);
157 expected_code_path = true;
158 } catch (const std::logic_error& e) {
159 if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
160 expected_code_path = true;
161 }
162 }
163 assert(expected_code_path);
164 });
165 }
166
167 {
168 const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
169 const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
170 const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
171 const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
172 if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
173 assert(*coin == coin_using_access_coin);
174 assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
175 } else {
176 assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
177 }
178 // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
179 const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
180 if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
181 assert(exists_using_have_coin);
182 }
183 if (auto coin{backend_coins_view.GetCoin(random_out_point)}) {
184 assert(exists_using_have_coin_in_backend);
185 // Note we can't assert that `coin_using_get_coin == *coin` because the coin in
186 // the cache may have been modified but not yet flushed.
187 } else {
188 assert(!exists_using_have_coin_in_backend);
189 }
190 }
191
192 {
193 bool expected_code_path = false;
194 try {
195 (void)coins_view_cache.Cursor();
196 } catch (const std::logic_error&) {
197 expected_code_path = true;
198 }
199 assert(expected_code_path);
200 (void)coins_view_cache.DynamicMemoryUsage();
201 (void)coins_view_cache.EstimateSize();
202 (void)coins_view_cache.GetBestBlock();
203 (void)coins_view_cache.GetCacheSize();
204 (void)coins_view_cache.GetHeadBlocks();
205 (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
206 }
207
208 {
209 std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
210 assert(is_db == !!coins_view_cursor);
211 (void)backend_coins_view.EstimateSize();
212 (void)backend_coins_view.GetBestBlock();
213 (void)backend_coins_view.GetHeadBlocks();
214 }
215
217 CallOneOf(
219 [&] {
220 const CTransaction transaction{random_mutable_transaction};
221 bool is_spent = false;
222 for (const CTxOut& tx_out : transaction.vout) {
223 if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
224 is_spent = true;
225 }
226 }
227 if (is_spent) {
228 // Avoid:
229 // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
230 return;
231 }
232 bool expected_code_path = false;
233 const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
234 const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
235 try {
236 AddCoins(coins_view_cache, transaction, height, possible_overwrite);
237 expected_code_path = true;
238 } catch (const std::logic_error& e) {
239 if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
240 assert(!possible_overwrite);
241 expected_code_path = true;
242 }
243 }
244 assert(expected_code_path);
245 },
246 [&] {
247 (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
248 },
249 [&] {
250 TxValidationState state;
251 CAmount tx_fee_out;
252 const CTransaction transaction{random_mutable_transaction};
253 if (ContainsSpentInput(transaction, coins_view_cache)) {
254 // Avoid:
255 // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
256 return;
257 }
258 TxValidationState dummy;
259 if (!CheckTransaction(transaction, dummy)) {
260 // It is not allowed to call CheckTxInputs if CheckTransaction failed
261 return;
262 }
263 if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
264 assert(MoneyRange(tx_fee_out));
265 }
266 },
267 [&] {
268 const CTransaction transaction{random_mutable_transaction};
269 if (ContainsSpentInput(transaction, coins_view_cache)) {
270 // Avoid:
271 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
272 return;
273 }
274 (void)GetP2SHSigOpCount(transaction, coins_view_cache);
275 },
276 [&] {
277 const CTransaction transaction{random_mutable_transaction};
278 if (ContainsSpentInput(transaction, coins_view_cache)) {
279 // Avoid:
280 // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
281 return;
282 }
284 if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
285 // Avoid:
286 // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness *, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
287 return;
288 }
289 (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
290 },
291 [&] {
292 (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
293 });
294 }
295}
296
298{
299 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
300 CCoinsView backend_coins_view;
301 TestCoinsView(fuzzed_data_provider, backend_coins_view, /*is_db=*/false);
302}
303
305{
306 FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
307 auto db_params = DBParams{
308 .path = "",
309 .cache_bytes = 1_MiB,
310 .memory_only = true,
311 };
312 CCoinsViewDB coins_db{std::move(db_params), CoinsViewOptions{}};
313 TestCoinsView(fuzzed_data_provider, coins_db, /*is_db=*/true);
314}
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:361
CCoinsView backed by the coin database (chainstate/)
Definition: txdb.h:38
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:296
An output of a transaction.
Definition: transaction.h:150
A UTXO entry.
Definition: coins.h:33
CTxOut out
unspent transaction output
Definition: coins.h:36
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:81
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:42
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:39
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:122
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:91
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:229
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:231
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:297
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:195
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:109
Coin coin
Definition: coins.h:147
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:178
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:177
A mutable version of CTransaction.
Definition: transaction.h:378
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:266
User-controlled performance and debug options.
Definition: txdb.h:28
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:240
uint256 ConsumeUInt256(FuzzedDataProvider &fuzzed_data_provider) noexcept
Definition: util.h:171
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