Bitcoin Core  29.1.0
P2P Digital Currency
coins.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 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>
15 #include <uint256.h>
16 #include <util/check.h>
17 #include <util/hasher.h>
18 
19 #include <assert.h>
20 #include <stdint.h>
21 
22 #include <functional>
23 #include <unordered_map>
24 
32 class Coin
33 {
34 public:
37 
39  unsigned int fCoinBase : 1;
40 
42  uint32_t nHeight : 31;
43 
45  Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
46  Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
47 
48  void Clear() {
49  out.SetNull();
50  fCoinBase = false;
51  nHeight = 0;
52  }
53 
55  Coin() : fCoinBase(false), nHeight(0) { }
56 
57  bool IsCoinBase() const {
58  return fCoinBase;
59  }
60 
61  template<typename Stream>
62  void Serialize(Stream &s) const {
63  assert(!IsSpent());
64  uint32_t code = nHeight * uint32_t{2} + fCoinBase;
65  ::Serialize(s, VARINT(code));
66  ::Serialize(s, Using<TxOutCompression>(out));
67  }
68 
69  template<typename Stream>
70  void Unserialize(Stream &s) {
71  uint32_t code = 0;
72  ::Unserialize(s, VARINT(code));
73  nHeight = code >> 1;
74  fCoinBase = code & 1;
75  ::Unserialize(s, Using<TxOutCompression>(out));
76  }
77 
81  bool IsSpent() const {
82  return out.IsNull();
83  }
84 
85  size_t DynamicMemoryUsage() const {
87  }
88 };
89 
90 struct CCoinsCacheEntry;
91 using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
92 
109 {
110 private:
129  uint8_t m_flags{0};
130 
132  static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
133  {
134  Assume(flags & (DIRTY | FRESH));
135  if (!pair.second.m_flags) {
136  Assume(!pair.second.m_prev && !pair.second.m_next);
137  pair.second.m_prev = sentinel.second.m_prev;
138  pair.second.m_next = &sentinel;
139  sentinel.second.m_prev = &pair;
140  pair.second.m_prev->second.m_next = &pair;
141  }
142  Assume(pair.second.m_prev && pair.second.m_next);
143  pair.second.m_flags |= flags;
144  }
145 
146 public:
147  Coin coin; // The actual cached data.
148 
149  enum Flags {
157  DIRTY = (1 << 0),
167  FRESH = (1 << 1),
168  };
169 
170  CCoinsCacheEntry() noexcept = default;
171  explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
173  {
174  SetClean();
175  }
176 
177  static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
178  static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
179 
180  void SetClean() noexcept
181  {
182  if (!m_flags) return;
183  m_next->second.m_prev = m_prev;
184  m_prev->second.m_next = m_next;
185  m_flags = 0;
186  m_prev = m_next = nullptr;
187  }
188  bool IsDirty() const noexcept { return m_flags & DIRTY; }
189  bool IsFresh() const noexcept { return m_flags & FRESH; }
190 
192  CoinsCachePair* Next() const noexcept
193  {
194  Assume(m_flags);
195  return m_next;
196  }
197 
199  CoinsCachePair* Prev() const noexcept
200  {
201  Assume(m_flags);
202  return m_prev;
203  }
204 
206  void SelfRef(CoinsCachePair& pair) noexcept
207  {
208  Assume(&pair.second == this);
209  m_prev = &pair;
210  m_next = &pair;
211  // Set sentinel to DIRTY so we can call Next on it
212  m_flags = DIRTY;
213  }
214 };
215 
224 using CCoinsMap = std::unordered_map<COutPoint,
227  std::equal_to<COutPoint>,
229  sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
230 
231 using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
232 
235 {
236 public:
237  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
238  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 
247  const uint256 &GetBestBlock() const { return hashBlock; }
248 private:
250 };
251 
266 {
275  CoinsCachePair& sentinel LIFETIMEBOUND,
277  bool will_erase) noexcept
278  : m_usage(usage), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
279 
280  inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
281  inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
282 
285  {
286  const auto next_entry{current.second.Next()};
287  // If we are not going to erase the cache, we must still erase spent entries.
288  // Otherwise, clear the state of the entry.
289  if (!m_will_erase) {
290  if (current.second.coin.IsSpent()) {
291  m_usage -= current.second.coin.DynamicMemoryUsage();
292  m_map.erase(current.first);
293  } else {
294  current.second.SetClean();
295  }
296  }
297  return next_entry;
298  }
299 
300  inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
301 private:
302  size_t& m_usage;
306 };
307 
310 {
311 public:
313  virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const;
314 
316  virtual bool HaveCoin(const COutPoint &outpoint) const;
317 
319  virtual uint256 GetBestBlock() const;
320 
325  virtual std::vector<uint256> GetHeadBlocks() const;
326 
329  virtual bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
330 
332  virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
333 
335  virtual ~CCoinsView() = default;
336 
338  virtual size_t EstimateSize() const { return 0; }
339 };
340 
341 
344 {
345 protected:
347 
348 public:
349  CCoinsViewBacked(CCoinsView *viewIn);
350  std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
351  bool HaveCoin(const COutPoint &outpoint) const override;
352  uint256 GetBestBlock() const override;
353  std::vector<uint256> GetHeadBlocks() const override;
354  void SetBackend(CCoinsView &viewIn);
355  bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
356  std::unique_ptr<CCoinsViewCursor> Cursor() const override;
357  size_t EstimateSize() const override;
358 };
359 
360 
363 {
364 private:
365  const bool m_deterministic;
366 
367 protected:
374  /* The starting sentinel of the flagged entry circular doubly linked list. */
377 
378  /* Cached dynamic memory usage for the inner Coin objects. */
379  mutable size_t cachedCoinsUsage{0};
380 
381 public:
382  CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
383 
387  CCoinsViewCache(const CCoinsViewCache &) = delete;
388 
389  // Standard CCoinsView methods
390  std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
391  bool HaveCoin(const COutPoint &outpoint) const override;
392  uint256 GetBestBlock() const override;
393  void SetBestBlock(const uint256 &hashBlock);
394  bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
395  std::unique_ptr<CCoinsViewCursor> Cursor() const override {
396  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
397  }
398 
404  bool HaveCoinInCache(const COutPoint &outpoint) const;
405 
416  const Coin& AccessCoin(const COutPoint &output) const;
417 
422  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
423 
431  void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
432 
438  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
439 
446  bool Flush();
447 
455  bool Sync();
456 
461  void Uncache(const COutPoint &outpoint);
462 
464  unsigned int GetCacheSize() const;
465 
467  size_t DynamicMemoryUsage() const;
468 
470  bool HaveInputs(const CTransaction& tx) const;
471 
477  void ReallocateCache();
478 
480  void SanityCheck() const;
481 
482 private:
487  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
488 };
489 
494 // TODO: pass in a boolean to limit these possible overwrites to known
495 // (pre-BIP34) cases.
496 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
497 
502 const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
503 
512 {
513 public:
515 
516  void AddReadErrCallback(std::function<void()> f) {
517  m_err_callbacks.emplace_back(std::move(f));
518  }
519 
520  std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
521  bool HaveCoin(const COutPoint &outpoint) const override;
522 
523 private:
525  std::vector<std::function<void()>> m_err_callbacks;
526 
527 };
528 
529 #endif // BITCOIN_COINS_H
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:284
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:30
#define VARINT(obj)
Definition: serialize.h:500
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition: coins.cpp:37
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:81
void SetNull()
Definition: transaction.h:164
bool IsCoinBase() const
Definition: coins.h:57
~CCoinsCacheEntry()
Definition: coins.h:172
CoinsCachePair m_sentinel
Definition: coins.h:375
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:108
assert(!tx.IsCoinBase())
CScript scriptPubKey
Definition: transaction.h:153
CoinsCachePair * m_next
Definition: coins.h:128
const Coin & AccessByTxid(const CCoinsViewCache &cache, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:351
Flags
Definition: coins.h:149
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:154
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:250
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:32
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< CoinsCachePair, sizeof(CoinsCachePair)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator&#39;s MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
Definition: coins.h:229
A UTXO entry.
Definition: coins.h:32
CCoinsMap & m_map
Definition: coins.h:304
CoinsCachePair * End() const noexcept
Definition: coins.h:281
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:31
virtual bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:19
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:525
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:373
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:33
virtual void Next()=0
CoinsCachePair * m_prev
These are used to create a doubly linked list of flagged entries.
Definition: coins.h:127
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:516
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:44
CTxOut out
unspent transaction output
Definition: coins.h:36
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:300
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:31
virtual ~CCoinsViewCursor()=default
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:39
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:168
bool IsFresh() const noexcept
Definition: coins.h:189
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:305
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:22
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view...
Definition: coins.cpp:293
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:66
void Serialize(Stream &s) const
Definition: coins.h:62
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:231
const bool m_deterministic
Definition: coins.h:365
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:130
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache...
Definition: coins.h:157
bool IsNull() const
Definition: transaction.h:170
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:514
uint256 hashBlock
Definition: coins.h:249
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:179
virtual bool GetValue(Coin &coin) const =0
CoinsCachePair & m_sentinel
Definition: coins.h:303
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:42
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:289
CCoinsCacheEntry() noexcept=default
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:91
CCoinsMap cacheCoins
Definition: coins.h:376
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty...
Definition: coins.cpp:113
#define LIFETIMEBOUND
Definition: attributes.h:16
virtual bool Valid() const =0
Abstract view on the open txout dataset.
Definition: coins.h:309
CoinsCachePair * Next() const noexcept
Only call Next when this entry is DIRTY, FRESH, or both.
Definition: coins.h:192
CCoinsView * base
Definition: coins.h:346
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:265
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:34
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:28
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:18
uint8_t m_flags
Definition: coins.h:129
An output of a transaction.
Definition: transaction.h:149
CoinsCachePair * Prev() const noexcept
Only call Prev when this entry is DIRTY, FRESH, or both.
Definition: coins.h:199
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:28
virtual ~CCoinsView()=default
As we use CCoinsViews polymorphically, have a virtual destructor.
unsigned int nHeight
Coin()
empty constructor
Definition: coins.h:55
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:27
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:72
virtual bool GetKey(COutPoint &key) const =0
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:395
CoinsCachePair * Begin() const noexcept
Definition: coins.h:280
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:173
Forwards all allocations/deallocations to the PoolResource.
Definition: pool.h:276
int flags
Definition: bitcoin-tx.cpp:536
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:29
256-bit opaque blob.
Definition: uint256.h:201
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:372
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check=false)
Utility function to add all of a transaction&#39;s outputs to a cache.
Definition: coins.cpp:119
void Unserialize(Stream &s)
Definition: coins.h:70
FRESH means the parent cache does not have this coin or that it is a spent coin in the parent cache...
Definition: coins.h:167
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:177
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:338
void SelfRef(CoinsCachePair &pair) noexcept
Only use this for initializing the linked list sentinel.
Definition: coins.h:206
CoinsViewCacheCursor(size_t &usage LIFETIMEBOUND, CoinsCachePair &sentinel LIFETIMEBOUND, CCoinsMap &map LIFETIMEBOUND, bool will_erase) noexcept
If will_erase is not set, iterating through the cursor will erase spent coins from the map...
Definition: coins.h:274
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:274
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:17
size_t DynamicMemoryUsage() const
Definition: coins.h:85
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:16
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:183
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:380
size_t cachedCoinsUsage
Definition: coins.h:379
void Clear()
Definition: coins.h:48
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:48
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:237
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:20
static void AddFlags(uint8_t flags, CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Adding a flag requires a reference to the sentinel of the flagged pair linked list.
Definition: coins.h:132
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:295
void SanityCheck() const
Run an internal sanity check on the cache data structure. */.
Definition: coins.cpp:315
CCoinsView backed by another CCoinsView.
Definition: coins.h:343
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:35
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:362
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:178
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:385
size_t & m_usage
Definition: coins.h:302
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:247
bool IsDirty() const noexcept
Definition: coins.h:188
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:511
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:46
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:261
void SetClean() noexcept
Definition: coins.h:180
Coin coin
Definition: coins.h:147
transaction_identifier represents the two canonical transaction identifier types (txid, wtxid).
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:163
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:45
Cursor for iterating over CoinsView state.
Definition: coins.h:234