Coverage Report

Created: 2025-09-08 17:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/bitcoin/src/coins.cpp
Line
Count
Source
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
1.83M
std::optional<Coin> CCoinsView::GetCoin(const COutPoint& outpoint) const { return std::nullopt; }
17
15.3k
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
18
9.27k
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
19
104k
bool CCoinsView::BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) { return false; }
20
4.63k
std::unique_ptr<CCoinsViewCursor> CCoinsView::Cursor() const { return nullptr; }
21
22
bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
23
4.63k
{
24
4.63k
    return GetCoin(outpoint).has_value();
25
4.63k
}
26
27
6.11M
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
28
2.71M
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
1.02M
uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
31
10.1k
std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
32
3.24M
void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
33
177k
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
10.1k
size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
36
37
CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn, bool deterministic) :
38
3.49M
    CCoinsViewBacked(baseIn), m_deterministic(deterministic),
39
3.49M
    cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic), CCoinsMap::key_equal{}, &m_cache_coins_memory_resource)
40
3.49M
{
41
3.49M
    m_sentinel.second.SelfRef(m_sentinel);
42
3.49M
}
43
44
7.25M
size_t CCoinsViewCache::DynamicMemoryUsage() const {
45
7.25M
    return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
46
7.25M
}
47
48
78.7M
CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
49
78.7M
    const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);
50
78.7M
    if (inserted) {
51
15.3M
        if (auto coin{base->GetCoin(outpoint)}) {
52
8.11M
            ret->second.coin = std::move(*coin);
53
8.11M
            cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
54
8.11M
            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
5.52k
                CCoinsCacheEntry::SetFresh(*ret, m_sentinel);
57
5.52k
            }
58
8.11M
        } else {
59
7.25M
            cacheCoins.erase(ret);
60
7.25M
            return cacheCoins.end();
61
7.25M
        }
62
15.3M
    }
63
71.5M
    return ret;
64
78.7M
}
65
66
std::optional<Coin> CCoinsViewCache::GetCoin(const COutPoint& outpoint) const
67
30.5M
{
68
30.5M
    if (auto it{FetchCoin(outpoint)}; it != cacheCoins.end() && !it->second.coin.IsSpent()) return it->second.coin;
69
2.34M
    return std::nullopt;
70
30.5M
}
71
72
8.23M
void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
73
8.23M
    assert(!coin.IsSpent());
74
8.23M
    if (coin.out.scriptPubKey.IsUnspendable()) return;
75
7.69M
    CCoinsMap::iterator it;
76
7.69M
    bool inserted;
77
7.69M
    std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
78
7.69M
    bool fresh = false;
79
7.69M
    if (!inserted) {
80
503k
        cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
81
503k
    }
82
7.69M
    if (!possible_overwrite) {
83
6.08M
        if (!it->second.coin.IsSpent()) {
84
24.6k
            throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
85
24.6k
        }
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
6.05M
        fresh = !it->second.IsDirty();
100
6.05M
    }
101
7.67M
    it->second.coin = std::move(coin);
102
7.67M
    CCoinsCacheEntry::SetDirty(*it, m_sentinel);
103
7.67M
    if (fresh) CCoinsCacheEntry::SetFresh(*it, m_sentinel);
104
7.67M
    cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
105
7.67M
    TRACEPOINT(utxocache, add,
106
7.67M
           outpoint.hash.data(),
107
7.67M
           (uint32_t)outpoint.n,
108
7.67M
           (uint32_t)it->second.coin.nHeight,
109
7.67M
           (int64_t)it->second.coin.out.nValue,
110
7.67M
           (bool)it->second.coin.IsCoinBase());
111
7.67M
}
112
113
402k
void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) {
114
402k
    cachedCoinsUsage += coin.DynamicMemoryUsage();
115
402k
    auto [it, inserted] = cacheCoins.try_emplace(std::move(outpoint), std::move(coin));
116
402k
    if (inserted) CCoinsCacheEntry::SetDirty(*it, m_sentinel);
117
402k
}
118
119
732k
void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
120
732k
    bool fCoinbase = tx.IsCoinBase();
121
732k
    const Txid& txid = tx.GetHash();
122
7.91M
    for (size_t i = 0; i < tx.vout.size(); ++i) {
123
7.17M
        bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
124
        // Coinbase transactions can always be overwritten, in order to correctly
125
        // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
126
7.17M
        cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
127
7.17M
    }
128
732k
}
129
130
1.09M
bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
131
1.09M
    CCoinsMap::iterator it = FetchCoin(outpoint);
132
1.09M
    if (it == cacheCoins.end()) return false;
133
701k
    cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
134
701k
    TRACEPOINT(utxocache, spent,
135
701k
           outpoint.hash.data(),
136
701k
           (uint32_t)outpoint.n,
137
701k
           (uint32_t)it->second.coin.nHeight,
138
701k
           (int64_t)it->second.coin.out.nValue,
139
701k
           (bool)it->second.coin.IsCoinBase());
140
701k
    if (moveout) {
141
355k
        *moveout = std::move(it->second.coin);
142
355k
    }
143
701k
    if (it->second.IsFresh()) {
144
114k
        cacheCoins.erase(it);
145
586k
    } else {
146
586k
        CCoinsCacheEntry::SetDirty(*it, m_sentinel);
147
586k
        it->second.coin.Clear();
148
586k
    }
149
701k
    return true;
150
1.09M
}
151
152
static const Coin coinEmpty;
153
154
30.1M
const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
155
30.1M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
156
30.1M
    if (it == cacheCoins.end()) {
157
898k
        return coinEmpty;
158
29.2M
    } else {
159
29.2M
        return it->second.coin;
160
29.2M
    }
161
30.1M
}
162
163
17.0M
bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
164
17.0M
    CCoinsMap::const_iterator it = FetchCoin(outpoint);
165
17.0M
    return (it != cacheCoins.end() && !it->second.coin.IsSpent());
166
17.0M
}
167
168
11.8M
bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
169
11.8M
    CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
170
11.8M
    return (it != cacheCoins.end() && !it->second.coin.IsSpent());
171
11.8M
}
172
173
5.02M
uint256 CCoinsViewCache::GetBestBlock() const {
174
5.02M
    if (hashBlock.IsNull())
175
1.56M
        hashBlock = base->GetBestBlock();
176
5.02M
    return hashBlock;
177
5.02M
}
178
179
255k
void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
180
255k
    hashBlock = hashBlockIn;
181
255k
}
182
183
388k
bool CCoinsViewCache::BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlockIn) {
184
938k
    for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)) {
185
        // Ignore non-dirty entries (optimization).
186
559k
        if (!it->second.IsDirty()) {
187
2.03k
            continue;
188
2.03k
        }
189
557k
        CCoinsMap::iterator itUs = cacheCoins.find(it->first);
190
557k
        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
458k
            if (!(it->second.IsFresh() && it->second.coin.IsSpent())) {
194
                // Create the coin in the parent cache, move the data up
195
                // and mark it as dirty.
196
453k
                itUs = cacheCoins.try_emplace(it->first).first;
197
453k
                CCoinsCacheEntry& entry{itUs->second};
198
453k
                if (cursor.WillErase(*it)) {
199
                    // Since this entry will be erased,
200
                    // we can move the coin into us instead of copying it
201
318k
                    entry.coin = std::move(it->second.coin);
202
318k
                } else {
203
135k
                    entry.coin = it->second.coin;
204
135k
                }
205
453k
                cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
206
453k
                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
453k
                if (it->second.IsFresh()) CCoinsCacheEntry::SetFresh(*itUs, m_sentinel);
211
453k
            }
212
458k
        } else {
213
            // Found the entry in the parent cache
214
99.0k
            if (it->second.IsFresh() && !itUs->second.coin.IsSpent()) {
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
9.03k
                throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
220
9.03k
            }
221
222
89.9k
            if (itUs->second.IsFresh() && it->second.coin.IsSpent()) {
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
5.45k
                cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
226
5.45k
                cacheCoins.erase(itUs);
227
84.5k
            } else {
228
                // A normal modification.
229
84.5k
                cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
230
84.5k
                if (cursor.WillErase(*it)) {
231
                    // Since this entry will be erased,
232
                    // we can move the coin into us instead of copying it
233
56.6k
                    itUs->second.coin = std::move(it->second.coin);
234
56.6k
                } else {
235
27.9k
                    itUs->second.coin = it->second.coin;
236
27.9k
                }
237
84.5k
                cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
238
84.5k
                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
84.5k
            }
244
89.9k
        }
245
557k
    }
246
379k
    hashBlock = hashBlockIn;
247
379k
    return true;
248
388k
}
249
250
2.08M
bool CCoinsViewCache::Flush() {
251
2.08M
    auto cursor{CoinsViewCacheCursor(cachedCoinsUsage, m_sentinel, cacheCoins, /*will_erase=*/true)};
252
2.08M
    bool fOk = base->BatchWrite(cursor, hashBlock);
253
2.08M
    if (fOk) {
254
2.05M
        cacheCoins.clear();
255
2.05M
        ReallocateCache();
256
2.05M
    }
257
2.08M
    cachedCoinsUsage = 0;
258
2.08M
    return fOk;
259
2.08M
}
260
261
bool CCoinsViewCache::Sync()
262
2.76M
{
263
2.76M
    auto cursor{CoinsViewCacheCursor(cachedCoinsUsage, m_sentinel, cacheCoins, /*will_erase=*/false)};
264
2.76M
    bool fOk = base->BatchWrite(cursor, hashBlock);
265
2.76M
    if (fOk) {
266
2.68M
        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
2.68M
    }
271
2.76M
    return fOk;
272
2.76M
}
273
274
void CCoinsViewCache::Uncache(const COutPoint& hash)
275
6.09M
{
276
6.09M
    CCoinsMap::iterator it = cacheCoins.find(hash);
277
6.09M
    if (it != cacheCoins.end() && !it->second.IsDirty() && !it->second.IsFresh()) {
278
1.04M
        cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
279
1.04M
        TRACEPOINT(utxocache, uncache,
280
1.04M
               hash.hash.data(),
281
1.04M
               (uint32_t)hash.n,
282
1.04M
               (uint32_t)it->second.coin.nHeight,
283
1.04M
               (int64_t)it->second.coin.out.nValue,
284
1.04M
               (bool)it->second.coin.IsCoinBase());
285
1.04M
        cacheCoins.erase(it);
286
1.04M
    }
287
6.09M
}
288
289
3.93M
unsigned int CCoinsViewCache::GetCacheSize() const {
290
3.93M
    return cacheCoins.size();
291
3.93M
}
292
293
bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
294
1.50M
{
295
1.50M
    if (!tx.IsCoinBase()) {
296
7.01M
        for (unsigned int i = 0; i < tx.vin.size(); i++) {
297
5.52M
            if (!HaveCoin(tx.vin[i].prevout)) {
298
14.9k
                return false;
299
14.9k
            }
300
5.52M
        }
301
1.50M
    }
302
1.49M
    return true;
303
1.50M
}
304
305
void CCoinsViewCache::ReallocateCache()
306
2.10M
{
307
    // Cache should be empty when we're calling this.
308
2.10M
    assert(cacheCoins.size() == 0);
309
2.10M
    cacheCoins.~CCoinsMap();
310
2.10M
    m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
311
2.10M
    ::new (&m_cache_coins_memory_resource) CCoinsMapMemoryResource{};
312
2.10M
    ::new (&cacheCoins) CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic}, CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
313
2.10M
}
314
315
void CCoinsViewCache::SanityCheck() const
316
52.2k
{
317
52.2k
    size_t recomputed_usage = 0;
318
52.2k
    size_t count_flagged = 0;
319
152k
    for (const auto& [_, entry] : cacheCoins) {
320
152k
        unsigned attr = 0;
321
152k
        if (entry.IsDirty()) attr |= 1;
322
152k
        if (entry.IsFresh()) attr |= 2;
323
152k
        if (entry.coin.IsSpent()) attr |= 4;
324
        // Only 5 combinations are possible.
325
152k
        assert(attr != 2 && attr != 4 && attr != 7);
326
327
        // Recompute cachedCoinsUsage.
328
152k
        recomputed_usage += entry.coin.DynamicMemoryUsage();
329
330
        // Count the number of entries we expect in the linked list.
331
152k
        if (entry.IsDirty() || entry.IsFresh()) ++count_flagged;
332
152k
    }
333
    // Iterate over the linked list of flagged entries.
334
52.2k
    size_t count_linked = 0;
335
84.7k
    for (auto it = m_sentinel.second.Next(); it != &m_sentinel; it = it->second.Next()) {
336
        // Verify linked list integrity.
337
32.5k
        assert(it->second.Next()->second.Prev() == it);
338
32.5k
        assert(it->second.Prev()->second.Next() == it);
339
        // Verify they are actually flagged.
340
32.5k
        assert(it->second.IsDirty() || it->second.IsFresh());
341
        // Count the number of entries actually in the list.
342
32.5k
        ++count_linked;
343
32.5k
    }
344
52.2k
    assert(count_linked == count_flagged);
345
52.2k
    assert(recomputed_usage == cachedCoinsUsage);
346
52.2k
}
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
2.71M
{
365
2.71M
    try {
366
2.71M
        return func();
367
2.71M
    } 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());
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
2.71M
}
coins.cpp:_ZL20ExecuteBackedWrapperISt8optionalI4CoinEZNK22CCoinsViewErrorCatcher7GetCoinERK9COutPointE3$_0ET_T0_RKSt6vectorISt8functionIFvvEESaISD_EE
Line
Count
Source
364
2.71M
{
365
2.71M
    try {
366
2.71M
        return func();
367
2.71M
    } 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());
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
2.71M
}
Unexecuted instantiation: coins.cpp:_ZL20ExecuteBackedWrapperIbZNK22CCoinsViewErrorCatcher8HaveCoinERK9COutPointE3$_0ET_T0_RKSt6vectorISt8functionIFvvEESaISA_EE
379
380
std::optional<Coin> CCoinsViewErrorCatcher::GetCoin(const COutPoint& outpoint) const
381
2.71M
{
382
2.71M
    return ExecuteBackedWrapper<std::optional<Coin>>([&]() { return CCoinsViewBacked::GetCoin(outpoint); }, m_err_callbacks);
383
2.71M
}
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
}