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 
23 class ChainstateManager;
24 
32 class Coin
33 {
34 public:
37 
39  unsigned int fCoinBase : 1;
40 
42  uint32_t nHeight : 31;
43 
45  Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
46  Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
47 
48  void Clear() {
49  out.SetNull();
50  fCoinBase = false;
51  nHeight = 0;
52  }
53 
55  Coin() : fCoinBase(false), nHeight(0) { }
56 
57  bool IsCoinBase() const {
58  return fCoinBase;
59  }
60 
61  template<typename Stream>
62  void Serialize(Stream &s) const {
63  assert(!IsSpent());
64  uint32_t code = nHeight * uint32_t{2} + fCoinBase;
65  ::Serialize(s, VARINT(code));
66  ::Serialize(s, Using<TxOutCompression>(out));
67  }
68 
69  template<typename Stream>
70  void Unserialize(Stream &s) {
71  uint32_t code = 0;
72  ::Unserialize(s, VARINT(code));
73  nHeight = code >> 1;
74  fCoinBase = code & 1;
75  ::Unserialize(s, Using<TxOutCompression>(out));
76  }
77 
81  bool IsSpent() const {
82  return out.IsNull();
83  }
84 
85  size_t DynamicMemoryUsage() const {
87  }
88 };
89 
106 {
107  Coin coin; // The actual cached data.
108  unsigned char flags;
109 
110  enum Flags {
118  DIRTY = (1 << 0),
128  FRESH = (1 << 1),
129  };
130 
132  explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
133  CCoinsCacheEntry(Coin&& coin_, unsigned char flag) : coin(std::move(coin_)), flags(flag) {}
134 };
135 
136 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
137 
140 {
141 public:
142  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
143  virtual ~CCoinsViewCursor() {}
144 
145  virtual bool GetKey(COutPoint &key) const = 0;
146  virtual bool GetValue(Coin &coin) const = 0;
147  virtual unsigned int GetValueSize() const = 0;
148 
149  virtual bool Valid() const = 0;
150  virtual void Next() = 0;
151 
153  const uint256 &GetBestBlock() const { return hashBlock; }
154 private:
156 };
157 
160 {
161 public:
166  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
167 
169  virtual bool HaveCoin(const COutPoint &outpoint) const;
170 
172  virtual uint256 GetBestBlock() const;
173 
178  virtual std::vector<uint256> GetHeadBlocks() const;
179 
182  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
183 
185  virtual CCoinsViewCursor *Cursor() const;
186 
188  virtual ~CCoinsView() {}
189 
191  virtual size_t EstimateSize() const { return 0; }
192 };
193 
194 
197 {
198 protected:
200 
201 public:
202  CCoinsViewBacked(CCoinsView *viewIn);
203  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
204  bool HaveCoin(const COutPoint &outpoint) const override;
205  uint256 GetBestBlock() const override;
206  std::vector<uint256> GetHeadBlocks() const override;
207  void SetBackend(CCoinsView &viewIn);
208  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
209  CCoinsViewCursor *Cursor() const override;
210  size_t EstimateSize() const override;
211 };
212 
213 
216 {
217 protected:
224 
225  /* Cached dynamic memory usage for the inner Coin objects. */
226  mutable size_t cachedCoinsUsage;
227 
228 public:
229  CCoinsViewCache(CCoinsView *baseIn);
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) override;
242  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 
292  bool Flush();
293 
298  void Uncache(const COutPoint &outpoint);
299 
301  unsigned int GetCacheSize() const;
302 
304  size_t DynamicMemoryUsage() const;
305 
307  bool HaveInputs(const CTransaction& tx) const;
308 
314  void ReallocateCache();
315 
316 private:
321  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
322 };
323 
328 // TODO: pass in a boolean to limit these possible overwrites to known
329 // (pre-BIP34) cases.
330 void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
331 
336 const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
337 
346 {
347 public:
349 
350  void AddReadErrCallback(std::function<void()> f) {
351  m_err_callbacks.emplace_back(std::move(f));
352  }
353 
354  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
355 
356 private:
358  std::vector<std::function<void()>> m_err_callbacks;
359 
360 };
361 
362 #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:153
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:46
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:45
uint256.h
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:223
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:39
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:107
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:348
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:199
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:159
Coin::out
CTxOut out
unspent transaction output
Definition: coins.h:36
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:139
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:110
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:32
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry()
Definition: coins.h:131
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:479
Coin::nHeight
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:42
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:62
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:132
CCoinsViewCursor::hashBlock
uint256 hashBlock
Definition: coins.h:155
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:108
CCoinsViewCache::hashBlock
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:222
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:191
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:24
hasher.h
ChainstateManager
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:815
Coin::Unserialize
void Unserialize(Stream &s)
Definition: coins.h:70
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:226
core_memusage.h
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:215
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:196
memusage.h
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:162
CCoinsViewErrorCatcher::AddReadErrCallback
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:350
CCoinsViewCursor::~CCoinsViewCursor
virtual ~CCoinsViewCursor()
Definition: coins.h:143
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:55
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:345
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:136
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:85
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:358
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry(Coin &&coin_, unsigned char flag)
Definition: coins.h:133
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:81
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:128
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:118
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
assert
assert(std::addressof(::ChainstateActive().CoinsTip())==std::addressof(coins_cache))
CTxOut::SetNull
void SetNull()
Definition: transaction.h:143
CCoinsView::~CCoinsView
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:188
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:105
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:242
CCoinsViewCursor::CCoinsViewCursor
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:142
Coin::Clear
void Clear()
Definition: coins.h:48
Coin::IsCoinBase
bool IsCoinBase() const
Definition: coins.h:57