LCOV - code coverage report
Current view: top level - src - coins.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 95.5 % 89 85
Test Date: 2025-10-16 05:04:40 Functions: 80.0 % 10 8
Branches: 61.5 % 576 354

             Branch data     Line data    Source code
       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   [ +  -  +  -  :    84611121 : 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         [ +  + ]:          61 :     Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
      46         [ +  - ]:    19503997 :     Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
           [ +  +  +  + ]
      47                 :             : 
      48                 :    11916118 :     void Clear() {
      49                 :    11916118 :         out.SetNull();
      50                 :    11916118 :         fCoinBase = false;
      51   [ -  +  +  +  :    11916118 :         nHeight = 0;
                   +  - ]
      52                 :    11848437 :     }
      53                 :             : 
      54                 :             :     //! empty constructor
      55   [ +  -  +  -  :    73600152 :     Coin() : fCoinBase(false), nHeight(0) { }
          #  #  #  #  #  
           #  #  # ][ +  
          -  +  -  +  -  
          -  +  -  +  +  
           + ][ +  -  +  
           -  +  - ][ -  
             -  -  -  +  
                      - ]
      56                 :             : 
      57                 :    12205533 :     bool IsCoinBase() const {
      58         [ +  + ]:    12205533 :         return fCoinBase;
           [ +  +  +  + ]
      59                 :             :     }
      60                 :             : 
      61                 :             :     template<typename Stream>
      62                 :      297212 :     void Serialize(Stream &s) const {
      63         [ -  + ]:      297212 :         assert(!IsSpent());
      64                 :      297212 :         uint32_t code = nHeight * uint32_t{2} + fCoinBase;
      65                 :      297212 :         ::Serialize(s, VARINT(code));
      66                 :      297212 :         ::Serialize(s, Using<TxOutCompression>(out));
      67                 :      297212 :     }
      68                 :             : 
      69                 :             :     template<typename Stream>
      70                 :      317803 :     void Unserialize(Stream &s) {
      71                 :      317803 :         uint32_t code = 0;
      72                 :      317803 :         ::Unserialize(s, VARINT(code));
      73                 :      317803 :         nHeight = code >> 1;
      74                 :      317803 :         fCoinBase = code & 1;
      75                 :      317803 :         ::Unserialize(s, Using<TxOutCompression>(out));
      76                 :      317800 :     }
      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         [ +  - ]:   116044810 :     bool IsSpent() const {
      82 [ +  + ][ +  +  :   115264971 :         return out.IsNull();
          +  +  -  +  +  
          -  +  -  +  -  
          +  +  +  +  +  
          +  +  +  +  -  
          +  +  +  +  +  
             +  +  +  -  
           + ][ -  -  -  
          +  +  -  -  +  
           -  + ][ -  +  
          +  +  -  +  #  
           #  #  # ][ +  
          +  -  +  +  +  
          +  -  -  +  +  
          +  +  +  -  +  
          -  +  +  +  -  
           + ][ +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  -  +  +  +  
             +  +  +  + ]
      83                 :             :     }
      84                 :             : 
      85                 :    46007839 :     size_t DynamicMemoryUsage() const {
      86   [ -  +  +  +  :    46808792 :         return memusage::DynamicUsage(out.scriptPubKey);
          -  +  -  +  -  
          -  -  +  +  +  
          +  -  +  +  +  
          +  -  +  +  +  
          +  +  +  +  +  
          +  -  +  -  +  
          +  +  +  +  -  
           + ][ +  +  +  
          +  +  +  -  +  
          -  -  +  +  +  
          +  +  -  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
                   +  + ]
      87                 :             :     }
      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                 :    50888905 :     static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
     133                 :             :     {
     134                 :    50888905 :         Assume(flags & (DIRTY | FRESH));
     135                 :    50888905 :         if (!pair.second.m_flags) {
     136                 :    31685577 :             Assume(!pair.second.m_prev && !pair.second.m_next);
     137                 :    31685577 :             pair.second.m_prev = sentinel.second.m_prev;
     138                 :    31685577 :             pair.second.m_next = &sentinel;
     139                 :    31685577 :             sentinel.second.m_prev = &pair;
     140                 :    31685577 :             pair.second.m_prev->second.m_next = &pair;
     141                 :             :         }
     142                 :    50888905 :         Assume(pair.second.m_prev && pair.second.m_next);
     143                 :    50888905 :         pair.second.m_flags |= flags;
     144                 :             :     }
     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                 :    60292437 :     CCoinsCacheEntry() noexcept = default;
     171                 :        6049 :     explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
     172                 :    60298806 :     ~CCoinsCacheEntry()
     173                 :             :     {
     174                 :   120597612 :         SetClean();
     175                 :    60298806 :     }
     176                 :             : 
     177   [ +  -  +  +  :    63044870 :     static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
          +  +  +  +  +  
             -  +  +  +  
           + ][ +  -  #  
          #  #  #  #  #  
             #  #  #  # ]
           [ +  -  +  +  
          +  +  +  +  +  
             -  +  +  +  
                      + ]
     178   [ +  -  +  -  :    19529612 :     static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
             -  +  +  - ]
           [ +  +  #  #  
             #  #  #  # ]
     179                 :             : 
     180                 :    60356907 :     void SetClean() noexcept
     181                 :             :     {
     182 [ +  + ][ +  -  :    60298812 :         if (!m_flags) return;
          -  +  +  -  -  
                      - ]
     183                 :    32211741 :         m_next->second.m_prev = m_prev;
     184                 :    32211741 :         m_prev->second.m_next = m_next;
     185                 :    32211741 :         m_flags = 0;
     186                 :    32211741 :         m_prev = m_next = nullptr;
     187                 :             :     }
     188   [ +  -  +  -  :    20723764 :     bool IsDirty() const noexcept { return m_flags & DIRTY; }
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
           -  +  - ][ +  
          +  -  -  +  +  
          -  +  #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
           # ][ +  +  +  
             +  +  +  +  
                      + ]
     189   [ +  +  +  +  :    12985276 :     bool IsFresh() const noexcept { return m_flags & FRESH; }
          +  +  +  +  +  
           + ][ +  +  +  
          +  +  +  +  +  
                   +  + ]
     190                 :             : 
     191                 :             :     //! Only call Next when this entry is DIRTY, FRESH, or both
     192                 :     1423890 :     CoinsCachePair* Next() const noexcept
     193                 :             :     {
     194                 :     1423891 :         Assume(m_flags);
     195   [ +  +  +  -  :     1085200 :         return m_next;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
             +  -  +  - ]
                 [ -  + ]
     196                 :             :     }
     197                 :             : 
     198                 :             :     //! Only call Prev when this entry is DIRTY, FRESH, or both
     199                 :      194697 :     CoinsCachePair* Prev() const noexcept
     200                 :             :     {
     201                 :      194697 :         Assume(m_flags);
     202   [ +  -  +  -  :       97368 :         return m_prev;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                      - ]
           [ -  +  -  + ]
     203                 :             :     }
     204                 :             : 
     205                 :             :     //! Only use this for initializing the linked list sentinel
     206                 :      526164 :     void SelfRef(CoinsCachePair& pair) noexcept
     207                 :             :     {
     208                 :      526164 :         Assume(&pair.second == this);
     209                 :      526164 :         m_prev = &pair;
     210                 :      526164 :         m_next = &pair;
     211                 :             :         // Set sentinel to DIRTY so we can call Next on it
     212   [ +  -  +  -  :      526164 :         m_flags = DIRTY;
           +  - ][ +  -  
             #  #  #  # ]
     213                 :             :     }
     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                 :        1194 :     CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
     238                 :        1194 :     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                 :             :     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                 :      147860 :     CoinsViewCacheCursor(CoinsCachePair& sentinel LIFETIMEBOUND,
     275                 :             :                          CCoinsMap& map LIFETIMEBOUND,
     276                 :             :                          bool will_erase) noexcept
     277         [ +  - ]:      147860 :         : m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
     278                 :             : 
     279                 :      147860 :     inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
     280         [ +  + ]:     1228567 :     inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
     281                 :             : 
     282                 :             :     //! Return the next entry after current, possibly erasing current
     283                 :     1080707 :     inline CoinsCachePair* NextAndMaybeErase(CoinsCachePair& current) noexcept
     284                 :             :     {
     285                 :     1080707 :         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         [ +  + ]:     1080707 :         if (!m_will_erase) {
     289         [ +  + ]:       82716 :             if (current.second.coin.IsSpent()) {
     290   [ -  +  -  - ]:       24621 :                 assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin
     291                 :       24621 :                 m_map.erase(current.first);
     292                 :             :             } else {
     293         [ +  - ]:       58095 :                 current.second.SetClean();
     294                 :             :             }
     295                 :             :         }
     296                 :     1080707 :         return next_entry;
     297                 :             :     }
     298                 :             : 
     299   [ +  +  +  +  :      470822 :     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   [ +  -  +  -  :      604579 : 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                 :         191 :     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                 :           0 : 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                 :             :     }
     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         [ +  - ]:        1241 :     explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
     513                 :             : 
     514                 :        1021 :     void AddReadErrCallback(std::function<void()> f) {
     515         [ +  - ]:        1021 :         m_err_callbacks.emplace_back(std::move(f));
     516                 :        1021 :     }
     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
        

Generated by: LCOV version 2.0-1