Bitcoin Core  28.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 
131 public:
132  Coin coin; // The actual cached data.
133 
134  enum Flags {
142  DIRTY = (1 << 0),
152  FRESH = (1 << 1),
153  };
154 
155  CCoinsCacheEntry() noexcept = default;
156  explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
158  {
159  ClearFlags();
160  }
161 
165  inline void AddFlags(uint8_t flags, CoinsCachePair& self, CoinsCachePair& sentinel) noexcept
166  {
167  Assume(&self.second == this);
168  if (!m_flags && flags) {
169  m_prev = sentinel.second.m_prev;
170  m_next = &sentinel;
171  sentinel.second.m_prev = &self;
172  m_prev->second.m_next = &self;
173  }
174  m_flags |= flags;
175  }
176  inline void ClearFlags() noexcept
177  {
178  if (!m_flags) return;
179  m_next->second.m_prev = m_prev;
180  m_prev->second.m_next = m_next;
181  m_flags = 0;
182  }
183  inline uint8_t GetFlags() const noexcept { return m_flags; }
184  inline bool IsDirty() const noexcept { return m_flags & DIRTY; }
185  inline bool IsFresh() const noexcept { return m_flags & FRESH; }
186 
188  inline CoinsCachePair* Next() const noexcept {
189  Assume(m_flags);
190  return m_next;
191  }
192 
194  inline CoinsCachePair* Prev() const noexcept {
195  Assume(m_flags);
196  return m_prev;
197  }
198 
200  inline void SelfRef(CoinsCachePair& self) noexcept
201  {
202  Assume(&self.second == this);
203  m_prev = &self;
204  m_next = &self;
205  // Set sentinel to DIRTY so we can call Next on it
206  m_flags = DIRTY;
207  }
208 };
209 
218 using CCoinsMap = std::unordered_map<COutPoint,
221  std::equal_to<COutPoint>,
223  sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
224 
225 using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
226 
229 {
230 public:
231  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
232  virtual ~CCoinsViewCursor() = default;
233 
234  virtual bool GetKey(COutPoint &key) const = 0;
235  virtual bool GetValue(Coin &coin) const = 0;
236 
237  virtual bool Valid() const = 0;
238  virtual void Next() = 0;
239 
241  const uint256 &GetBestBlock() const { return hashBlock; }
242 private:
244 };
245 
260 {
269  CoinsCachePair& sentinel LIFETIMEBOUND,
271  bool will_erase) noexcept
272  : m_usage(usage), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
273 
274  inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
275  inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
276 
279  {
280  const auto next_entry{current.second.Next()};
281  // If we are not going to erase the cache, we must still erase spent entries.
282  // Otherwise clear the flags on the entry.
283  if (!m_will_erase) {
284  if (current.second.coin.IsSpent()) {
285  m_usage -= current.second.coin.DynamicMemoryUsage();
286  m_map.erase(current.first);
287  } else {
288  current.second.ClearFlags();
289  }
290  }
291  return next_entry;
292  }
293 
294  inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
295 private:
296  size_t& m_usage;
300 };
301 
304 {
305 public:
310  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
311 
313  virtual bool HaveCoin(const COutPoint &outpoint) const;
314 
316  virtual uint256 GetBestBlock() const;
317 
322  virtual std::vector<uint256> GetHeadBlocks() const;
323 
326  virtual bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
327 
329  virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
330 
332  virtual ~CCoinsView() = default;
333 
335  virtual size_t EstimateSize() const { return 0; }
336 };
337 
338 
341 {
342 protected:
344 
345 public:
346  CCoinsViewBacked(CCoinsView *viewIn);
347  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
348  bool HaveCoin(const COutPoint &outpoint) const override;
349  uint256 GetBestBlock() const override;
350  std::vector<uint256> GetHeadBlocks() const override;
351  void SetBackend(CCoinsView &viewIn);
352  bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
353  std::unique_ptr<CCoinsViewCursor> Cursor() const override;
354  size_t EstimateSize() const override;
355 };
356 
357 
360 {
361 private:
362  const bool m_deterministic;
363 
364 protected:
371  /* The starting sentinel of the flagged entry circular doubly linked list. */
374 
375  /* Cached dynamic memory usage for the inner Coin objects. */
376  mutable size_t cachedCoinsUsage{0};
377 
378 public:
379  CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
380 
384  CCoinsViewCache(const CCoinsViewCache &) = delete;
385 
386  // Standard CCoinsView methods
387  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
388  bool HaveCoin(const COutPoint &outpoint) const override;
389  uint256 GetBestBlock() const override;
390  void SetBestBlock(const uint256 &hashBlock);
391  bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
392  std::unique_ptr<CCoinsViewCursor> Cursor() const override {
393  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
394  }
395 
401  bool HaveCoinInCache(const COutPoint &outpoint) const;
402 
413  const Coin& AccessCoin(const COutPoint &output) const;
414 
419  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
420 
428  void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
429 
435  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
436 
443  bool Flush();
444 
452  bool Sync();
453 
458  void Uncache(const COutPoint &outpoint);
459 
461  unsigned int GetCacheSize() const;
462 
464  size_t DynamicMemoryUsage() const;
465 
467  bool HaveInputs(const CTransaction& tx) const;
468 
474  void ReallocateCache();
475 
477  void SanityCheck() const;
478 
479 private:
484  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
485 };
486 
491 // TODO: pass in a boolean to limit these possible overwrites to known
492 // (pre-BIP34) cases.
493 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
494 
499 const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
500 
509 {
510 public:
512 
513  void AddReadErrCallback(std::function<void()> f) {
514  m_err_callbacks.emplace_back(std::move(f));
515  }
516 
517  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
518  bool HaveCoin(const COutPoint &outpoint) const override;
519 
520 private:
522  std::vector<std::function<void()>> m_err_callbacks;
523 
524 };
525 
526 #endif // BITCOIN_COINS_H
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:278
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:384
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:27
void SelfRef(CoinsCachePair &self) noexcept
Only use this for initializing the linked list sentinel.
Definition: coins.h:200
#define VARINT(obj)
Definition: serialize.h:498
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition: coins.cpp:34
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:157
CoinsCachePair m_sentinel
Definition: coins.h:372
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:108
assert(!tx.IsCoinBase())
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:12
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:355
Flags
Definition: coins.h:134
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:156
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:254
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:29
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:223
A UTXO entry.
Definition: coins.h:32
CCoinsMap & m_map
Definition: coins.h:298
CoinsCachePair * End() const noexcept
Definition: coins.h:275
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:30
virtual bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:15
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:522
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:370
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:30
virtual void Next()=0
CoinsCachePair * m_prev
These are used to create a doubly linked list of flagged entries.
Definition: coins.h:127
unsigned int nHeight
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:513
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:41
CTxOut out
unspent transaction output
Definition: coins.h:36
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:294
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:28
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:170
bool IsFresh() const noexcept
Definition: coins.h:185
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:309
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:18
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:297
void Serialize(Stream &s) const
Definition: coins.h:62
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:225
const bool m_deterministic
Definition: coins.h:362
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:132
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache...
Definition: coins.h:142
bool IsNull() const
Definition: transaction.h:170
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:511
void ClearFlags() noexcept
Definition: coins.h:176
uint256 hashBlock
Definition: coins.h:243
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:181
virtual bool GetValue(Coin &coin) const =0
CoinsCachePair & m_sentinel
Definition: coins.h:297
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:293
CCoinsCacheEntry() noexcept=default
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:91
CCoinsMap cacheCoins
Definition: coins.h:373
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty...
Definition: coins.cpp:110
#define LIFETIMEBOUND
Definition: attributes.h:16
virtual bool Valid() const =0
Abstract view on the open txout dataset.
Definition: coins.h:303
CoinsCachePair * Next() const noexcept
Only call Next when this entry is DIRTY, FRESH, or both.
Definition: coins.h:188
CCoinsView * base
Definition: coins.h:343
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:259
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:31
void AddFlags(uint8_t flags, CoinsCachePair &self, CoinsCachePair &sentinel) noexcept
Adding a flag also requires a self reference to the pair that contains this entry in the CCoinsCache ...
Definition: coins.h:165
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:14
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:194
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.
Coin()
empty constructor
Definition: coins.h:55
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:24
#define Assume(val)
Assume is the identity function.
Definition: check.h:89
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:70
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:392
CoinsCachePair * Begin() const noexcept
Definition: coins.h:274
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:175
Forwards all allocations/deallocations to the PoolResource.
Definition: pool.h:276
int flags
Definition: bitcoin-tx.cpp:533
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:26
256-bit opaque blob.
Definition: uint256.h:178
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:369
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:121
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:61
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:152
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:335
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:268
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:278
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:13
size_t DynamicMemoryUsage() const
Definition: coins.h:85
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:25
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:185
size_t cachedCoinsUsage
Definition: coins.h:376
void Clear()
Definition: coins.h:48
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:45
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:231
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:16
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:319
CCoinsView backed by another CCoinsView.
Definition: coins.h:340
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:32
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:359
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:388
size_t & m_usage
Definition: coins.h:296
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:241
uint8_t GetFlags() const noexcept
Definition: coins.h:183
bool IsDirty() const noexcept
Definition: coins.h:184
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:508
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:265
Coin coin
Definition: coins.h:132
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:165
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:228