Bitcoin Core  0.19.99
P2P Digital Currency
coins.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 
10 #include <compressor.h>
11 #include <core_memusage.h>
12 #include <crypto/siphash.h>
13 #include <memusage.h>
14 #include <serialize.h>
15 #include <uint256.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 * 2 + fCoinBase;
63  ::Serialize(s, VARINT(code));
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;
74  }
75 
76  bool IsSpent() const {
77  return out.IsNull();
78  }
79 
80  size_t DynamicMemoryUsage() const {
82  }
83 };
84 
86 {
87 private:
89  const uint64_t k0, k1;
90 
91 public:
93 
107  size_t operator()(const COutPoint& id) const noexcept {
108  return SipHashUint256Extra(k0, k1, id.hash, id.n);
109  }
110 };
111 
113 {
114  Coin coin; // The actual cached data.
115  unsigned char flags;
116 
117  enum Flags {
118  DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
119  FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
120  /* Note that FRESH is a performance optimization with which we can
121  * erase coins that are fully spent if we know we do not need to
122  * flush the changes to the parent cache. It is always safe to
123  * not mark FRESH if that condition is not guaranteed.
124  */
125  };
126 
127  CCoinsCacheEntry() : flags(0) {}
128  explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
129 };
130 
131 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
132 
135 {
136 public:
137  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
138  virtual ~CCoinsViewCursor() {}
139 
140  virtual bool GetKey(COutPoint &key) const = 0;
141  virtual bool GetValue(Coin &coin) const = 0;
142  virtual unsigned int GetValueSize() const = 0;
143 
144  virtual bool Valid() const = 0;
145  virtual void Next() = 0;
146 
148  const uint256 &GetBestBlock() const { return hashBlock; }
149 private:
151 };
152 
155 {
156 public:
161  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
162 
164  virtual bool HaveCoin(const COutPoint &outpoint) const;
165 
167  virtual uint256 GetBestBlock() const;
168 
173  virtual std::vector<uint256> GetHeadBlocks() const;
174 
177  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
178 
180  virtual CCoinsViewCursor *Cursor() const;
181 
183  virtual ~CCoinsView() {}
184 
186  virtual size_t EstimateSize() const { return 0; }
187 };
188 
189 
192 {
193 protected:
195 
196 public:
197  CCoinsViewBacked(CCoinsView *viewIn);
198  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
199  bool HaveCoin(const COutPoint &outpoint) const override;
200  uint256 GetBestBlock() const override;
201  std::vector<uint256> GetHeadBlocks() const override;
202  void SetBackend(CCoinsView &viewIn);
203  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
204  CCoinsViewCursor *Cursor() const override;
205  size_t EstimateSize() const override;
206 };
207 
208 
211 {
212 protected:
218  mutable CCoinsMap cacheCoins;
219 
220  /* Cached dynamic memory usage for the inner Coin objects. */
221  mutable size_t cachedCoinsUsage;
222 
223 public:
224  CCoinsViewCache(CCoinsView *baseIn);
225 
229  CCoinsViewCache(const CCoinsViewCache &) = delete;
230 
231  // Standard CCoinsView methods
232  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
233  bool HaveCoin(const COutPoint &outpoint) const override;
234  uint256 GetBestBlock() const override;
235  void SetBestBlock(const uint256 &hashBlock);
236  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
237  CCoinsViewCursor* Cursor() const override {
238  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
239  }
240 
246  bool HaveCoinInCache(const COutPoint &outpoint) const;
247 
258  const Coin& AccessCoin(const COutPoint &output) const;
259 
264  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool potential_overwrite);
265 
271  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
272 
278  bool Flush();
279 
284  void Uncache(const COutPoint &outpoint);
285 
287  unsigned int GetCacheSize() const;
288 
290  size_t DynamicMemoryUsage() const;
291 
300  CAmount GetValueIn(const CTransaction& tx) const;
301 
303  bool HaveInputs(const CTransaction& tx) const;
304 
305 private:
310  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
311 };
312 
317 // TODO: pass in a boolean to limit these possible overwrites to known
318 // (pre-BIP34) cases.
319 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
320 
325 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
326 
335 {
336 public:
338 
339  void AddReadErrCallback(std::function<void()> f) {
340  m_err_callbacks.emplace_back(std::move(f));
341  }
342 
343  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
344 
345 private:
347  std::vector<std::function<void()>> m_err_callbacks;
348 
349 };
350 
351 #endif // BITCOIN_COINS_H
bool IsSpent() const
Definition: coins.h:76
void SetNull()
Definition: transaction.h:154
bool IsCoinBase() const
Definition: coins.h:55
Definition: coins.h:112
CScript scriptPubKey
Definition: transaction.h:137
Flags
Definition: coins.h:117
A UTXO entry.
Definition: coins.h:30
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:27
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:347
wrapper for CTxOut that provides a more compact serialization
Definition: compressor.h:86
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:339
CTxOut out
unspent transaction output
Definition: coins.h:34
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:237
void Serialize(Stream &s) const
Definition: coins.h:60
bool IsNull() const
Definition: transaction.h:160
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:337
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:183
uint256 hashBlock
Definition: coins.h:150
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CCoinsCacheEntry()
Definition: coins.h:127
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:40
CCoinsMap cacheCoins
Definition: coins.h:218
Abstract view on the open txout dataset.
Definition: coins.h:154
const Coin & AccessByTxid(const CCoinsViewCache &cache, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:252
CCoinsCacheEntry(Coin &&coin_)
Definition: coins.h:128
CCoinsView * base
Definition: coins.h:194
size_t operator()(const COutPoint &id) const noexcept
This must return size_t.
Definition: coins.h:107
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:131
const uint64_t k1
Definition: coins.h:89
An output of a transaction.
Definition: transaction.h:133
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256 &val, uint32_t extra)
Definition: siphash.cpp:134
Coin()
empty constructor
Definition: coins.h:53
256-bit opaque blob.
Definition: uint256.h:120
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:217
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:89
void Unserialize(Stream &s)
Definition: coins.h:68
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:186
virtual ~CCoinsViewCursor()
Definition: coins.h:138
size_t DynamicMemoryUsage() const
Definition: coins.h:80
size_t cachedCoinsUsage
Definition: coins.h:221
void Clear()
Definition: coins.h:46
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:137
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:270
CCoinsView backed by another CCoinsView.
Definition: coins.h:191
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:210
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:148
T & REF(const T &val)
Used to bypass the rule against non-const reference to temporary where it makes sense with wrappers...
Definition: serialize.h:47
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:334
unsigned char flags
Definition: coins.h:115
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:44
#define VARINT(obj,...)
Definition: serialize.h:421
Coin coin
Definition: coins.h:114
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:43
Cursor for iterating over CoinsView state.
Definition: coins.h:134