Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/coins.cpp
Line
Count
Source
1
// Copyright (c) 2012-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
7
#include <consensus/consensus.h>
8
#include <random.h>
9
#include <uint256.h>
10
#include <util/log.h>
11
#include <util/trace.h>
12
13
TRACEPOINT_SEMAPHORE(utxocache, add);
14
TRACEPOINT_SEMAPHORE(utxocache, spent);
15
TRACEPOINT_SEMAPHORE(utxocache, uncache);
16
17
CoinsViewEmpty& CoinsViewEmpty::Get()
18
73.9k
{
19
73.9k
    static CoinsViewEmpty instance;
20
73.9k
    return instance;
21
73.9k
}
22
23
std::optional<Coin> CCoinsViewCache::PeekCoin(const COutPoint& outpoint) const
24
438k
{
25
438k
    if (auto it{cacheCoins.find(outpoint)}; it != cacheCoins.end()) {
26
56.4k
        return it->second.coin.IsSpent() ? std::nullopt : std::optional{it->second.coin};
27
56.4k
    }
28
382k
    return base->PeekCoin(outpoint);
29
438k
}
30
31
CCoinsViewCache::CCoinsViewCache(CCoinsView* in_base, bool deterministic) :
32
373k
    CCoinsViewBacked(in_base), m_deterministic(deterministic),
33
373k
    cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic), CCoinsMap::key_equal{}, &m_cache_coins_memory_resource)
34
373k
{
35
373k
    m_sentinel.second.SelfRef(m_sentinel);
36
373k
}
37
38
978k
size_t CCoinsViewCache::DynamicMemoryUsage() const {
39
978k
    return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
40
978k
}
41
42
std::optional<Coin> CCoinsViewCache::FetchCoinFromBase(const COutPoint& outpoint) const
43
44.4M
{
44
44.4M
    return base->GetCoin(outpoint);
45
44.4M
}
46
47
101M
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
48
101M
    const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);
49
101M
    if (inserted) {
50
44.9M
        if (auto coin{FetchCoinFromBase(outpoint)}) {
51
14.2M
            ret->second.coin = std::move(*coin);
52
14.2M
            cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
53
14.2M
            Assert(!ret->second.coin.IsSpent());
54
30.7M
        } else {
55
30.7M
            cacheCoins.erase(ret);
56
30.7M
            return cacheCoins.end();
57
30.7M
        }
58
44.9M
    }
59
70.9M
    return ret;
60
101M
}
61
62
std::optional<Coin> CCoinsViewCache::GetCoin(const COutPoint& outpoint) const
63
32.6M
{
64
32.6M
    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() && !it->second.coin.IsSpent()) return it->second.coin;
65
18.6M
    return std::nullopt;
66
32.6M
}
67
68
21.8M
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
69
21.8M
    assert(!coin.IsSpent());
70
21.8M
    if (coin.out.scriptPubKey.IsUnspendable()) return;
71
21.5M
    CCoinsMap::iterator it;
72
21.5M
    bool inserted;
73
21.5M
    std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
74
21.5M
    bool fresh = false;
75
21.5M
    if (!possible_overwrite) {
76
21.3M
        if (!it->second.coin.IsSpent()) {
77
17
            throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
78
17
        }
79
        // If the coin exists in this cache as a spent coin and is DIRTY, then
80
        // its spentness hasn't been flushed to the parent cache. We're
81
        // re-adding the coin to this cache now but we can't mark it as FRESH.
82
        // If we mark it FRESH and then spend it before the cache is flushed
83
        // we would remove it from this cache and would never flush spentness
84
        // to the parent cache.
85
        //
86
        // Re-adding a spent coin can happen in the case of a re-org (the coin
87
        // is 'spent' when the block adding it is disconnected and then
88
        // re-added when it is also added in a newly connected block).
89
        //
90
        // If the coin doesn't exist in the current cache, or is spent but not
91
        // DIRTY, then it can be marked FRESH.
92
21.3M
        fresh = !it->second.IsDirty();
93
21.3M
    }
94
21.5M
    if (!inserted) {
95
11.3k
        Assume(TrySub(m_dirty_count, it->second.IsDirty()));
96
11.3k
        Assume(TrySub(cachedCoinsUsage, it->second.coin.DynamicMemoryUsage()));
97
11.3k
    }
98
21.5M
    it->second.coin = std::move(coin);
99
21.5M
    CCoinsCacheEntry::SetDirty(*it, m_sentinel);
100
21.5M
    ++m_dirty_count;
101
21.5M
    if (fresh) CCoinsCacheEntry::SetFresh(*it, m_sentinel);
102
21.5M
    cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
103
21.5M
    TRACEPOINT(utxocache, add,
104
21.5M
           outpoint.hash.data(),
105
21.5M
           (uint32_t)outpoint.n,
106
21.5M
           (uint32_t)it->second.coin.nHeight,
107
21.5M
           (int64_t)it->second.coin.out.nValue,
108
21.5M
           (bool)it->second.coin.IsCoinBase());
109
21.5M
}
110
111
24.5k
void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) {
112
24.5k
    const auto mem_usage{coin.DynamicMemoryUsage()};
113
24.5k
    auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint), std::move(coin));
114
24.5k
    if (inserted) {
115
24.5k
        CCoinsCacheEntry::SetDirty(*it, m_sentinel);
116
24.5k
        ++m_dirty_count;
117
24.5k
        cachedCoinsUsage += mem_usage;
118
24.5k
    }
119
24.5k
}
120
121
10.9M
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
122
10.9M
    bool fCoinbase = tx.IsCoinBase();
123
10.9M
    const Txid& txid = tx.GetHash();
124
32.6M
    for (size_t i = 0; i < tx.vout.size(); ++i) {
125
21.6M
        bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
126
        // Coinbase transactions can always be overwritten, in order to correctly
127
        // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
128
21.6M
        cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
129
21.6M
    }
130
10.9M
}
131
132
13.9M
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
133
13.9M
    CCoinsMap::iterator it = FetchCoin(outpoint);
134
13.9M
    if (it == cacheCoins.end()) return false;
135
13.9M
    Assume(TrySub(m_dirty_count, it->second.IsDirty()));
136
13.9M
    Assume(TrySub(cachedCoinsUsage, it->second.coin.DynamicMemoryUsage()));
137
13.9M
    TRACEPOINT(utxocache, spent,
138
13.9M
           outpoint.hash.data(),
139
13.9M
           (uint32_t)outpoint.n,
140
13.9M
           (uint32_t)it->second.coin.nHeight,
141
13.9M
           (int64_t)it->second.coin.out.nValue,
142
13.9M
           (bool)it->second.coin.IsCoinBase());
143
13.9M
    if (moveout) {
144
171k
        *moveout = std::move(it->second.coin);
145
171k
    }
146
13.9M
    if (it->second.IsFresh()) {
147
242k
        cacheCoins.erase(it);
148
13.6M
    } else {
149
13.6M
        CCoinsCacheEntry::SetDirty(*it, m_sentinel);
150
13.6M
        ++m_dirty_count;
151
13.6M
        it->second.coin.Clear();
152
13.6M
    }
153
13.9M
    return true;
154
13.9M
}
155
156
static const Coin coinEmpty;
157
158
25.8M
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
159
25.8M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
160
25.8M
    if (it == cacheCoins.end()) {
161
10.8M
        return coinEmpty;
162
14.9M
    } else {
163
14.9M
        return it->second.coin;
164
14.9M
    }
165
25.8M
}
166
167
bool CCoinsViewCache::HaveCoin(const COutPoint& outpoint) const
168
29.1M
{
169
29.1M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
170
29.1M
    return (it != cacheCoins.end() && !it->second.coin.IsSpent());
171
29.1M
}
172
173
248k
bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
174
248k
    CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
175
248k
    return (it != cacheCoins.end() && !it->second.coin.IsSpent());
176
248k
}
177
178
450k
uint256 CCoinsViewCache::GetBestBlock() const {
179
450k
    if (m_block_hash.IsNull())
180
204k
        m_block_hash = base->GetBestBlock();
181
450k
    return m_block_hash;
182
450k
}
183
184
void CCoinsViewCache::SetBestBlock(const uint256& in_block_hash)
185
777k
{
186
777k
    m_block_hash = in_block_hash;
187
777k
}
188
189
void CCoinsViewCache::BatchWrite(CoinsViewCacheCursor& cursor, const uint256& in_block_hash)
190
121k
{
191
617k
    for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)) {
192
495k
        if (!it->second.IsDirty()) { // TODO a cursor can only contain dirty entries
193
18
            continue;
194
18
        }
195
495k
        auto [itUs, inserted]{cacheCoins.try_emplace(it->first)};
196
495k
        if (inserted) {
197
381k
            if (it->second.IsFresh() && it->second.coin.IsSpent()) {
198
1
                cacheCoins.erase(itUs); // TODO fresh coins should have been removed at spend
199
381k
            } else {
200
                // The parent cache does not have an entry, while the child cache does.
201
                // Move the data up and mark it as dirty.
202
381k
                CCoinsCacheEntry& entry{itUs->second};
203
381k
                assert(entry.coin.DynamicMemoryUsage() == 0);
204
381k
                if (cursor.WillErase(*it)) {
205
                    // Since this entry will be erased,
206
                    // we can move the coin into us instead of copying it
207
370k
                    entry.coin = std::move(it->second.coin);
208
370k
                } else {
209
11.0k
                    entry.coin = it->second.coin;
210
11.0k
                }
211
381k
                CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);
212
381k
                ++m_dirty_count;
213
381k
                cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
214
                // We can mark it FRESH in the parent if it was FRESH in the child
215
                // Otherwise it might have just been flushed from the parent's cache
216
                // and already exist in the grandparent
217
381k
                if (it->second.IsFresh()) CCoinsCacheEntry::SetFresh(*itUs, m_sentinel);
218
381k
            }
219
381k
        } else {
220
            // Found the entry in the parent cache
221
113k
            if (it->second.IsFresh() && !itUs->second.coin.IsSpent()) {
222
                // The coin was marked FRESH in the child cache, but the coin
223
                // exists in the parent cache. If this ever happens, it means
224
                // the FRESH flag was misapplied and there is a logic error in
225
                // the calling code.
226
8
                throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
227
8
            }
228
229
113k
            if (itUs->second.IsFresh() && it->second.coin.IsSpent()) {
230
                // The grandparent cache does not have an entry, and the coin
231
                // has been spent. We can just delete it from the parent cache.
232
39.8k
                Assume(TrySub(m_dirty_count, itUs->second.IsDirty()));
233
39.8k
                Assume(TrySub(cachedCoinsUsage, itUs->second.coin.DynamicMemoryUsage()));
234
39.8k
                cacheCoins.erase(itUs);
235
73.9k
            } else {
236
                // A normal modification.
237
73.9k
                Assume(TrySub(cachedCoinsUsage, itUs->second.coin.DynamicMemoryUsage()));
238
73.9k
                if (cursor.WillErase(*it)) {
239
                    // Since this entry will be erased,
240
                    // we can move the coin into us instead of copying it
241
71.9k
                    itUs->second.coin = std::move(it->second.coin);
242
71.9k
                } else {
243
2.00k
                    itUs->second.coin = it->second.coin;
244
2.00k
                }
245
73.9k
                cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
246
73.9k
                if (!itUs->second.IsDirty()) {
247
46.9k
                    CCoinsCacheEntry::SetDirty(*itUs, m_sentinel);
248
46.9k
                    ++m_dirty_count;
249
46.9k
                }
250
                // NOTE: It isn't safe to mark the coin as FRESH in the parent
251
                // cache. If it already existed and was spent in the parent
252
                // cache then marking it FRESH would prevent that spentness
253
                // from being flushed to the grandparent.
254
73.9k
            }
255
113k
        }
256
495k
    }
257
121k
    SetBestBlock(in_block_hash);
258
121k
}
259
260
void CCoinsViewCache::Flush(bool reallocate_cache)
261
123k
{
262
123k
    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, /*will_erase=*/true)};
263
123k
    base->BatchWrite(cursor, m_block_hash);
264
123k
    Assume(m_dirty_count == 0);
265
123k
    cacheCoins.clear();
266
123k
    if (reallocate_cache) {
267
3.15k
        ReallocateCache();
268
3.15k
    }
269
123k
    cachedCoinsUsage = 0;
270
123k
}
271
272
void CCoinsViewCache::Sync()
273
1.41k
{
274
1.41k
    auto cursor{CoinsViewCacheCursor(m_dirty_count, m_sentinel, cacheCoins, /*will_erase=*/false)};
275
1.41k
    base->BatchWrite(cursor, m_block_hash);
276
1.41k
    Assume(m_dirty_count == 0);
277
1.41k
    if (m_sentinel.second.Next() != &m_sentinel) {
278
        /* BatchWrite must clear flags of all entries */
279
0
        throw std::logic_error("Not all unspent flagged entries were cleared");
280
0
    }
281
1.41k
}
282
283
void CCoinsViewCache::Reset() noexcept
284
109k
{
285
109k
    cacheCoins.clear();
286
109k
    cachedCoinsUsage = 0;
287
109k
    m_dirty_count = 0;
288
109k
    SetBestBlock(uint256::ZERO);
289
109k
}
290
291
void CCoinsViewCache::Uncache(const COutPoint& hash)
292
22.0k
{
293
22.0k
    CCoinsMap::iterator it = cacheCoins.find(hash);
294
22.0k
    if (it != cacheCoins.end() && !it->second.IsDirty()) {
295
8.99k
        Assume(TrySub(cachedCoinsUsage, it->second.coin.DynamicMemoryUsage()));
296
8.99k
        TRACEPOINT(utxocache, uncache,
297
8.99k
               hash.hash.data(),
298
8.99k
               (uint32_t)hash.n,
299
8.99k
               (uint32_t)it->second.coin.nHeight,
300
8.99k
               (int64_t)it->second.coin.out.nValue,
301
8.99k
               (bool)it->second.coin.IsCoinBase());
302
8.99k
        cacheCoins.erase(it);
303
8.99k
    }
304
22.0k
}
305
306
487k
unsigned int CCoinsViewCache::GetCacheSize() const {
307
487k
    return cacheCoins.size();
308
487k
}
309
310
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
311
10.8M
{
312
10.8M
    if (!tx.IsCoinBase()) {
313
24.6M
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
314
13.8M
            if (!HaveCoin(tx.vin[i].prevout)) {
315
322
                return false;
316
322
            }
317
13.8M
        }
318
10.8M
    }
319
10.8M
    return true;
320
10.8M
}
321
322
void CCoinsViewCache::ReallocateCache()
323
3.15k
{
324
    // Cache should be empty when we're calling this.
325
3.15k
    assert(cacheCoins.size() == 0);
326
3.15k
    cacheCoins.~CCoinsMap();
327
3.15k
    m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
328
3.15k
    ::new (&m_cache_coins_memory_resource) CCoinsMapMemoryResource{};
329
3.15k
    ::new (&cacheCoins) CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic}, CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
330
3.15k
}
331
332
void CCoinsViewCache::SanityCheck() const
333
294
{
334
294
    size_t recomputed_usage = 0;
335
294
    size_t count_dirty = 0;
336
425k
    for (const auto& [_, entry] : cacheCoins) {
337
425k
        if (entry.coin.IsSpent()) {
338
16.5k
            assert(entry.IsDirty() && !entry.IsFresh()); // A spent coin must be dirty and cannot be fresh
339
408k
        } else {
340
408k
            assert(entry.IsDirty() || !entry.IsFresh()); // An unspent coin must not be fresh if not dirty
341
408k
        }
342
343
        // Recompute cachedCoinsUsage.
344
425k
        recomputed_usage += entry.coin.DynamicMemoryUsage();
345
346
        // Count the number of entries we expect in the linked list.
347
425k
        if (entry.IsDirty()) ++count_dirty;
348
425k
    }
349
    // Iterate over the linked list of flagged entries.
350
294
    size_t count_linked = 0;
351
41.8k
    for (auto it = m_sentinel.second.Next(); it != &m_sentinel; it = it->second.Next()) {
352
        // Verify linked list integrity.
353
41.5k
        assert(it->second.Next()->second.Prev() == it);
354
41.5k
        assert(it->second.Prev()->second.Next() == it);
355
        // Verify they are actually flagged.
356
41.5k
        assert(it->second.IsDirty());
357
        // Count the number of entries actually in the list.
358
41.5k
        ++count_linked;
359
41.5k
    }
360
294
    assert(count_dirty == count_linked && count_dirty == m_dirty_count);
361
294
    assert(recomputed_usage == cachedCoinsUsage);
362
294
}
363
364
static const uint64_t MIN_TRANSACTION_OUTPUT_WEIGHT{WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut())};
365
static const uint64_t MAX_OUTPUTS_PER_BLOCK{MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT};
366
367
const Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)
368
183
{
369
183
    COutPoint iter(txid, 0);
370
10.1M
    while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
371
10.1M
        const Coin& alternate = view.AccessCoin(iter);
372
10.1M
        if (!alternate.IsSpent()) return alternate;
373
10.1M
        ++iter.n;
374
10.1M
    }
375
91
    return coinEmpty;
376
183
}
377
378
template <typename ReturnType, typename Func>
379
static ReturnType ExecuteBackedWrapper(Func func, const std::vector<std::function<void()>>& err_callbacks)
380
1.27M
{
381
1.27M
    try {
382
1.27M
        return func();
383
1.27M
    } catch(const std::runtime_error& e) {
384
0
        for (const auto& f : err_callbacks) {
385
0
            f();
386
0
        }
387
0
        LogError("Error reading from database: %s\n", e.what());
388
        // Starting the shutdown sequence and returning false to the caller would be
389
        // interpreted as 'entry not found' (as opposed to unable to read data), and
390
        // could lead to invalid interpretation. Just exit immediately, as we can't
391
        // continue anyway, and all writes should be atomic.
392
0
        std::abort();
393
0
    }
394
1.27M
}
coins.cpp:std::optional<Coin> ExecuteBackedWrapper<std::optional<Coin>, CCoinsViewErrorCatcher::GetCoin(COutPoint const&) const::$_0>(CCoinsViewErrorCatcher::GetCoin(COutPoint const&) const::$_0, std::vector<std::function<void ()>, std::allocator<std::function<void ()>>> const&)
Line
Count
Source
380
889k
{
381
889k
    try {
382
889k
        return func();
383
889k
    } catch(const std::runtime_error& e) {
384
0
        for (const auto& f : err_callbacks) {
385
0
            f();
386
0
        }
387
0
        LogError("Error reading from database: %s\n", e.what());
388
        // Starting the shutdown sequence and returning false to the caller would be
389
        // interpreted as 'entry not found' (as opposed to unable to read data), and
390
        // could lead to invalid interpretation. Just exit immediately, as we can't
391
        // continue anyway, and all writes should be atomic.
392
0
        std::abort();
393
0
    }
394
889k
}
Unexecuted instantiation: coins.cpp:bool ExecuteBackedWrapper<bool, CCoinsViewErrorCatcher::HaveCoin(COutPoint const&) const::$_0>(CCoinsViewErrorCatcher::HaveCoin(COutPoint const&) const::$_0, std::vector<std::function<void ()>, std::allocator<std::function<void ()>>> const&)
coins.cpp:std::optional<Coin> ExecuteBackedWrapper<std::optional<Coin>, CCoinsViewErrorCatcher::PeekCoin(COutPoint const&) const::$_0>(CCoinsViewErrorCatcher::PeekCoin(COutPoint const&) const::$_0, std::vector<std::function<void ()>, std::allocator<std::function<void ()>>> const&)
Line
Count
Source
380
381k
{
381
381k
    try {
382
381k
        return func();
383
381k
    } catch(const std::runtime_error& e) {
384
0
        for (const auto& f : err_callbacks) {
385
0
            f();
386
0
        }
387
0
        LogError("Error reading from database: %s\n", e.what());
388
        // Starting the shutdown sequence and returning false to the caller would be
389
        // interpreted as 'entry not found' (as opposed to unable to read data), and
390
        // could lead to invalid interpretation. Just exit immediately, as we can't
391
        // continue anyway, and all writes should be atomic.
392
0
        std::abort();
393
0
    }
394
381k
}
395
396
std::optional<Coin> CCoinsViewErrorCatcher::GetCoin(const COutPoint& outpoint) const
397
889k
{
398
889k
    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);
399
889k
}
400
401
bool CCoinsViewErrorCatcher::HaveCoin(const COutPoint& outpoint) const
402
0
{
403
0
    return ExecuteBackedWrapper<bool>([&]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);
404
0
}
405
406
std::optional<Coin> CCoinsViewErrorCatcher::PeekCoin(const COutPoint& outpoint) const
407
381k
{
408
381k
    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::PeekCoin(outpoint); }, m_err_callbacks);
409
381k
}