fuzz coverage

Coverage Report

Created: 2025-09-17 22:41

/Users/eugenesiegel/btc/bitcoin/src/coins.cpp
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2012-2022 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
7
#include <consensus/consensus.h>
8
#include <logging.h>
9
#include <random.h>
10
#include <util/trace.h>
11
12
TRACEPOINT_SEMAPHORE(utxocache, add);
13
TRACEPOINT_SEMAPHORE(utxocache, spent);
14
TRACEPOINT_SEMAPHORE(utxocache, uncache);
15
16
0
std::optional<Coin> CCoinsView::GetCoin(const COutPoint& outpoint) const { return std::nullopt; }
17
0
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
18
0
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
19
0
bool CCoinsView::BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) { return false; }
20
0
std::unique_ptr<CCoinsViewCursor> CCoinsView::Cursor() const { return nullptr; }
21
22
bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
23
0
{
24
0
    return GetCoin(outpoint).has_value();
25
0
}
26
27
1.95M
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
28
1.19M
std::optional<Coin> CCoinsViewBacked::GetCoin(const COutPoint& outpoint) const { return base->GetCoin(outpoint); }
29
0
bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
30
475k
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
31
0
std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
32
874k
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
33
14.2k
bool CCoinsViewBacked::BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) { return base->BatchWrite(cursor, hashBlock); }
34
0
std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
35
0
size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
36
37
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn, bool deterministic) :
38
1.42M
    CCoinsViewBacked(baseIn), m_deterministic(deterministic),
39
1.42M
    cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic), CCoinsMap::key_equal{}, &m_cache_coins_memory_resource)
40
1.42M
{
41
1.42M
    m_sentinel.second.SelfRef(m_sentinel);
42
1.42M
}
43
44
1.95M
size_t CCoinsViewCache::DynamicMemoryUsage() const {
45
1.95M
    return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
46
1.95M
}
47
48
18.7M
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
49
18.7M
    const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);
50
18.7M
    if (inserted) {
51
3.39M
        if (auto coin{base->GetCoin(outpoint)}) {
52
1.62M
            ret->second.coin = std::move(*coin);
53
1.62M
            cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
54
1.62M
            if (ret->second.coin.IsSpent()) { // TODO GetCoin cannot return spent coins
55
                // The parent only has an empty entry for this outpoint; we can consider our version as fresh.
56
0
                CCoinsCacheEntry::SetFresh(*ret, m_sentinel);
57
0
            }
58
1.77M
        } else {
59
1.77M
            cacheCoins.erase(ret);
60
1.77M
            return cacheCoins.end();
61
1.77M
        }
62
3.39M
    }
63
16.9M
    return ret;
64
18.7M
}
65
66
std::optional<Coin> CCoinsViewCache::GetCoin(const COutPoint& outpoint) const
67
2.33M
{
68
2.33M
    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() && 
!it->second.coin.IsSpent()1.45M
)
return it->second.coin1.44M
;
69
889k
    return std::nullopt;
70
2.33M
}
71
72
3.14M
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
73
3.14M
    assert(!coin.IsSpent());
74
3.14M
    if (coin.out.scriptPubKey.IsUnspendable()) 
return192k
;
75
2.95M
    CCoinsMap::iterator it;
76
2.95M
    bool inserted;
77
2.95M
    std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
78
2.95M
    bool fresh = false;
79
2.95M
    if (!inserted) {
80
0
        cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
81
0
    }
82
2.95M
    if (!possible_overwrite) {
83
2.76M
        if (!it->second.coin.IsSpent()) {
84
0
            throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
85
0
        }
86
        // If the coin exists in this cache as a spent coin and is DIRTY, then
87
        // its spentness hasn't been flushed to the parent cache. We're
88
        // re-adding the coin to this cache now but we can't mark it as FRESH.
89
        // If we mark it FRESH and then spend it before the cache is flushed
90
        // we would remove it from this cache and would never flush spentness
91
        // to the parent cache.
92
        //
93
        // Re-adding a spent coin can happen in the case of a re-org (the coin
94
        // is 'spent' when the block adding it is disconnected and then
95
        // re-added when it is also added in a newly connected block).
96
        //
97
        // If the coin doesn't exist in the current cache, or is spent but not
98
        // DIRTY, then it can be marked FRESH.
99
2.76M
        fresh = !it->second.IsDirty();
100
2.76M
    }
101
2.95M
    it->second.coin = std::move(coin);
102
2.95M
    CCoinsCacheEntry::SetDirty(*it, m_sentinel);
103
2.95M
    if (fresh) 
CCoinsCacheEntry::SetFresh(*it, m_sentinel)2.76M
;
104
2.95M
    cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
105
2.95M
    TRACEPOINT(utxocache, add,
106
2.95M
           outpoint.hash.data(),
107
2.95M
           (uint32_t)outpoint.n,
108
2.95M
           (uint32_t)it->second.coin.nHeight,
109
2.95M
           (int64_t)it->second.coin.out.nValue,
110
2.95M
           (bool)it->second.coin.IsCoinBase());
111
2.95M
}
112
113
0
void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) {
114
0
    cachedCoinsUsage += coin.DynamicMemoryUsage();
115
0
    auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint), std::move(coin));
116
0
    if (inserted) CCoinsCacheEntry::SetDirty(*it, m_sentinel);
117
0
}
118
119
2.94M
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
120
2.94M
    bool fCoinbase = tx.IsCoinBase();
121
2.94M
    const Txid& txid = tx.GetHash();
122
6.09M
    for (size_t i = 0; i < tx.vout.size(); 
++i3.14M
) {
123
3.14M
        bool overwrite = check_for_overwrite ? 
cache.HaveCoin(COutPoint(txid, i))0
: fCoinbase;
124
        // Coinbase transactions can always be overwritten, in order to correctly
125
        // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
126
3.14M
        cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
127
3.14M
    }
128
2.94M
}
129
130
3.00M
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
131
3.00M
    CCoinsMap::iterator it = FetchCoin(outpoint);
132
3.00M
    if (it == cacheCoins.end()) 
return false0
;
133
3.00M
    cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
134
3.00M
    TRACEPOINT(utxocache, spent,
135
3.00M
           outpoint.hash.data(),
136
3.00M
           (uint32_t)outpoint.n,
137
3.00M
           (uint32_t)it->second.coin.nHeight,
138
3.00M
           (int64_t)it->second.coin.out.nValue,
139
3.00M
           (bool)it->second.coin.IsCoinBase());
140
3.00M
    if (moveout) {
141
267k
        *moveout = std::move(it->second.coin);
142
267k
    }
143
3.00M
    if (it->second.IsFresh()) {
144
2.12M
        cacheCoins.erase(it);
145
2.12M
    } else {
146
871k
        CCoinsCacheEntry::SetDirty(*it, m_sentinel);
147
871k
        it->second.coin.Clear();
148
871k
    }
149
3.00M
    return true;
150
3.00M
}
151
152
static const Coin coinEmpty;
153
154
6.22M
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
155
6.22M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
156
6.22M
    if (it == cacheCoins.end()) {
157
0
        return coinEmpty;
158
6.22M
    } else {
159
6.22M
        return it->second.coin;
160
6.22M
    }
161
6.22M
}
162
163
7.20M
bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
164
7.20M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
165
7.20M
    return (it != cacheCoins.end() && 
!it->second.coin.IsSpent()6.31M
);
166
7.20M
}
167
168
439k
bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
169
439k
    CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
170
439k
    return (it != cacheCoins.end() && 
!it->second.coin.IsSpent()57.5k
);
171
439k
}
172
173
2.10M
uint256 CCoinsViewCache::GetBestBlock() const {
174
2.10M
    if (hashBlock.IsNull())
175
712k
        hashBlock = base->GetBestBlock();
176
2.10M
    return hashBlock;
177
2.10M
}
178
179
269k
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
180
269k
    hashBlock = hashBlockIn;
181
269k
}
182
183
36.2k
bool CCoinsViewCache::BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlockIn) {
184
103k
    for (auto it{cursor.Begin()}; it != cursor.End(); 
it = cursor.NextAndMaybeErase(*it)67.7k
) {
185
        // Ignore non-dirty entries (optimization).
186
67.7k
        if (!it->second.IsDirty()) {
187
0
            continue;
188
0
        }
189
67.7k
        CCoinsMap::iterator itUs = cacheCoins.find(it->first);
190
67.7k
        if (itUs == cacheCoins.end()) {
191
            // The parent cache does not have an entry, while the child cache does.
192
            // We can ignore it if it's both spent and FRESH in the child
193
40.3k
            if (!(it->second.IsFresh() && 
it->second.coin.IsSpent()12.2k
)) {
194
                // Create the coin in the parent cache, move the data up
195
                // and mark it as dirty.
196
40.3k
                itUs = cacheCoins.try_emplace(it->first).first;
197
40.3k
                CCoinsCacheEntry& entry{itUs->second};
198
40.3k
                if (cursor.WillErase(*it)) {
199
                    // Since this entry will be erased,
200
                    // we can move the coin into us instead of copying it
201
40.3k
                    entry.coin = std::move(it->second.coin);
202
40.3k
                } else {
203
0
                    entry.coin = it->second.coin;
204
0
                }
205
40.3k
                cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
206
40.3k
                CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);
207
                // We can mark it FRESH in the parent if it was FRESH in the child
208
                // Otherwise it might have just been flushed from the parent's cache
209
                // and already exist in the grandparent
210
40.3k
                if (it->second.IsFresh()) 
CCoinsCacheEntry::SetFresh(*itUs, m_sentinel)12.2k
;
211
40.3k
            }
212
40.3k
        } else {
213
            // Found the entry in the parent cache
214
27.3k
            if (it->second.IsFresh() && 
!itUs->second.coin.IsSpent()3.51k
) {
215
                // The coin was marked FRESH in the child cache, but the coin
216
                // exists in the parent cache. If this ever happens, it means
217
                // the FRESH flag was misapplied and there is a logic error in
218
                // the calling code.
219
0
                throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
220
0
            }
221
222
27.3k
            if (itUs->second.IsFresh() && 
it->second.coin.IsSpent()4.67k
) {
223
                // The grandparent cache does not have an entry, and the coin
224
                // has been spent. We can just delete it from the parent cache.
225
4.67k
                cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
226
4.67k
                cacheCoins.erase(itUs);
227
22.6k
            } else {
228
                // A normal modification.
229
22.6k
                cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
230
22.6k
                if (cursor.WillErase(*it)) {
231
                    // Since this entry will be erased,
232
                    // we can move the coin into us instead of copying it
233
22.6k
                    itUs->second.coin = std::move(it->second.coin);
234
22.6k
                } else {
235
0
                    itUs->second.coin = it->second.coin;
236
0
                }
237
22.6k
                cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
238
22.6k
                CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);
239
                // NOTE: It isn't safe to mark the coin as FRESH in the parent
240
                // cache. If it already existed and was spent in the parent
241
                // cache then marking it FRESH would prevent that spentness
242
                // from being flushed to the grandparent.
243
22.6k
            }
244
27.3k
        }
245
67.7k
    }
246
36.2k
    hashBlock = hashBlockIn;
247
36.2k
    return true;
248
36.2k
}
249
250
36.2k
bool CCoinsViewCache::Flush() {
251
36.2k
    auto cursor{CoinsViewCacheCursor(cachedCoinsUsage, m_sentinel, cacheCoins, /*will_erase=*/true)};
252
36.2k
    bool fOk = base->BatchWrite(cursor, hashBlock);
253
36.2k
    if (fOk) {
254
36.2k
        cacheCoins.clear();
255
36.2k
        ReallocateCache();
256
36.2k
    }
257
36.2k
    cachedCoinsUsage = 0;
258
36.2k
    return fOk;
259
36.2k
}
260
261
bool CCoinsViewCache::Sync()
262
14.2k
{
263
14.2k
    auto cursor{CoinsViewCacheCursor(cachedCoinsUsage, m_sentinel, cacheCoins, /*will_erase=*/false)};
264
14.2k
    bool fOk = base->BatchWrite(cursor, hashBlock);
265
14.2k
    if (fOk) {
266
14.2k
        if (m_sentinel.second.Next() != &m_sentinel) {
267
            /* BatchWrite must clear flags of all entries */
268
0
            throw std::logic_error("Not all unspent flagged entries were cleared");
269
0
        }
270
14.2k
    }
271
14.2k
    return fOk;
272
14.2k
}
273
274
void CCoinsViewCache::Uncache(const COutPoint& hash)
275
418k
{
276
418k
    CCoinsMap::iterator it = cacheCoins.find(hash);
277
418k
    if (it != cacheCoins.end() && 
!it->second.IsDirty()243k
&&
!it->second.IsFresh()243k
) {
278
243k
        cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
279
243k
        TRACEPOINT(utxocache, uncache,
280
243k
               hash.hash.data(),
281
243k
               (uint32_t)hash.n,
282
243k
               (uint32_t)it->second.coin.nHeight,
283
243k
               (int64_t)it->second.coin.out.nValue,
284
243k
               (bool)it->second.coin.IsCoinBase());
285
243k
        cacheCoins.erase(it);
286
243k
    }
287
418k
}
288
289
774k
unsigned int CCoinsViewCache::GetCacheSize() const {
290
774k
    return cacheCoins.size();
291
774k
}
292
293
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
294
3.30M
{
295
3.30M
    if (!tx.IsCoinBase()) {
296
6.45M
        for (unsigned int i = 0; i < tx.vin.size(); 
i++3.14M
) {
297
3.30M
            if (!HaveCoin(tx.vin[i].prevout)) {
298
160k
                return false;
299
160k
            }
300
3.30M
        }
301
3.30M
    }
302
3.14M
    return true;
303
3.30M
}
304
305
void CCoinsViewCache::ReallocateCache()
306
36.2k
{
307
    // Cache should be empty when we're calling this.
308
36.2k
    assert(cacheCoins.size() == 0);
309
36.2k
    cacheCoins.~CCoinsMap();
310
36.2k
    m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
311
36.2k
    ::new (&m_cache_coins_memory_resource) CCoinsMapMemoryResource{};
312
36.2k
    ::new (&cacheCoins) CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic}, CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
313
36.2k
}
314
315
void CCoinsViewCache::SanityCheck() const
316
0
{
317
0
    size_t recomputed_usage = 0;
318
0
    size_t count_flagged = 0;
319
0
    for (const auto& [_, entry] : cacheCoins) {
320
0
        unsigned attr = 0;
321
0
        if (entry.IsDirty()) attr |= 1;
322
0
        if (entry.IsFresh()) attr |= 2;
323
0
        if (entry.coin.IsSpent()) attr |= 4;
324
        // Only 5 combinations are possible.
325
0
        assert(attr != 2 && attr != 4 && attr != 7);
326
327
        // Recompute cachedCoinsUsage.
328
0
        recomputed_usage += entry.coin.DynamicMemoryUsage();
329
330
        // Count the number of entries we expect in the linked list.
331
0
        if (entry.IsDirty() || entry.IsFresh()) ++count_flagged;
332
0
    }
333
    // Iterate over the linked list of flagged entries.
334
0
    size_t count_linked = 0;
335
0
    for (auto it = m_sentinel.second.Next(); it != &m_sentinel; it = it->second.Next()) {
336
        // Verify linked list integrity.
337
0
        assert(it->second.Next()->second.Prev() == it);
338
0
        assert(it->second.Prev()->second.Next() == it);
339
        // Verify they are actually flagged.
340
0
        assert(it->second.IsDirty() || it->second.IsFresh());
341
        // Count the number of entries actually in the list.
342
0
        ++count_linked;
343
0
    }
344
0
    assert(count_linked == count_flagged);
345
0
    assert(recomputed_usage == cachedCoinsUsage);
346
0
}
347
348
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut());
349
static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
350
351
const Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)
352
0
{
353
0
    COutPoint iter(txid, 0);
354
0
    while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
355
0
        const Coin& alternate = view.AccessCoin(iter);
356
0
        if (!alternate.IsSpent()) return alternate;
357
0
        ++iter.n;
358
0
    }
359
0
    return coinEmpty;
360
0
}
361
362
template <typename ReturnType, typename Func>
363
static ReturnType ExecuteBackedWrapper(Func func, const std::vector<std::function<void()>>& err_callbacks)
364
1.19M
{
365
1.19M
    try {
366
1.19M
        return func();
367
1.19M
    } catch(const std::runtime_error& e) {
368
0
        for (const auto& f : err_callbacks) {
369
0
            f();
370
0
        }
371
0
        LogError("Error reading from database: %s\n", e.what());
Line
Count
Source
358
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
        LogError("Error reading from database: %s\n", e.what());
Line
Count
Source
358
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
372
        // Starting the shutdown sequence and returning false to the caller would be
373
        // interpreted as 'entry not found' (as opposed to unable to read data), and
374
        // could lead to invalid interpretation. Just exit immediately, as we can't
375
        // continue anyway, and all writes should be atomic.
376
0
        std::abort();
377
0
    }
378
1.19M
}
coins.cpp:_ZL20ExecuteBackedWrapperINSt3__18optionalI4CoinEEZNK22CCoinsViewErrorCatcher7GetCoinERK9COutPointE3$_0ET_T0_RKNS0_6vectorINS0_8functionIFvvEEENS0_9allocatorISE_EEEE
Line
Count
Source
364
1.19M
{
365
1.19M
    try {
366
1.19M
        return func();
367
1.19M
    } catch(const std::runtime_error& e) {
368
0
        for (const auto& f : err_callbacks) {
369
0
            f();
370
0
        }
371
0
        LogError("Error reading from database: %s\n", e.what());
Line
Count
Source
358
0
#define LogError(...) LogPrintLevel_(BCLog::LogFlags::ALL, BCLog::Level::Error, /*should_ratelimit=*/true, __VA_ARGS__)
Line
Count
Source
350
0
#define LogPrintLevel_(category, level, should_ratelimit, ...) LogPrintFormatInternal(std::source_location::current(), category, level, should_ratelimit, __VA_ARGS__)
372
        // Starting the shutdown sequence and returning false to the caller would be
373
        // interpreted as 'entry not found' (as opposed to unable to read data), and
374
        // could lead to invalid interpretation. Just exit immediately, as we can't
375
        // continue anyway, and all writes should be atomic.
376
0
        std::abort();
377
0
    }
378
1.19M
}
Unexecuted instantiation: coins.cpp:_ZL20ExecuteBackedWrapperIbZNK22CCoinsViewErrorCatcher8HaveCoinERK9COutPointE3$_0ET_T0_RKNSt3__16vectorINS7_8functionIFvvEEENS7_9allocatorISB_EEEE
379
380
std::optional<Coin> CCoinsViewErrorCatcher::GetCoin(const COutPoint& outpoint) const
381
1.19M
{
382
1.19M
    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);
383
1.19M
}
384
385
bool CCoinsViewErrorCatcher::HaveCoin(const COutPoint& outpoint) const
386
0
{
387
0
    return ExecuteBackedWrapper<bool>([&]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);
388
0
}