Branch data Line data Source code
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>
7 : : #include <consensus/tx_check.h>
8 : : #include <consensus/tx_verify.h>
9 : : #include <consensus/validation.h>
10 : : #include <policy/policy.h>
11 : : #include <primitives/transaction.h>
12 : : #include <script/interpreter.h>
13 : : #include <test/fuzz/FuzzedDataProvider.h>
14 : : #include <test/fuzz/fuzz.h>
15 : : #include <test/fuzz/util.h>
16 : : #include <test/util/setup_common.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 : :
30 : : namespace {
31 : : const Coin EMPTY_COIN{};
32 : :
33 : 7311 : bool operator==(const Coin& a, const Coin& b)
34 : : {
35 [ + + - + ]: 7311 : if (a.IsSpent() && b.IsSpent()) return true;
36 [ + + + + : 6110 : return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out;
+ + ]
37 : : }
38 : : } // namespace
39 : :
40 : 2 : void initialize_coins_view()
41 : : {
42 [ + - + - : 2 : static const auto testing_setup = MakeNoLogFileContext<>();
+ - ]
43 : 2 : }
44 : :
45 : 4256 : void TestCoinsView(FuzzedDataProvider& fuzzed_data_provider, CCoinsView& backend_coins_view, bool is_db)
46 : : {
47 : 4256 : bool good_data{true};
48 : :
49 : 4256 : CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
50 [ + + + - ]: 4256 : if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
51 : 4256 : COutPoint random_out_point;
52 : 4256 : Coin random_coin;
53 [ + - ]: 4256 : CMutableTransaction random_mutable_transaction;
54 [ + + + + : 6772410 : LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
+ + ]
55 : : {
56 [ + - ]: 3382204 : CallOneOf(
57 : : fuzzed_data_provider,
58 : 512331 : [&] {
59 [ + + ]: 512331 : if (random_coin.IsSpent()) {
60 : : return;
61 : : }
62 : 484394 : Coin coin = random_coin;
63 : 484394 : bool expected_code_path = false;
64 : 484394 : const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
65 : 484394 : try {
66 [ + + ]: 484394 : coins_view_cache.AddCoin(random_out_point, std::move(coin), possible_overwrite);
67 : : expected_code_path = true;
68 [ - + ]: 12378 : } catch (const std::logic_error& e) {
69 [ + - + - ]: 12378 : if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
70 [ - + ]: 12378 : assert(!possible_overwrite);
71 : 12378 : expected_code_path = true;
72 : : // AddCoin() decreases cachedCoinsUsage by the memory usage of the old coin at the beginning and
73 : : // increases it by the value of the new coin at the end. If it throws in the process, the value
74 : : // of cachedCoinsUsage would have been incorrectly decreased, leading to an underflow later on.
75 : : // To avoid this, use Flush() to reset the value of cachedCoinsUsage in sync with the cacheCoins
76 : : // mapping.
77 [ + - ]: 12378 : (void)coins_view_cache.Flush();
78 : : }
79 : 0 : }
80 : 12378 : assert(expected_code_path);
81 : 484394 : },
82 : 879746 : [&] {
83 : 879746 : (void)coins_view_cache.Flush();
84 : 879746 : },
85 : 1502956 : [&] {
86 : 1502956 : (void)coins_view_cache.Sync();
87 : 1502956 : },
88 : 7884 : [&] {
89 : 7884 : uint256 best_block{ConsumeUInt256(fuzzed_data_provider)};
90 : : // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
91 [ + + + + ]: 13304 : if (is_db && best_block.IsNull()) best_block = uint256::ONE;
92 : 7884 : coins_view_cache.SetBestBlock(best_block);
93 : 7884 : },
94 : 378466 : [&] {
95 : 378466 : Coin move_to;
96 [ + + + - ]: 398009 : (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
97 : 378466 : },
98 : 32146 : [&] {
99 : 32146 : coins_view_cache.Uncache(random_out_point);
100 : 32146 : },
101 : 12451 : [&] {
102 [ + + ]: 12451 : if (fuzzed_data_provider.ConsumeBool()) {
103 : 11505 : backend_coins_view = CCoinsView{};
104 : : }
105 : 12451 : coins_view_cache.SetBackend(backend_coins_view);
106 : 12451 : },
107 : 6188 : [&] {
108 : 6188 : const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
109 [ + + ]: 6188 : if (!opt_out_point) {
110 : 42 : good_data = false;
111 : 42 : return;
112 : : }
113 : 6146 : random_out_point = *opt_out_point;
114 : : },
115 : 14632 : [&] {
116 : 14632 : const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
117 [ + + ]: 14632 : if (!opt_coin) {
118 : 143 : good_data = false;
119 : 143 : return;
120 : : }
121 : 14489 : random_coin = *opt_coin;
122 : 14632 : },
123 : 9940 : [&] {
124 : 9940 : const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
125 [ + + ]: 9940 : if (!opt_mutable_transaction) {
126 : 274 : good_data = false;
127 [ - + ]: 274 : return;
128 : : }
129 [ + - ]: 9666 : random_mutable_transaction = *opt_mutable_transaction;
130 : 9940 : },
131 : 25464 : [&] {
132 : 25464 : CoinsCachePair sentinel{};
133 : 25464 : sentinel.second.SelfRef(sentinel);
134 : 25464 : size_t usage{0};
135 [ + - ]: 25464 : CCoinsMapMemoryResource resource;
136 [ + - + - ]: 25464 : CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
137 [ + - + + : 428704 : LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
+ + ]
138 : : {
139 : 403291 : CCoinsCacheEntry coins_cache_entry;
140 : 403291 : const auto dirty{fuzzed_data_provider.ConsumeBool()};
141 : 403291 : const auto fresh{fuzzed_data_provider.ConsumeBool()};
142 [ + + ]: 403291 : if (fuzzed_data_provider.ConsumeBool()) {
143 : 396644 : coins_cache_entry.coin = random_coin;
144 : : } else {
145 : 6647 : const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
146 [ + + ]: 6647 : if (!opt_coin) {
147 : 51 : good_data = false;
148 : 51 : return;
149 : : }
150 : 6596 : coins_cache_entry.coin = *opt_coin;
151 : 6596 : }
152 [ + - ]: 403240 : auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
153 [ + + ]: 403240 : if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
154 [ + + ]: 403240 : if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
155 [ + + ]: 403240 : usage += it->second.coin.DynamicMemoryUsage();
156 : 403291 : }
157 : 25413 : bool expected_code_path = false;
158 : 25413 : try {
159 [ + - ]: 25413 : auto cursor{CoinsViewCacheCursor(usage, sentinel, coins_map, /*will_erase=*/true)};
160 [ + - ]: 25413 : uint256 best_block{coins_view_cache.GetBestBlock()};
161 [ + + ]: 25413 : if (fuzzed_data_provider.ConsumeBool()) best_block = ConsumeUInt256(fuzzed_data_provider);
162 : : // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
163 [ + + + + ]: 35038 : if (is_db && best_block.IsNull()) best_block = uint256::ONE;
164 [ + + ]: 25413 : coins_view_cache.BatchWrite(cursor, best_block);
165 : : expected_code_path = true;
166 [ - + ]: 3218 : } catch (const std::logic_error& e) {
167 [ + - + - ]: 3218 : if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
168 : 3218 : expected_code_path = true;
169 : : }
170 : 0 : }
171 : 3218 : assert(expected_code_path);
172 : 25464 : });
173 : : }
174 : :
175 : 4256 : {
176 [ + - ]: 4256 : const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
177 : 4256 : const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
178 [ + - ]: 4256 : const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
179 [ + - ]: 4256 : const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
180 [ + - + + ]: 4256 : if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
181 [ - + ]: 3055 : assert(*coin == coin_using_access_coin);
182 [ + - - + ]: 3055 : assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
183 : : } else {
184 [ + - - + ]: 1201 : assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
185 : 4256 : }
186 : : // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
187 [ + - ]: 4256 : const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
188 [ + + + + ]: 4256 : if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
189 [ - + ]: 1203 : assert(exists_using_have_coin);
190 : : }
191 [ + - + + ]: 4256 : if (auto coin{backend_coins_view.GetCoin(random_out_point)}) {
192 [ - + ]: 1239 : assert(exists_using_have_coin_in_backend);
193 : : // Note we can't assert that `coin_using_get_coin == *coin` because the coin in
194 : : // the cache may have been modified but not yet flushed.
195 : : } else {
196 [ - + ]: 3017 : assert(!exists_using_have_coin_in_backend);
197 : 4256 : }
198 : : }
199 : :
200 : 4256 : {
201 : 4256 : bool expected_code_path = false;
202 : 4256 : try {
203 : 4256 : (void)coins_view_cache.Cursor();
204 [ - + ]: 4256 : } catch (const std::logic_error&) {
205 : 4256 : expected_code_path = true;
206 : 4256 : }
207 : 4256 : assert(expected_code_path);
208 [ + - ]: 4256 : (void)coins_view_cache.DynamicMemoryUsage();
209 [ + - ]: 4256 : (void)coins_view_cache.EstimateSize();
210 [ + - ]: 4256 : (void)coins_view_cache.GetBestBlock();
211 [ + - ]: 4256 : (void)coins_view_cache.GetCacheSize();
212 [ + - ]: 4256 : (void)coins_view_cache.GetHeadBlocks();
213 [ + - + - ]: 4256 : (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
214 : : }
215 : :
216 : 4256 : {
217 [ + - ]: 4256 : std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
218 [ - + ]: 4256 : assert(is_db == !!coins_view_cursor);
219 [ + - ]: 4256 : (void)backend_coins_view.EstimateSize();
220 [ + - ]: 4256 : (void)backend_coins_view.GetBestBlock();
221 [ + - ]: 4256 : (void)backend_coins_view.GetHeadBlocks();
222 : 4256 : }
223 : :
224 [ + + ]: 4256 : if (fuzzed_data_provider.ConsumeBool()) {
225 [ + - ]: 3162 : CallOneOf(
226 : : fuzzed_data_provider,
227 : 222 : [&] {
228 : 222 : const CTransaction transaction{random_mutable_transaction};
229 : 222 : bool is_spent = false;
230 [ + + ]: 1631358 : for (const CTxOut& tx_out : transaction.vout) {
231 [ + + ]: 1631136 : if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
232 : 32 : is_spent = true;
233 : : }
234 : : }
235 [ + + ]: 222 : if (is_spent) {
236 : : // Avoid:
237 : : // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
238 : 10 : return;
239 : : }
240 : 212 : bool expected_code_path = false;
241 : 212 : const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
242 : 212 : const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
243 : 212 : try {
244 [ + + ]: 212 : AddCoins(coins_view_cache, transaction, height, possible_overwrite);
245 : : expected_code_path = true;
246 [ - + ]: 4 : } catch (const std::logic_error& e) {
247 [ + - + - ]: 4 : if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
248 [ - + ]: 4 : assert(!possible_overwrite);
249 : : expected_code_path = true;
250 : : }
251 : 0 : }
252 : 4 : assert(expected_code_path);
253 : 222 : },
254 : 1885 : [&] {
255 [ + - ]: 1885 : (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
256 : 1885 : },
257 : 150 : [&] {
258 [ + - ]: 150 : TxValidationState state;
259 : 150 : CAmount tx_fee_out;
260 [ + - ]: 150 : const CTransaction transaction{random_mutable_transaction};
261 [ + + ]: 150 : if (ContainsSpentInput(transaction, coins_view_cache)) {
262 : : // Avoid:
263 : : // consensus/tx_verify.cpp:171: bool Consensus::CheckTxInputs(const CTransaction &, TxValidationState &, const CCoinsViewCache &, int, CAmount &): Assertion `!coin.IsSpent()' failed.
264 : : return;
265 : : }
266 [ + - ]: 134 : TxValidationState dummy;
267 [ + - + + ]: 134 : if (!CheckTransaction(transaction, dummy)) {
268 : : // It is not allowed to call CheckTxInputs if CheckTransaction failed
269 : 93 : return;
270 : : }
271 [ + - + + ]: 41 : if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
272 [ - + ]: 2 : assert(MoneyRange(tx_fee_out));
273 : : }
274 : 434 : },
275 : 194 : [&] {
276 : 194 : const CTransaction transaction{random_mutable_transaction};
277 [ + + ]: 194 : if (ContainsSpentInput(transaction, coins_view_cache)) {
278 : : // Avoid:
279 : : // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
280 : 58 : return;
281 : : }
282 [ + - ]: 136 : (void)GetP2SHSigOpCount(transaction, coins_view_cache);
283 : 194 : },
284 : 372 : [&] {
285 : 372 : const CTransaction transaction{random_mutable_transaction};
286 [ + + ]: 372 : if (ContainsSpentInput(transaction, coins_view_cache)) {
287 : : // Avoid:
288 : : // consensus/tx_verify.cpp:130: unsigned int GetP2SHSigOpCount(const CTransaction &, const CCoinsViewCache &): Assertion `!coin.IsSpent()' failed.
289 : : return;
290 : : }
291 : 365 : const auto flags{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
292 [ + + + + : 365 : if (!transaction.vin.empty() && (flags & SCRIPT_VERIFY_WITNESS) != 0 && (flags & SCRIPT_VERIFY_P2SH) == 0) {
+ + ]
293 : : // Avoid:
294 : : // script/interpreter.cpp:1705: size_t CountWitnessSigOps(const CScript &, const CScript &, const CScriptWitness *, unsigned int): Assertion `(flags & SCRIPT_VERIFY_P2SH) != 0' failed.
295 : : return;
296 : : }
297 [ + - ]: 363 : (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
298 : 372 : },
299 : 339 : [&] {
300 [ + - ]: 339 : (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
301 : 339 : });
302 : : }
303 : 4256 : }
304 : :
305 [ + - ]: 2316 : FUZZ_TARGET(coins_view, .init = initialize_coins_view)
306 : : {
307 [ + - ]: 1860 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
308 : 1860 : CCoinsView backend_coins_view;
309 [ + - ]: 1860 : TestCoinsView(fuzzed_data_provider, backend_coins_view, /*is_db=*/false);
310 : 1860 : }
311 : :
312 [ + - ]: 2852 : FUZZ_TARGET(coins_view_db, .init = initialize_coins_view)
313 : : {
314 : 2396 : FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
315 : 2396 : auto db_params = DBParams{
316 : : .path = "",
317 : : .cache_bytes = 1_MiB,
318 : : .memory_only = true,
319 : 2396 : };
320 [ + - ]: 2396 : CCoinsViewDB coins_db{std::move(db_params), CoinsViewOptions{}};
321 [ + - ]: 2396 : TestCoinsView(fuzzed_data_provider, coins_db, /*is_db=*/true);
322 : 4792 : }
|