Bitcoin Core  24.99.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>
14 #include <uint256.h>
15 #include <util/hasher.h>
16 
17 #include <assert.h>
18 #include <stdint.h>
19 
20 #include <functional>
21 #include <unordered_map>
22 
30 class Coin
31 {
32 public:
35 
37  unsigned int fCoinBase : 1;
38 
40  uint32_t nHeight : 31;
41 
43  Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
44  Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
45 
46  void Clear() {
47  out.SetNull();
48  fCoinBase = false;
49  nHeight = 0;
50  }
51 
53  Coin() : fCoinBase(false), nHeight(0) { }
54 
55  bool IsCoinBase() const {
56  return fCoinBase;
57  }
58 
59  template<typename Stream>
60  void Serialize(Stream &s) const {
61  assert(!IsSpent());
62  uint32_t code = nHeight * uint32_t{2} + fCoinBase;
63  ::Serialize(s, VARINT(code));
64  ::Serialize(s, Using<TxOutCompression>(out));
65  }
66 
67  template<typename Stream>
68  void Unserialize(Stream &s) {
69  uint32_t code = 0;
70  ::Unserialize(s, VARINT(code));
71  nHeight = code >> 1;
72  fCoinBase = code & 1;
73  ::Unserialize(s, Using<TxOutCompression>(out));
74  }
75 
79  bool IsSpent() const {
80  return out.IsNull();
81  }
82 
83  size_t DynamicMemoryUsage() const {
85  }
86 };
87 
104 {
105  Coin coin; // The actual cached data.
106  unsigned char flags;
107 
108  enum Flags {
116  DIRTY = (1 << 0),
126  FRESH = (1 << 1),
127  };
128 
130  explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
131  CCoinsCacheEntry(Coin&& coin_, unsigned char flag) : coin(std::move(coin_)), flags(flag) {}
132 };
133 
134 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
135 
138 {
139 public:
140  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
141  virtual ~CCoinsViewCursor() {}
142 
143  virtual bool GetKey(COutPoint &key) const = 0;
144  virtual bool GetValue(Coin &coin) const = 0;
145 
146  virtual bool Valid() const = 0;
147  virtual void Next() = 0;
148 
150  const uint256 &GetBestBlock() const { return hashBlock; }
151 private:
153 };
154 
157 {
158 public:
163  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
164 
166  virtual bool HaveCoin(const COutPoint &outpoint) const;
167 
169  virtual uint256 GetBestBlock() const;
170 
175  virtual std::vector<uint256> GetHeadBlocks() const;
176 
179  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true);
180 
182  virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
183 
185  virtual ~CCoinsView() {}
186 
188  virtual size_t EstimateSize() const { return 0; }
189 };
190 
191 
194 {
195 protected:
197 
198 public:
199  CCoinsViewBacked(CCoinsView *viewIn);
200  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
201  bool HaveCoin(const COutPoint &outpoint) const override;
202  uint256 GetBestBlock() const override;
203  std::vector<uint256> GetHeadBlocks() const override;
204  void SetBackend(CCoinsView &viewIn);
205  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true) override;
206  std::unique_ptr<CCoinsViewCursor> Cursor() const override;
207  size_t EstimateSize() const override;
208 };
209 
210 
213 {
214 private:
215  const bool m_deterministic;
216 
217 protected:
224 
225  /* Cached dynamic memory usage for the inner Coin objects. */
226  mutable size_t cachedCoinsUsage{0};
227 
228 public:
229  CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
230 
234  CCoinsViewCache(const CCoinsViewCache &) = delete;
235 
236  // Standard CCoinsView methods
237  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
238  bool HaveCoin(const COutPoint &outpoint) const override;
239  uint256 GetBestBlock() const override;
240  void SetBestBlock(const uint256 &hashBlock);
241  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase = true) override;
242  std::unique_ptr<CCoinsViewCursor> Cursor() const override {
243  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
244  }
245 
251  bool HaveCoinInCache(const COutPoint &outpoint) const;
252 
263  const Coin& AccessCoin(const COutPoint &output) const;
264 
269  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
270 
278  void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
279 
285  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
286 
293  bool Flush();
294 
302  bool Sync();
303 
308  void Uncache(const COutPoint &outpoint);
309 
311  unsigned int GetCacheSize() const;
312 
314  size_t DynamicMemoryUsage() const;
315 
317  bool HaveInputs(const CTransaction& tx) const;
318 
324  void ReallocateCache();
325 
327  void SanityCheck() const;
328 
329 private:
334  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
335 };
336 
341 // TODO: pass in a boolean to limit these possible overwrites to known
342 // (pre-BIP34) cases.
343 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
344 
349 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
350 
359 {
360 public:
362 
363  void AddReadErrCallback(std::function<void()> f) {
364  m_err_callbacks.emplace_back(std::move(f));
365  }
366 
367  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
368 
369 private:
371  std::vector<std::function<void()>> m_err_callbacks;
372 
373 };
374 
375 #endif // BITCOIN_COINS_H
CCoinsView backed by another CCoinsView.
Definition: coins.h:194
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:26
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:33
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:28
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:30
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:32
CCoinsView * base
Definition: coins.h:196
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:31
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:29
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:25
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition: coins.cpp:35
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:242
const bool m_deterministic
Definition: coins.h:215
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:222
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:129
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:281
CCoinsViewCache(const CCoinsViewCache &)=delete
By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache...
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:300
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:70
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:182
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:296
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:172
size_t cachedCoinsUsage
Definition: coins.h:226
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:178
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:44
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:61
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:167
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:254
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:40
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:264
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
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:162
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition: coins.cpp:320
CCoinsMap cacheCoins
Definition: coins.h:223
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:153
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:312
Cursor for iterating over CoinsView state.
Definition: coins.h:138
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:140
uint256 hashBlock
Definition: coins.h:152
virtual ~CCoinsViewCursor()
Definition: coins.h:141
virtual bool GetKey(COutPoint &key) const =0
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:150
virtual bool GetValue(Coin &coin) const =0
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:359
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:363
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:371
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:351
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:361
Abstract view on the open txout dataset.
Definition: coins.h:157
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:15
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:185
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:19
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:188
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:17
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:16
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:14
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
An output of a transaction.
Definition: transaction.h:158
CScript scriptPubKey
Definition: transaction.h:161
void SetNull()
Definition: transaction.h:172
bool IsNull() const
Definition: transaction.h:178
A UTXO entry.
Definition: coins.h:31
bool IsCoinBase() const
Definition: coins.h:55
void Clear()
Definition: coins.h:46
void Serialize(Stream &s) const
Definition: coins.h:60
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:43
Coin()
empty constructor
Definition: coins.h:53
CTxOut out
unspent transaction output
Definition: coins.h:34
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:44
void Unserialize(Stream &s)
Definition: coins.h:68
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
size_t DynamicMemoryUsage() const
Definition: coins.h:83
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
256-bit opaque blob.
Definition: uint256.h:105
const Coin & AccessByTxid(const CCoinsViewCache &cache, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:340
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check=false)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:118
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:28
#define VARINT(obj)
Definition: serialize.h:436
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:104
unsigned char flags
Definition: coins.h:106
Coin coin
Definition: coins.h:105
Flags
Definition: coins.h:108
@ FRESH
FRESH means the parent cache does not have this coin or that it is a spent coin in the parent cache.
Definition: coins.h:126
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:116
CCoinsCacheEntry(Coin &&coin_, unsigned char flag)
Definition: coins.h:131
CCoinsCacheEntry()
Definition: coins.h:129
CCoinsCacheEntry(Coin &&coin_)
Definition: coins.h:130
assert(!tx.IsCoinBase())