Coverage Report

Created: 2025-09-25 19:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/test/fuzz/coins_view.cpp
Line
Count
Source
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
bool operator==(const Coin& a, const Coin& b)
34
0
{
35
0
    if (a.IsSpent() && b.IsSpent()) return true;
36
0
    return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.out == b.out;
37
0
}
38
} // namespace
39
40
void initialize_coins_view()
41
0
{
42
0
    static const auto testing_setup = MakeNoLogFileContext<>();
43
0
}
44
45
void TestCoinsView(FuzzedDataProvider& fuzzed_data_provider, CCoinsView& backend_coins_view, bool is_db)
46
0
{
47
0
    bool good_data{true};
48
49
0
    CCoinsViewCache coins_view_cache{&backend_coins_view, /*deterministic=*/true};
50
0
    if (is_db) coins_view_cache.SetBestBlock(uint256::ONE);
51
0
    COutPoint random_out_point;
52
0
    Coin random_coin;
53
0
    CMutableTransaction random_mutable_transaction;
54
0
    LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
55
0
    {
56
0
        CallOneOf(
57
0
            fuzzed_data_provider,
58
0
            [&] {
59
0
                if (random_coin.IsSpent()) {
60
0
                    return;
61
0
                }
62
0
                Coin coin = random_coin;
63
0
                bool expected_code_path = false;
64
0
                const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
65
0
                try {
66
0
                    coins_view_cache.AddCoin(random_out_point, std::move(coin), possible_overwrite);
67
0
                    expected_code_path = true;
68
0
                } catch (const std::logic_error& e) {
69
0
                    if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
70
0
                        assert(!possible_overwrite);
71
0
                        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
0
                        (void)coins_view_cache.Flush();
78
0
                    }
79
0
                }
80
0
                assert(expected_code_path);
81
0
            },
82
0
            [&] {
83
0
                (void)coins_view_cache.Flush();
84
0
            },
85
0
            [&] {
86
0
                (void)coins_view_cache.Sync();
87
0
            },
88
0
            [&] {
89
0
                uint256 best_block{ConsumeUInt256(fuzzed_data_provider)};
90
                // Set best block hash to non-null to satisfy the assertion in CCoinsViewDB::BatchWrite().
91
0
                if (is_db && best_block.IsNull()) best_block = uint256::ONE;
92
0
                coins_view_cache.SetBestBlock(best_block);
93
0
            },
94
0
            [&] {
95
0
                Coin move_to;
96
0
                (void)coins_view_cache.SpendCoin(random_out_point, fuzzed_data_provider.ConsumeBool() ? &move_to : nullptr);
97
0
            },
98
0
            [&] {
99
0
                coins_view_cache.Uncache(random_out_point);
100
0
            },
101
0
            [&] {
102
0
                if (fuzzed_data_provider.ConsumeBool()) {
103
0
                    backend_coins_view = CCoinsView{};
104
0
                }
105
0
                coins_view_cache.SetBackend(backend_coins_view);
106
0
            },
107
0
            [&] {
108
0
                const std::optional<COutPoint> opt_out_point = ConsumeDeserializable<COutPoint>(fuzzed_data_provider);
109
0
                if (!opt_out_point) {
110
0
                    good_data = false;
111
0
                    return;
112
0
                }
113
0
                random_out_point = *opt_out_point;
114
0
            },
115
0
            [&] {
116
0
                const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
117
0
                if (!opt_coin) {
118
0
                    good_data = false;
119
0
                    return;
120
0
                }
121
0
                random_coin = *opt_coin;
122
0
            },
123
0
            [&] {
124
0
                const std::optional<CMutableTransaction> opt_mutable_transaction = ConsumeDeserializable<CMutableTransaction>(fuzzed_data_provider, TX_WITH_WITNESS);
125
0
                if (!opt_mutable_transaction) {
126
0
                    good_data = false;
127
0
                    return;
128
0
                }
129
0
                random_mutable_transaction = *opt_mutable_transaction;
130
0
            },
131
0
            [&] {
132
0
                CoinsCachePair sentinel{};
133
0
                sentinel.second.SelfRef(sentinel);
134
0
                size_t usage{0};
135
0
                CCoinsMapMemoryResource resource;
136
0
                CCoinsMap coins_map{0, SaltedOutpointHasher{/*deterministic=*/true}, CCoinsMap::key_equal{}, &resource};
137
0
                LIMITED_WHILE(good_data && fuzzed_data_provider.ConsumeBool(), 10'000)
138
0
                {
139
0
                    CCoinsCacheEntry coins_cache_entry;
140
0
                    const auto dirty{fuzzed_data_provider.ConsumeBool()};
141
0
                    const auto fresh{fuzzed_data_provider.ConsumeBool()};
142
0
                    if (fuzzed_data_provider.ConsumeBool()) {
143
0
                        coins_cache_entry.coin = random_coin;
144
0
                    } else {
145
0
                        const std::optional<Coin> opt_coin = ConsumeDeserializable<Coin>(fuzzed_data_provider);
146
0
                        if (!opt_coin) {
147
0
                            good_data = false;
148
0
                            return;
149
0
                        }
150
0
                        coins_cache_entry.coin = *opt_coin;
151
0
                    }
152
0
                    auto it{coins_map.emplace(random_out_point, std::move(coins_cache_entry)).first};
153
0
                    if (dirty) CCoinsCacheEntry::SetDirty(*it, sentinel);
154
0
                    if (fresh) CCoinsCacheEntry::SetFresh(*it, sentinel);
155
0
                    usage += it->second.coin.DynamicMemoryUsage();
156
0
                }
157
0
                bool expected_code_path = false;
158
0
                try {
159
0
                    auto cursor{CoinsViewCacheCursor(usage, sentinel, coins_map, /*will_erase=*/true)};
160
0
                    uint256 best_block{coins_view_cache.GetBestBlock()};
161
0
                    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
0
                    if (is_db && best_block.IsNull()) best_block = uint256::ONE;
164
0
                    coins_view_cache.BatchWrite(cursor, best_block);
165
0
                    expected_code_path = true;
166
0
                } catch (const std::logic_error& e) {
167
0
                    if (e.what() == std::string{"FRESH flag misapplied to coin that exists in parent cache"}) {
168
0
                        expected_code_path = true;
169
0
                    }
170
0
                }
171
0
                assert(expected_code_path);
172
0
            });
173
0
    }
174
175
0
    {
176
0
        const Coin& coin_using_access_coin = coins_view_cache.AccessCoin(random_out_point);
177
0
        const bool exists_using_access_coin = !(coin_using_access_coin == EMPTY_COIN);
178
0
        const bool exists_using_have_coin = coins_view_cache.HaveCoin(random_out_point);
179
0
        const bool exists_using_have_coin_in_cache = coins_view_cache.HaveCoinInCache(random_out_point);
180
0
        if (auto coin{coins_view_cache.GetCoin(random_out_point)}) {
181
0
            assert(*coin == coin_using_access_coin);
182
0
            assert(exists_using_access_coin && exists_using_have_coin_in_cache && exists_using_have_coin);
183
0
        } else {
184
0
            assert(!exists_using_access_coin && !exists_using_have_coin_in_cache && !exists_using_have_coin);
185
0
        }
186
        // If HaveCoin on the backend is true, it must also be on the cache if the coin wasn't spent.
187
0
        const bool exists_using_have_coin_in_backend = backend_coins_view.HaveCoin(random_out_point);
188
0
        if (!coin_using_access_coin.IsSpent() && exists_using_have_coin_in_backend) {
189
0
            assert(exists_using_have_coin);
190
0
        }
191
0
        if (auto coin{backend_coins_view.GetCoin(random_out_point)}) {
192
0
            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
0
        } else {
196
0
            assert(!exists_using_have_coin_in_backend);
197
0
        }
198
0
    }
199
200
0
    {
201
0
        bool expected_code_path = false;
202
0
        try {
203
0
            (void)coins_view_cache.Cursor();
204
0
        } catch (const std::logic_error&) {
205
0
            expected_code_path = true;
206
0
        }
207
0
        assert(expected_code_path);
208
0
        (void)coins_view_cache.DynamicMemoryUsage();
209
0
        (void)coins_view_cache.EstimateSize();
210
0
        (void)coins_view_cache.GetBestBlock();
211
0
        (void)coins_view_cache.GetCacheSize();
212
0
        (void)coins_view_cache.GetHeadBlocks();
213
0
        (void)coins_view_cache.HaveInputs(CTransaction{random_mutable_transaction});
214
0
    }
215
216
0
    {
217
0
        std::unique_ptr<CCoinsViewCursor> coins_view_cursor = backend_coins_view.Cursor();
218
0
        assert(is_db == !!coins_view_cursor);
219
0
        (void)backend_coins_view.EstimateSize();
220
0
        (void)backend_coins_view.GetBestBlock();
221
0
        (void)backend_coins_view.GetHeadBlocks();
222
0
    }
223
224
0
    if (fuzzed_data_provider.ConsumeBool()) {
225
0
        CallOneOf(
226
0
            fuzzed_data_provider,
227
0
            [&] {
228
0
                const CTransaction transaction{random_mutable_transaction};
229
0
                bool is_spent = false;
230
0
                for (const CTxOut& tx_out : transaction.vout) {
231
0
                    if (Coin{tx_out, 0, transaction.IsCoinBase()}.IsSpent()) {
232
0
                        is_spent = true;
233
0
                    }
234
0
                }
235
0
                if (is_spent) {
236
                    // Avoid:
237
                    // coins.cpp:69: void CCoinsViewCache::AddCoin(const COutPoint &, Coin &&, bool): Assertion `!coin.IsSpent()' failed.
238
0
                    return;
239
0
                }
240
0
                bool expected_code_path = false;
241
0
                const int height{int(fuzzed_data_provider.ConsumeIntegral<uint32_t>() >> 1)};
242
0
                const bool possible_overwrite = fuzzed_data_provider.ConsumeBool();
243
0
                try {
244
0
                    AddCoins(coins_view_cache, transaction, height, possible_overwrite);
245
0
                    expected_code_path = true;
246
0
                } catch (const std::logic_error& e) {
247
0
                    if (e.what() == std::string{"Attempted to overwrite an unspent coin (when possible_overwrite is false)"}) {
248
0
                        assert(!possible_overwrite);
249
0
                        expected_code_path = true;
250
0
                    }
251
0
                }
252
0
                assert(expected_code_path);
253
0
            },
254
0
            [&] {
255
0
                (void)AreInputsStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
256
0
            },
257
0
            [&] {
258
0
                TxValidationState state;
259
0
                CAmount tx_fee_out;
260
0
                const CTransaction transaction{random_mutable_transaction};
261
0
                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
0
                    return;
265
0
                }
266
0
                TxValidationState dummy;
267
0
                if (!CheckTransaction(transaction, dummy)) {
268
                    // It is not allowed to call CheckTxInputs if CheckTransaction failed
269
0
                    return;
270
0
                }
271
0
                if (Consensus::CheckTxInputs(transaction, state, coins_view_cache, fuzzed_data_provider.ConsumeIntegralInRange<int>(0, std::numeric_limits<int>::max()), tx_fee_out)) {
272
0
                    assert(MoneyRange(tx_fee_out));
273
0
                }
274
0
            },
275
0
            [&] {
276
0
                const CTransaction transaction{random_mutable_transaction};
277
0
                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
0
                    return;
281
0
                }
282
0
                (void)GetP2SHSigOpCount(transaction, coins_view_cache);
283
0
            },
284
0
            [&] {
285
0
                const CTransaction transaction{random_mutable_transaction};
286
0
                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
0
                    return;
290
0
                }
291
0
                const auto flags{fuzzed_data_provider.ConsumeIntegral<uint32_t>()};
292
0
                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
0
                    return;
296
0
                }
297
0
                (void)GetTransactionSigOpCost(transaction, coins_view_cache, flags);
298
0
            },
299
0
            [&] {
300
0
                (void)IsWitnessStandard(CTransaction{random_mutable_transaction}, coins_view_cache);
301
0
            });
302
0
    }
303
0
}
304
305
FUZZ_TARGET(coins_view, .init = initialize_coins_view)
306
0
{
307
0
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
308
0
    CCoinsView backend_coins_view;
309
0
    TestCoinsView(fuzzed_data_provider, backend_coins_view, /*is_db=*/false);
310
0
}
311
312
FUZZ_TARGET(coins_view_db, .init = initialize_coins_view)
313
0
{
314
0
    FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
315
0
    auto db_params = DBParams{
316
0
        .path = "",
317
0
        .cache_bytes = 1_MiB,
318
0
        .memory_only = true,
319
0
    };
320
0
    CCoinsViewDB coins_db{std::move(db_params), CoinsViewOptions{}};
321
0
    TestCoinsView(fuzzed_data_provider, coins_db, /*is_db=*/true);
322
0
}