Coverage Report

Created: 2025-10-29 16:48

/root/bitcoin/src/coins.h
Line
Count
Source (jump to first uncovered line)
1
// Copyright (c) 2009-2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#ifndef BITCOIN_COINS_H
7
#define BITCOIN_COINS_H
8
9
#include <compressor.h>
10
#include <core_memusage.h>
11
#include <memusage.h>
12
#include <primitives/transaction.h>
13
#include <serialize.h>
14
#include <support/allocators/pool.h>
15
#include <uint256.h>
16
#include <util/check.h>
17
#include <util/hasher.h>
18
19
#include <cassert>
20
#include <cstdint>
21
22
#include <functional>
23
#include <unordered_map>
24
25
/**
26
 * A UTXO entry.
27
 *
28
 * Serialized format:
29
 * - VARINT((coinbase ? 1 : 0) | (height << 1))
30
 * - the non-spent CTxOut (via TxOutCompression)
31
 */
32
class Coin
33
{
34
public:
35
    //! unspent transaction output
36
    CTxOut out;
37
38
    //! whether containing transaction was a coinbase
39
    unsigned int fCoinBase : 1;
40
41
    //! at which height this containing transaction was included in the active block chain
42
    uint32_t nHeight : 31;
43
44
    //! construct a Coin from a CTxOut and height/coinbase information.
45
0
    Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
46
0
    Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
47
48
0
    void Clear() {
49
0
        out.SetNull();
50
0
        fCoinBase = false;
51
0
        nHeight = 0;
52
0
    }
53
54
    //! empty constructor
55
0
    Coin() : fCoinBase(false), nHeight(0) { }
56
57
0
    bool IsCoinBase() const {
58
0
        return fCoinBase;
59
0
    }
60
61
    template<typename Stream>
62
0
    void Serialize(Stream &s) const {
63
0
        assert(!IsSpent());
64
0
        uint32_t code = nHeight * uint32_t{2} + fCoinBase;
65
0
        ::Serialize(s, VARINT(code));
66
0
        ::Serialize(s, Using<TxOutCompression>(out));
67
0
    }
Unexecuted instantiation: _ZNK4Coin9SerializeI10DataStreamEEvRT_
Unexecuted instantiation: _ZNK4Coin9SerializeI8AutoFileEEvRT_
68
69
    template<typename Stream>
70
0
    void Unserialize(Stream &s) {
71
0
        uint32_t code = 0;
72
0
        ::Unserialize(s, VARINT(code));
73
0
        nHeight = code >> 1;
74
0
        fCoinBase = code & 1;
75
0
        ::Unserialize(s, Using<TxOutCompression>(out));
76
0
    }
Unexecuted instantiation: _ZN4Coin11UnserializeI10DataStreamEEvRT_
Unexecuted instantiation: _ZN4Coin11UnserializeI8AutoFileEEvRT_
77
78
    /** Either this coin never existed (see e.g. coinEmpty in coins.cpp), or it
79
      * did exist and has been spent.
80
      */
81
0
    bool IsSpent() const {
82
0
        return out.IsNull();
83
0
    }
84
85
0
    size_t DynamicMemoryUsage() const {
86
0
        return memusage::DynamicUsage(out.scriptPubKey);
87
0
    }
88
};
89
90
struct CCoinsCacheEntry;
91
using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
92
93
/**
94
 * A Coin in one level of the coins database caching hierarchy.
95
 *
96
 * A coin can either be:
97
 * - unspent or spent (in which case the Coin object will be nulled out - see Coin.Clear())
98
 * - DIRTY or not DIRTY
99
 * - FRESH or not FRESH
100
 *
101
 * Out of these 2^3 = 8 states, only some combinations are valid:
102
 * - unspent, FRESH, DIRTY (e.g. a new coin created in the cache)
103
 * - unspent, not FRESH, DIRTY (e.g. a coin changed in the cache during a reorg)
104
 * - unspent, not FRESH, not DIRTY (e.g. an unspent coin fetched from the parent cache)
105
 * - spent, FRESH, not DIRTY (e.g. a spent coin fetched from the parent cache)
106
 * - spent, not FRESH, DIRTY (e.g. a coin is spent and spentness needs to be flushed to the parent)
107
 */
108
struct CCoinsCacheEntry
109
{
110
private:
111
    /**
112
     * These are used to create a doubly linked list of flagged entries.
113
     * They are set in SetDirty, SetFresh, and unset in SetClean.
114
     * A flagged entry is any entry that is either DIRTY, FRESH, or both.
115
     *
116
     * DIRTY entries are tracked so that only modified entries can be passed to
117
     * the parent cache for batch writing. This is a performance optimization
118
     * compared to giving all entries in the cache to the parent and having the
119
     * parent scan for only modified entries.
120
     *
121
     * FRESH-but-not-DIRTY coins can not occur in practice, since that would
122
     * mean a spent coin exists in the parent CCoinsView and not in the child
123
     * CCoinsViewCache. Nevertheless, if a spent coin is retrieved from the
124
     * parent cache, the FRESH-but-not-DIRTY coin will be tracked by the linked
125
     * list and deleted when Sync or Flush is called on the CCoinsViewCache.
126
     */
127
    CoinsCachePair* m_prev{nullptr};
128
    CoinsCachePair* m_next{nullptr};
129
    uint8_t m_flags{0};
130
131
    //! Adding a flag requires a reference to the sentinel of the flagged pair linked list.
132
    static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
133
0
    {
134
0
        Assume(flags & (DIRTY | FRESH));
135
0
        if (!pair.second.m_flags) {
136
0
            Assume(!pair.second.m_prev && !pair.second.m_next);
137
0
            pair.second.m_prev = sentinel.second.m_prev;
138
0
            pair.second.m_next = &sentinel;
139
0
            sentinel.second.m_prev = &pair;
140
0
            pair.second.m_prev->second.m_next = &pair;
141
0
        }
142
0
        Assume(pair.second.m_prev && pair.second.m_next);
143
0
        pair.second.m_flags |= flags;
144
0
    }
145
146
public:
147
    Coin coin; // The actual cached data.
148
149
    enum Flags {
150
        /**
151
         * DIRTY means the CCoinsCacheEntry is potentially different from the
152
         * version in the parent cache. Failure to mark a coin as DIRTY when
153
         * it is potentially different from the parent cache will cause a
154
         * consensus failure, since the coin's state won't get written to the
155
         * parent when the cache is flushed.
156
         */
157
        DIRTY = (1 << 0),
158
        /**
159
         * FRESH means the parent cache does not have this coin or that it is a
160
         * spent coin in the parent cache. If a FRESH coin in the cache is
161
         * later spent, it can be deleted entirely and doesn't ever need to be
162
         * flushed to the parent. This is a performance optimization. Marking a
163
         * coin as FRESH when it exists unspent in the parent cache will cause a
164
         * consensus failure, since it might not be deleted from the parent
165
         * when this cache is flushed.
166
         */
167
        FRESH = (1 << 1),
168
    };
169
170
0
    CCoinsCacheEntry() noexcept = default;
171
0
    explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
172
    ~CCoinsCacheEntry()
173
1
    {
174
1
        SetClean();
175
1
    }
176
177
0
    static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
178
0
    static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
179
180
    void SetClean() noexcept
181
1
    {
182
1
        if (!m_flags) return;
183
1
        m_next->second.m_prev = m_prev;
184
1
        m_prev->second.m_next = m_next;
185
1
        m_flags = 0;
186
1
        m_prev = m_next = nullptr;
187
1
    }
188
0
    bool IsDirty() const noexcept { return m_flags & DIRTY; }
189
0
    bool IsFresh() const noexcept { return m_flags & FRESH; }
190
191
    //! Only call Next when this entry is DIRTY, FRESH, or both
192
    CoinsCachePair* Next() const noexcept
193
0
    {
194
0
        Assume(m_flags);
195
0
        return m_next;
196
0
    }
197
198
    //! Only call Prev when this entry is DIRTY, FRESH, or both
199
    CoinsCachePair* Prev() const noexcept
200
0
    {
201
0
        Assume(m_flags);
202
0
        return m_prev;
203
0
    }
204
205
    //! Only use this for initializing the linked list sentinel
206
    void SelfRef(CoinsCachePair& pair) noexcept
207
0
    {
208
0
        Assume(&pair.second == this);
209
0
        m_prev = &pair;
210
0
        m_next = &pair;
211
        // Set sentinel to DIRTY so we can call Next on it
212
0
        m_flags = DIRTY;
213
0
    }
214
};
215
216
/**
217
 * PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size
218
 * of 4 pointers. We do not know the exact node size used in the std::unordered_node implementation
219
 * because it is implementation defined. Most implementations have an overhead of 1 or 2 pointers,
220
 * so nodes can be connected in a linked list, and in some cases the hash value is stored as well.
221
 * Using an additional sizeof(void*)*4 for MAX_BLOCK_SIZE_BYTES should thus be sufficient so that
222
 * all implementations can allocate the nodes from the PoolAllocator.
223
 */
224
using CCoinsMap = std::unordered_map<COutPoint,
225
                                     CCoinsCacheEntry,
226
                                     SaltedOutpointHasher,
227
                                     std::equal_to<COutPoint>,
228
                                     PoolAllocator<CoinsCachePair,
229
                                                   sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
230
231
using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
232
233
/** Cursor for iterating over CoinsView state */
234
class CCoinsViewCursor
235
{
236
public:
237
0
    CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
238
0
    virtual ~CCoinsViewCursor() = default;
239
240
    virtual bool GetKey(COutPoint &key) const = 0;
241
    virtual bool GetValue(Coin &coin) const = 0;
242
243
    virtual bool Valid() const = 0;
244
    virtual void Next() = 0;
245
246
    //! Get best block at the time this cursor was created
247
0
    const uint256 &GetBestBlock() const { return hashBlock; }
248
private:
249
    uint256 hashBlock;
250
};
251
252
/**
253
 * Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
254
 *
255
 * This is a helper struct to encapsulate the diverging logic between a non-erasing
256
 * CCoinsViewCache::Sync and an erasing CCoinsViewCache::Flush. This allows the receiver
257
 * of CCoinsView::BatchWrite to iterate through the flagged entries without knowing
258
 * the caller's intent.
259
 *
260
 * However, the receiver can still call CoinsViewCacheCursor::WillErase to see if the
261
 * caller will erase the entry after BatchWrite returns. If so, the receiver can
262
 * perform optimizations such as moving the coin out of the CCoinsCachEntry instead
263
 * of copying it.
264
 */
265
struct CoinsViewCacheCursor
266
{
267
    //! If will_erase is not set, iterating through the cursor will erase spent coins from the map,
268
    //! and other coins will be unflagged (removing them from the linked list).
269
    //! If will_erase is set, the underlying map and linked list will not be modified,
270
    //! as the caller is expected to wipe the entire map anyway.
271
    //! This is an optimization compared to erasing all entries as the cursor iterates them when will_erase is set.
272
    //! Calling CCoinsMap::clear() afterwards is faster because a CoinsCachePair cannot be coerced back into a
273
    //! CCoinsMap::iterator to be erased, and must therefore be looked up again by key in the CCoinsMap before being erased.
274
    CoinsViewCacheCursor(CoinsCachePair& sentinel LIFETIMEBOUND,
275
                         CCoinsMap& map LIFETIMEBOUND,
276
                         bool will_erase) noexcept
277
0
        : m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
278
279
0
    inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
280
0
    inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
281
282
    //! Return the next entry after current, possibly erasing current
283
    inline CoinsCachePair* NextAndMaybeErase(CoinsCachePair& current) noexcept
284
0
    {
285
0
        const auto next_entry{current.second.Next()};
286
        // If we are not going to erase the cache, we must still erase spent entries.
287
        // Otherwise, clear the state of the entry.
288
0
        if (!m_will_erase) {
289
0
            if (current.second.coin.IsSpent()) {
290
0
                assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin
291
0
                m_map.erase(current.first);
292
0
            } else {
293
0
                current.second.SetClean();
294
0
            }
295
0
        }
296
0
        return next_entry;
297
0
    }
298
299
0
    inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
300
private:
301
    CoinsCachePair& m_sentinel;
302
    CCoinsMap& m_map;
303
    bool m_will_erase;
304
};
305
306
/** Abstract view on the open txout dataset. */
307
class CCoinsView
308
{
309
public:
310
    //! Retrieve the Coin (unspent transaction output) for a given outpoint.
311
    virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const;
312
313
    //! Just check whether a given outpoint is unspent.
314
    virtual bool HaveCoin(const COutPoint &outpoint) const;
315
316
    //! Retrieve the block hash whose state this CCoinsView currently represents
317
    virtual uint256 GetBestBlock() const;
318
319
    //! Retrieve the range of blocks that may have been only partially written.
320
    //! If the database is in a consistent state, the result is the empty vector.
321
    //! Otherwise, a two-element vector is returned consisting of the new and
322
    //! the old block hash, in that order.
323
    virtual std::vector<uint256> GetHeadBlocks() const;
324
325
    //! Do a bulk modification (multiple Coin changes + BestBlock change).
326
    //! The passed cursor is used to iterate through the coins.
327
    virtual bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
328
329
    //! Get a cursor to iterate over the whole state
330
    virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
331
332
    //! As we use CCoinsViews polymorphically, have a virtual destructor
333
3
    virtual ~CCoinsView() = default;
334
335
    //! Estimate database size (0 if not implemented)
336
0
    virtual size_t EstimateSize() const { return 0; }
337
};
338
339
340
/** CCoinsView backed by another CCoinsView */
341
class CCoinsViewBacked : public CCoinsView
342
{
343
protected:
344
    CCoinsView *base;
345
346
public:
347
    CCoinsViewBacked(CCoinsView *viewIn);
348
    std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
349
    bool HaveCoin(const COutPoint &outpoint) const override;
350
    uint256 GetBestBlock() const override;
351
    std::vector<uint256> GetHeadBlocks() const override;
352
    void SetBackend(CCoinsView &viewIn);
353
    bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
354
    std::unique_ptr<CCoinsViewCursor> Cursor() const override;
355
    size_t EstimateSize() const override;
356
};
357
358
359
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
360
class CCoinsViewCache : public CCoinsViewBacked
361
{
362
private:
363
    const bool m_deterministic;
364
365
protected:
366
    /**
367
     * Make mutable so that we can "fill the cache" even from Get-methods
368
     * declared as "const".
369
     */
370
    mutable uint256 hashBlock;
371
    mutable CCoinsMapMemoryResource m_cache_coins_memory_resource{};
372
    /* The starting sentinel of the flagged entry circular doubly linked list. */
373
    mutable CoinsCachePair m_sentinel;
374
    mutable CCoinsMap cacheCoins;
375
376
    /* Cached dynamic memory usage for the inner Coin objects. */
377
    mutable size_t cachedCoinsUsage{0};
378
379
public:
380
    CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
381
382
    /**
383
     * By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache.
384
     */
385
    CCoinsViewCache(const CCoinsViewCache &) = delete;
386
387
    // Standard CCoinsView methods
388
    std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
389
    bool HaveCoin(const COutPoint &outpoint) const override;
390
    uint256 GetBestBlock() const override;
391
    void SetBestBlock(const uint256 &hashBlock);
392
    bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
393
0
    std::unique_ptr<CCoinsViewCursor> Cursor() const override {
394
0
        throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
395
0
    }
396
397
    /**
398
     * Check if we have the given utxo already loaded in this cache.
399
     * The semantics are the same as HaveCoin(), but no calls to
400
     * the backing CCoinsView are made.
401
     */
402
    bool HaveCoinInCache(const COutPoint &outpoint) const;
403
404
    /**
405
     * Return a reference to Coin in the cache, or coinEmpty if not found. This is
406
     * more efficient than GetCoin.
407
     *
408
     * Generally, do not hold the reference returned for more than a short scope.
409
     * While the current implementation allows for modifications to the contents
410
     * of the cache while holding the reference, this behavior should not be relied
411
     * on! To be safe, best to not hold the returned reference through any other
412
     * calls to this cache.
413
     */
414
    const Coin& AccessCoin(const COutPoint &output) const;
415
416
    /**
417
     * Add a coin. Set possible_overwrite to true if an unspent version may
418
     * already exist in the cache.
419
     */
420
    void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
421
422
    /**
423
     * Emplace a coin into cacheCoins without performing any checks, marking
424
     * the emplaced coin as dirty.
425
     *
426
     * NOT FOR GENERAL USE. Used only when loading coins from a UTXO snapshot.
427
     * @sa ChainstateManager::PopulateAndValidateSnapshot()
428
     */
429
    void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
430
431
    /**
432
     * Spend a coin. Pass moveto in order to get the deleted data.
433
     * If no unspent output exists for the passed outpoint, this call
434
     * has no effect.
435
     */
436
    bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
437
438
    /**
439
     * Push the modifications applied to this cache to its base and wipe local state.
440
     * Failure to call this method or Sync() before destruction will cause the changes
441
     * to be forgotten.
442
     * If false is returned, the state of this cache (and its backing view) will be undefined.
443
     */
444
    bool Flush();
445
446
    /**
447
     * Push the modifications applied to this cache to its base while retaining
448
     * the contents of this cache (except for spent coins, which we erase).
449
     * Failure to call this method or Flush() before destruction will cause the changes
450
     * to be forgotten.
451
     * If false is returned, the state of this cache (and its backing view) will be undefined.
452
     */
453
    bool Sync();
454
455
    /**
456
     * Removes the UTXO with the given outpoint from the cache, if it is
457
     * not modified.
458
     */
459
    void Uncache(const COutPoint &outpoint);
460
461
    //! Calculate the size of the cache (in number of transaction outputs)
462
    unsigned int GetCacheSize() const;
463
464
    //! Calculate the size of the cache (in bytes)
465
    size_t DynamicMemoryUsage() const;
466
467
    //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
468
    bool HaveInputs(const CTransaction& tx) const;
469
470
    //! Force a reallocation of the cache map. This is required when downsizing
471
    //! the cache because the map's allocator may be hanging onto a lot of
472
    //! memory despite having called .clear().
473
    //!
474
    //! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory
475
    void ReallocateCache();
476
477
    //! Run an internal sanity check on the cache data structure. */
478
    void SanityCheck() const;
479
480
private:
481
    /**
482
     * @note this is marked const, but may actually append to `cacheCoins`, increasing
483
     * memory usage.
484
     */
485
    CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
486
};
487
488
//! Utility function to add all of a transaction's outputs to a cache.
489
//! When check is false, this assumes that overwrites are only possible for coinbase transactions.
490
//! When check is true, the underlying view may be queried to determine whether an addition is
491
//! an overwrite.
492
// TODO: pass in a boolean to limit these possible overwrites to known
493
// (pre-BIP34) cases.
494
void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
495
496
//! Utility function to find any unspent output with a given txid.
497
//! This function can be quite expensive because in the event of a transaction
498
//! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK
499
//! lookups to database, so it should be used with care.
500
const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
501
502
/**
503
 * This is a minimally invasive approach to shutdown on LevelDB read errors from the
504
 * chainstate, while keeping user interface out of the common library, which is shared
505
 * between bitcoind, and bitcoin-qt and non-server tools.
506
 *
507
 * Writes do not need similar protection, as failure to write is handled by the caller.
508
*/
509
class CCoinsViewErrorCatcher final : public CCoinsViewBacked
510
{
511
public:
512
0
    explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
513
514
0
    void AddReadErrCallback(std::function<void()> f) {
515
0
        m_err_callbacks.emplace_back(std::move(f));
516
0
    }
517
518
    std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
519
    bool HaveCoin(const COutPoint &outpoint) const override;
520
521
private:
522
    /** A list of callbacks to execute upon leveldb read error. */
523
    std::vector<std::function<void()>> m_err_callbacks;
524
525
};
526
527
#endif // BITCOIN_COINS_H