Bitcoin ABC  0.26.3
P2P Digital Currency
coins.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 <memusage.h>
11 #include <primitives/blockhash.h>
12 #include <serialize.h>
13 #include <util/hasher.h>
14 
15 #include <cassert>
16 #include <cstdint>
17 #include <functional>
18 #include <unordered_map>
19 
27 class Coin {
30 
34 
35 public:
38 
40  Coin(CTxOut outIn, uint32_t nHeightIn, bool IsCoinbase)
41  : out(std::move(outIn)),
42  nHeightAndIsCoinBase((nHeightIn << 1) | IsCoinbase) {}
43 
44  uint32_t GetHeight() const { return nHeightAndIsCoinBase >> 1; }
45  bool IsCoinBase() const { return nHeightAndIsCoinBase & 0x01; }
46  bool IsSpent() const { return out.IsNull(); }
47 
48  CTxOut &GetTxOut() { return out; }
49  const CTxOut &GetTxOut() const { return out; }
50 
51  void Clear() {
52  out.SetNull();
54  }
55 
56  template <typename Stream> void Serialize(Stream &s) const {
57  assert(!IsSpent());
59  ::Serialize(s, Using<TxOutCompression>(out));
60  }
61 
62  template <typename Stream> void Unserialize(Stream &s) {
64  ::Unserialize(s, Using<TxOutCompression>(out));
65  }
66 
67  size_t DynamicMemoryUsage() const {
69  }
70 };
71 
91  // The actual cached data.
93  uint8_t flags;
94 
95  enum Flags {
103  DIRTY = (1 << 0),
113  FRESH = (1 << 1),
114  };
115 
117  explicit CCoinsCacheEntry(Coin coinIn)
118  : coin(std::move(coinIn)), flags(0) {}
119  CCoinsCacheEntry(Coin &&coin_, uint8_t flag)
120  : coin(std::move(coin_)), flags(flag) {}
121 };
122 
123 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher>
125 
128 public:
129  CCoinsViewCursor(const BlockHash &hashBlockIn) : hashBlock(hashBlockIn) {}
130  virtual ~CCoinsViewCursor() {}
131 
132  virtual bool GetKey(COutPoint &key) const = 0;
133  virtual bool GetValue(Coin &coin) const = 0;
134  virtual unsigned int GetValueSize() const = 0;
135 
136  virtual bool Valid() const = 0;
137  virtual void Next() = 0;
138 
140  const BlockHash &GetBestBlock() const { return hashBlock; }
141 
142 private:
144 };
145 
147 class CCoinsView {
148 public:
154  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
155 
157  virtual bool HaveCoin(const COutPoint &outpoint) const;
158 
160  virtual BlockHash GetBestBlock() const;
161 
167  virtual std::vector<BlockHash> GetHeadBlocks() const;
168 
171  virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock);
172 
174  virtual CCoinsViewCursor *Cursor() const;
175 
177  virtual ~CCoinsView() {}
178 
180  virtual size_t EstimateSize() const { return 0; }
181 };
182 
184 class CCoinsViewBacked : public CCoinsView {
185 protected:
187 
188 public:
189  CCoinsViewBacked(CCoinsView *viewIn);
190  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
191  bool HaveCoin(const COutPoint &outpoint) const override;
192  BlockHash GetBestBlock() const override;
193  std::vector<BlockHash> GetHeadBlocks() const override;
194  void SetBackend(CCoinsView &viewIn);
195  bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override;
196  CCoinsViewCursor *Cursor() const override;
197  size_t EstimateSize() const override;
198 };
199 
204 protected:
211 
212  /* Cached dynamic memory usage for the inner Coin objects. */
213  mutable size_t cachedCoinsUsage;
214 
215 public:
216  CCoinsViewCache(CCoinsView *baseIn);
217 
222  CCoinsViewCache(const CCoinsViewCache &) = delete;
223 
224  // Standard CCoinsView methods
225  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
226  bool HaveCoin(const COutPoint &outpoint) const override;
227  BlockHash GetBestBlock() const override;
228  void SetBestBlock(const BlockHash &hashBlock);
229  bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override;
230  CCoinsViewCursor *Cursor() const override {
231  throw std::logic_error(
232  "CCoinsViewCache cursor iteration not supported.");
233  }
234 
240  bool HaveCoinInCache(const COutPoint &outpoint) const;
241 
252  const Coin &AccessCoin(const COutPoint &output) const;
253 
258  void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite);
259 
267  void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin);
268 
274  bool SpendCoin(const COutPoint &outpoint, Coin *moveto = nullptr);
275 
282  bool Flush();
283 
288  void Uncache(const COutPoint &outpoint);
289 
291  unsigned int GetCacheSize() const;
292 
294  size_t DynamicMemoryUsage() const;
295 
298  bool HaveInputs(const CTransaction &tx) const;
299 
306  void ReallocateCache();
307 
308 private:
313  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
314 };
315 
320 // TODO: pass in a boolean to limit these possible overwrites to known
321 // (pre-BIP34) cases.
322 void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight,
323  bool check = false);
324 
329 const Coin &AccessByTxid(const CCoinsViewCache &cache, const TxId &txid);
330 
340 public:
342  : CCoinsViewBacked(view) {}
343 
344  void AddReadErrCallback(std::function<void()> f) {
345  m_err_callbacks.emplace_back(std::move(f));
346  }
347 
348  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
349 
350 private:
354  std::vector<std::function<void()>> m_err_callbacks;
355 };
356 
357 #endif // BITCOIN_COINS_H
CCoinsView backed by another CCoinsView.
Definition: coins.h:184
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:37
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:40
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:53
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:34
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:56
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:49
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:46
CCoinsView * base
Definition: coins.h:186
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:43
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:33
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:203
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:100
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:210
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:168
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:290
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:230
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:60
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:306
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:217
BlockHash hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:209
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:302
size_t cachedCoinsUsage
Definition: coins.h:213
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:68
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:91
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:205
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:283
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:63
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:221
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:144
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:200
CCoinsMap cacheCoins
Definition: coins.h:210
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:192
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:320
Cursor for iterating over CoinsView state.
Definition: coins.h:127
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const BlockHash &hashBlockIn)
Definition: coins.h:129
virtual unsigned int GetValueSize() const =0
BlockHash hashBlock
Definition: coins.h:143
virtual ~CCoinsViewCursor()
Definition: coins.h:130
const BlockHash & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:140
virtual bool GetKey(COutPoint &key) const =0
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:339
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:344
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:354
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:342
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:341
Abstract view on the open txout dataset.
Definition: coins.h:147
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:25
virtual std::vector< BlockHash > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:19
virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:22
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:177
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:16
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:28
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:180
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
An output of a transaction.
Definition: transaction.h:130
CScript scriptPubKey
Definition: transaction.h:133
void SetNull()
Definition: transaction.h:142
bool IsNull() const
Definition: transaction.h:147
A UTXO entry.
Definition: coins.h:27
const CTxOut & GetTxOut() const
Definition: coins.h:49
uint32_t GetHeight() const
Definition: coins.h:44
bool IsCoinBase() const
Definition: coins.h:45
void Clear()
Definition: coins.h:51
Coin(CTxOut outIn, uint32_t nHeightIn, bool IsCoinbase)
Constructor from a CTxOut and height/coinbase information.
Definition: coins.h:40
void Serialize(Stream &s) const
Definition: coins.h:56
uint32_t nHeightAndIsCoinBase
Whether containing transaction was a coinbase and height at which the transaction was included into a...
Definition: coins.h:33
Coin()
Empty constructor.
Definition: coins.h:37
CTxOut out
Unspent transaction output.
Definition: coins.h:29
bool IsSpent() const
Definition: coins.h:46
CTxOut & GetTxOut()
Definition: coins.h:48
void Unserialize(Stream &s)
Definition: coins.h:62
size_t DynamicMemoryUsage() const
Definition: coins.h:67
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:152
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:124
const Coin & AccessByTxid(const CCoinsViewCache &cache, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:331
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:26
#define VARINT(obj)
Definition: serialize.h:597
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:90
Coin coin
Definition: coins.h:92
Flags
Definition: coins.h:95
@ 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:113
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:103
uint8_t flags
Definition: coins.h:93
CCoinsCacheEntry(Coin &&coin_, uint8_t flag)
Definition: coins.h:119
CCoinsCacheEntry()
Definition: coins.h:116
CCoinsCacheEntry(Coin coinIn)
Definition: coins.h:117
A TxId is the identifier of a transaction.
Definition: txid.h:14
assert(!tx.IsCoinBase())