Bitcoin Core  0.18.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 
99  size_t operator()(const COutPoint& id) const {
100  return SipHashUint256Extra(k0, k1, id.hash, id.n);
101  }
102 };
103 
105 {
106  Coin coin; // The actual cached data.
107  unsigned char flags;
108 
109  enum Flags {
110  DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
111  FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
112  /* Note that FRESH is a performance optimization with which we can
113  * erase coins that are fully spent if we know we do not need to
114  * flush the changes to the parent cache. It is always safe to
115  * not mark FRESH if that condition is not guaranteed.
116  */
117  };
118 
119  CCoinsCacheEntry() : flags(0) {}
120  explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
121 };
122 
123 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
124 
127 {
128 public:
129  CCoinsViewCursor(const uint256 &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 uint256 &GetBestBlock() const { return hashBlock; }
141 private:
143 };
144 
147 {
148 public:
153  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
154 
156  virtual bool HaveCoin(const COutPoint &outpoint) const;
157 
159  virtual uint256 GetBestBlock() const;
160 
165  virtual std::vector<uint256> GetHeadBlocks() const;
166 
169  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
170 
172  virtual CCoinsViewCursor *Cursor() const;
173 
175  virtual ~CCoinsView() {}
176 
178  virtual size_t EstimateSize() const { return 0; }
179 };
180 
181 
184 {
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  uint256 GetBestBlock() const override;
193  std::vector<uint256> GetHeadBlocks() const override;
194  void SetBackend(CCoinsView &viewIn);
195  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
196  CCoinsViewCursor *Cursor() const override;
197  size_t EstimateSize() const override;
198 };
199 
200 
203 {
204 protected:
210  mutable CCoinsMap cacheCoins;
211 
212  /* Cached dynamic memory usage for the inner Coin objects. */
213  mutable size_t cachedCoinsUsage;
214 
215 public:
216  CCoinsViewCache(CCoinsView *baseIn);
217 
221  CCoinsViewCache(const CCoinsViewCache &) = delete;
222 
223  // Standard CCoinsView methods
224  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
225  bool HaveCoin(const COutPoint &outpoint) const override;
226  uint256 GetBestBlock() const override;
227  void SetBestBlock(const uint256 &hashBlock);
228  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
229  CCoinsViewCursor* Cursor() const override {
230  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
231  }
232 
238  bool HaveCoinInCache(const COutPoint &outpoint) const;
239 
250  const Coin& AccessCoin(const COutPoint &output) const;
251 
256  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool potential_overwrite);
257 
263  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
264 
270  bool Flush();
271 
276  void Uncache(const COutPoint &outpoint);
277 
279  unsigned int GetCacheSize() const;
280 
282  size_t DynamicMemoryUsage() const;
283 
292  CAmount GetValueIn(const CTransaction& tx) const;
293 
295  bool HaveInputs(const CTransaction& tx) const;
296 
297 private:
302  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
303 };
304 
309 // TODO: pass in a boolean to limit these possible overwrites to known
310 // (pre-BIP34) cases.
311 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
312 
317 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
318 
327 {
328 public:
330 
331  void AddReadErrCallback(std::function<void()> f) {
332  m_err_callbacks.emplace_back(std::move(f));
333  }
334 
335  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
336 
337 private:
339  std::vector<std::function<void()>> m_err_callbacks;
340 
341 };
342 
343 #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:104
CScript scriptPubKey
Definition: transaction.h:137
Flags
Definition: coins.h:109
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:339
wrapper for CTxOut that provides a more compact serialization
Definition: compressor.h:86
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:331
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:229
void Serialize(Stream &s) const
Definition: coins.h:60
bool IsNull() const
Definition: transaction.h:160
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:329
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:175
uint256 hashBlock
Definition: coins.h:142
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
CCoinsCacheEntry()
Definition: coins.h:119
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:210
Abstract view on the open txout dataset.
Definition: coins.h:146
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:120
CCoinsView * base
Definition: coins.h:186
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:123
const uint64_t k1
Definition: coins.h:89
An output of a transaction.
Definition: transaction.h:133
size_t operator()(const COutPoint &id) const
This must return size_t.
Definition: coins.h:99
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:121
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:209
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:178
virtual ~CCoinsViewCursor()
Definition: coins.h:130
size_t DynamicMemoryUsage() const
Definition: coins.h:80
size_t cachedCoinsUsage
Definition: coins.h:213
void Clear()
Definition: coins.h:46
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:129
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:183
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:202
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:140
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:48
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate...
Definition: coins.h:326
unsigned char flags
Definition: coins.h:107
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:44
#define VARINT(obj,...)
Definition: serialize.h:422
Coin coin
Definition: coins.h:106
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:126