Bitcoin Core  21.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-2020 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  virtual unsigned int GetValueSize() const = 0;
146 
147  virtual bool Valid() const = 0;
148  virtual void Next() = 0;
149 
151  const uint256 &GetBestBlock() const { return hashBlock; }
152 private:
154 };
155 
158 {
159 public:
164  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
165 
167  virtual bool HaveCoin(const COutPoint &outpoint) const;
168 
170  virtual uint256 GetBestBlock() const;
171 
176  virtual std::vector<uint256> GetHeadBlocks() const;
177 
180  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
181 
183  virtual CCoinsViewCursor *Cursor() const;
184 
186  virtual ~CCoinsView() {}
187 
189  virtual size_t EstimateSize() const { return 0; }
190 };
191 
192 
195 {
196 protected:
198 
199 public:
200  CCoinsViewBacked(CCoinsView *viewIn);
201  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
202  bool HaveCoin(const COutPoint &outpoint) const override;
203  uint256 GetBestBlock() const override;
204  std::vector<uint256> GetHeadBlocks() const override;
205  void SetBackend(CCoinsView &viewIn);
206  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
207  CCoinsViewCursor *Cursor() const override;
208  size_t EstimateSize() const override;
209 };
210 
211 
214 {
215 protected:
222 
223  /* Cached dynamic memory usage for the inner Coin objects. */
224  mutable size_t cachedCoinsUsage;
225 
226 public:
227  CCoinsViewCache(CCoinsView *baseIn);
228 
232  CCoinsViewCache(const CCoinsViewCache &) = delete;
233 
234  // Standard CCoinsView methods
235  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
236  bool HaveCoin(const COutPoint &outpoint) const override;
237  uint256 GetBestBlock() const override;
238  void SetBestBlock(const uint256 &hashBlock);
239  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
240  CCoinsViewCursor* Cursor() const override {
241  throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
242  }
243 
249  bool HaveCoinInCache(const COutPoint &outpoint) const;
250 
261  const Coin& AccessCoin(const COutPoint &output) const;
262 
267  void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
268 
276  void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
277 
283  bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
284 
290  bool Flush();
291 
296  void Uncache(const COutPoint &outpoint);
297 
299  unsigned int GetCacheSize() const;
300 
302  size_t DynamicMemoryUsage() const;
303 
305  bool HaveInputs(const CTransaction& tx) const;
306 
312  void ReallocateCache();
313 
314 private:
319  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
320 };
321 
326 // TODO: pass in a boolean to limit these possible overwrites to known
327 // (pre-BIP34) cases.
328 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
329 
334 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
335 
344 {
345 public:
347 
348  void AddReadErrCallback(std::function<void()> f) {
349  m_err_callbacks.emplace_back(std::move(f));
350  }
351 
352  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
353 
354 private:
356  std::vector<std::function<void()>> m_err_callbacks;
357 
358 };
359 
360 #endif // BITCOIN_COINS_H
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:29
CCoinsViewCursor::GetBestBlock
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:151
assert
assert(!tx.IsCoinBase())
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:238
CCoinsViewBacked::EstimateSize
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:32
Coin::Coin
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:44
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
CCoinsViewCache::CCoinsViewCache
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:34
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:146
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:66
transaction.h
Coin::Coin
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:43
uint256.h
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:221
CCoinsViewBacked::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:26
CCoinsViewCache::EmplaceCoinInternalDANGER
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:100
CCoinsViewCache::AccessCoin
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:29
Coin::fCoinBase
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:105
CCoinsViewCursor::GetValueSize
virtual unsigned int GetValueSize() const =0
CCoinsViewCache::ReallocateCache
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:254
CCoinsViewErrorCatcher::CCoinsViewErrorCatcher
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:346
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
CCoinsView::HaveCoin
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:18
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:197
CCoinsView::GetCoin
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:12
compressor.h
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:157
Coin::out
CTxOut out
unspent transaction output
Definition: coins.h:34
AccessByTxid
const Coin & AccessByTxid(const CCoinsViewCache &cache, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:265
CCoinsViewCursor
Cursor for iterating over CoinsView state.
Definition: coins.h:137
CCoinsView::BatchWrite
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:15
CTxOut::IsNull
bool IsNull() const
Definition: transaction.h:149
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:57
CCoinsViewCache::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:166
CCoinsCacheEntry::Flags
Flags
Definition: coins.h:108
CCoinsViewCursor::GetValue
virtual bool GetValue(Coin &coin) const =0
CCoinsViewCache::SpendCoin
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:119
CCoinsViewBacked::Cursor
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:31
CTxOut
An output of a transaction.
Definition: transaction.h:128
Coin
A UTXO entry.
Definition: coins.h:30
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry()
Definition: coins.h:129
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:36
VARINT
#define VARINT(obj)
Definition: serialize.h:443
Coin::nHeight
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
CCoinsViewErrorCatcher::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:276
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:132
Coin::Serialize
void Serialize(Stream &s) const
Definition: coins.h:60
CCoinsView::GetHeadBlocks
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:14
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry(Coin &&coin_)
Definition: coins.h:130
CCoinsViewCursor::hashBlock
uint256 hashBlock
Definition: coins.h:153
AddCoins
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:108
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:151
CCoinsCacheEntry::flags
unsigned char flags
Definition: coins.h:106
CCoinsViewCache::hashBlock
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:220
uint256
256-bit opaque blob.
Definition: uint256.h:124
CCoinsViewCursor::Valid
virtual bool Valid() const =0
CCoinsView::Cursor
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:16
CCoinsView::EstimateSize
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:189
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:24
hasher.h
Coin::Unserialize
void Unserialize(Stream &s)
Definition: coins.h:68
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:224
core_memusage.h
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CCoinsViewCache::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:156
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:194
memusage.h
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:162
CCoinsViewErrorCatcher::AddReadErrCallback
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:348
CCoinsViewCursor::~CCoinsViewCursor
virtual ~CCoinsViewCursor()
Definition: coins.h:141
CCoinsViewBacked::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:30
Coin::Coin
Coin()
empty constructor
Definition: coins.h:53
CCoinsViewBacked::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:25
CCoinsViewErrorCatcher
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:343
CCoinsViewCache::HaveInputs
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:242
CCoinsMap
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
CCoinsViewCursor::GetKey
virtual bool GetKey(COutPoint &key) const =0
CCoinsViewBacked::GetHeadBlocks
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:28
serialize.h
CCoinsViewCache::Uncache
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:229
Coin::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: coins.h:83
CCoinsViewErrorCatcher::m_err_callbacks
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:356
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry(Coin &&coin_, unsigned char flag)
Definition: coins.h:131
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
CCoinsViewBacked::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:27
Coin::IsSpent
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
CCoinsCacheEntry::FRESH
@ 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
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:116
CCoinsViewCache::FetchCoin
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:40
CCoinsViewCursor::Next
virtual void Next()=0
CCoinsView::GetBestBlock
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:13
CTxOut::SetNull
void SetNull()
Definition: transaction.h:143
CCoinsView::~CCoinsView
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:186
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:103
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:222
CCoinsViewCache::Cursor
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:240
CCoinsViewCursor::CCoinsViewCursor
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:140
Coin::Clear
void Clear()
Definition: coins.h:46
Coin::IsCoinBase
bool IsCoinBase() const
Definition: coins.h:55