Bitcoin ABC  0.24.7
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 <crypto/siphash.h>
11 #include <memusage.h>
12 #include <primitives/blockhash.h>
13 #include <serialize.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 
73 private:
75  const uint64_t k0, k1;
76 
77 public:
79 
97  size_t operator()(const COutPoint &outpoint) const noexcept {
98  return SipHashUint256Extra(k0, k1, outpoint.GetTxId(), outpoint.GetN());
99  }
100 };
101 
121  // The actual cached data.
123  uint8_t flags;
124 
125  enum Flags {
133  DIRTY = (1 << 0),
143  FRESH = (1 << 1),
144  };
145 
147  explicit CCoinsCacheEntry(Coin coinIn)
148  : coin(std::move(coinIn)), flags(0) {}
149 };
150 
151 typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher>
153 
156 public:
157  CCoinsViewCursor(const BlockHash &hashBlockIn) : hashBlock(hashBlockIn) {}
158  virtual ~CCoinsViewCursor() {}
159 
160  virtual bool GetKey(COutPoint &key) const = 0;
161  virtual bool GetValue(Coin &coin) const = 0;
162  virtual unsigned int GetValueSize() const = 0;
163 
164  virtual bool Valid() const = 0;
165  virtual void Next() = 0;
166 
168  const BlockHash &GetBestBlock() const { return hashBlock; }
169 
170 private:
172 };
173 
175 class CCoinsView {
176 public:
182  virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
183 
185  virtual bool HaveCoin(const COutPoint &outpoint) const;
186 
188  virtual BlockHash GetBestBlock() const;
189 
195  virtual std::vector<BlockHash> GetHeadBlocks() const;
196 
199  virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock);
200 
202  virtual CCoinsViewCursor *Cursor() const;
203 
205  virtual ~CCoinsView() {}
206 
208  virtual size_t EstimateSize() const { return 0; }
209 };
210 
212 class CCoinsViewBacked : public CCoinsView {
213 protected:
215 
216 public:
217  CCoinsViewBacked(CCoinsView *viewIn);
218  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
219  bool HaveCoin(const COutPoint &outpoint) const override;
220  BlockHash GetBestBlock() const override;
221  std::vector<BlockHash> GetHeadBlocks() const override;
222  void SetBackend(CCoinsView &viewIn);
223  bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override;
224  CCoinsViewCursor *Cursor() const override;
225  size_t EstimateSize() const override;
226 };
227 
232 protected:
239 
240  /* Cached dynamic memory usage for the inner Coin objects. */
241  mutable size_t cachedCoinsUsage;
242 
243 public:
244  CCoinsViewCache(CCoinsView *baseIn);
245 
250  CCoinsViewCache(const CCoinsViewCache &) = delete;
251 
252  // Standard CCoinsView methods
253  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
254  bool HaveCoin(const COutPoint &outpoint) const override;
255  BlockHash GetBestBlock() const override;
256  void SetBestBlock(const BlockHash &hashBlock);
257  bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override;
258  CCoinsViewCursor *Cursor() const override {
259  throw std::logic_error(
260  "CCoinsViewCache cursor iteration not supported.");
261  }
262 
268  bool HaveCoinInCache(const COutPoint &outpoint) const;
269 
280  const Coin &AccessCoin(const COutPoint &output) const;
281 
286  void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite);
287 
293  bool SpendCoin(const COutPoint &outpoint, Coin *moveto = nullptr);
294 
301  bool Flush();
302 
307  void Uncache(const COutPoint &outpoint);
308 
310  unsigned int GetCacheSize() const;
311 
313  size_t DynamicMemoryUsage() const;
314 
317  bool HaveInputs(const CTransaction &tx) const;
318 
325  void ReallocateCache();
326 
327 private:
332  CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
333 };
334 
339 // TODO: pass in a boolean to limit these possible overwrites to known
340 // (pre-BIP34) cases.
341 void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight,
342  bool check = false);
343 
348 const Coin &AccessByTxid(const CCoinsViewCache &cache, const TxId &txid);
349 
359 public:
361  : CCoinsViewBacked(view) {}
362 
363  void AddReadErrCallback(std::function<void()> f) {
364  m_err_callbacks.emplace_back(std::move(f));
365  }
366 
367  bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
368 
369 private:
373  std::vector<std::function<void()>> m_err_callbacks;
374 };
375 
376 #endif // BITCOIN_COINS_H
CCoinsViewCache::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:209
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:45
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:286
CCoinsViewBacked::EstimateSize
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:55
Coin::Coin
Coin(CTxOut outIn, uint32_t nHeightIn, bool IsCoinbase)
Constructor from a CTxOut and height/coinbase information.
Definition: coins.h:40
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:13
CCoinsViewCache::CCoinsViewCache
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:63
SaltedOutpointHasher::k0
const uint64_t k0
Salt.
Definition: coins.h:75
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:188
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:103
CCoinsViewCursor::CCoinsViewCursor
CCoinsViewCursor(const BlockHash &hashBlockIn)
Definition: coins.h:157
Coin::nHeightAndIsCoinBase
uint32_t nHeightAndIsCoinBase
Whether containing transaction was a coinbase and height at which the transaction was included into a...
Definition: coins.h:33
CCoinsViewBacked::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:48
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:238
CCoinsViewBacked::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:36
blockhash.h
CCoinsViewCache::hashBlock
BlockHash hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:237
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:180
CCoinsViewCursor::hashBlock
BlockHash hashBlock
Definition: coins.h:171
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:26
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:122
CCoinsViewCursor::GetValueSize
virtual unsigned int GetValueSize() const =0
CCoinsViewCache::ReallocateCache
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:304
CCoinsViewErrorCatcher::CCoinsViewErrorCatcher
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:360
SaltedOutpointHasher::SaltedOutpointHasher
SaltedOutpointHasher()
Definition: coins.cpp:59
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
CCoinsView::HaveCoin
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:214
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:175
Coin::out
CTxOut out
Unspent transaction output.
Definition: coins.h:29
CCoinsViewCursor
Cursor for iterating over CoinsView state.
Definition: coins.h:155
CTxOut::IsNull
bool IsNull() const
Definition: transaction.h:147
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:94
siphash.h
CCoinsCacheEntry::Flags
Flags
Definition: coins.h:125
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:160
CCoinsViewBacked::Cursor
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:52
CTxOut
An output of a transaction.
Definition: transaction.h:130
Coin
A UTXO entry.
Definition: coins.h:27
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry()
Definition: coins.h:146
SipHashUint256Extra
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256 &val, uint32_t extra)
Definition: siphash.cpp:138
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:66
VARINT
#define VARINT(obj)
Definition: serialize.h:596
CCoinsViewErrorCatcher::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:326
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:133
CCoinsViewBacked::GetHeadBlocks
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:42
Coin::Serialize
void Serialize(Stream &s) const
Definition: coins.h:56
SaltedOutpointHasher::k1
const uint64_t k1
Definition: coins.h:75
CCoinsView::GetHeadBlocks
virtual std::vector< BlockHash > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:18
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:144
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:193
CCoinsViewCursor::Valid
virtual bool Valid() const =0
TxId
A TxId is the identifier of a transaction.
Definition: txid.h:14
CCoinsView::Cursor
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:24
CCoinsCacheEntry::flags
uint8_t flags
Definition: coins.h:123
CCoinsView::BatchWrite
virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:21
CCoinsView::EstimateSize
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:208
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:32
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
AccessByTxid
const Coin & AccessByTxid(const CCoinsViewCache &cache, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:315
Coin::Unserialize
void Unserialize(Stream &s)
Definition: coins.h:62
SaltedOutpointHasher
Definition: coins.h:72
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:241
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:231
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:212
memusage.h
CCoinsViewErrorCatcher::AddReadErrCallback
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:363
CCoinsViewCursor::~CCoinsViewCursor
virtual ~CCoinsViewCursor()
Definition: coins.h:158
CCoinsViewCache::GetBestBlock
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:198
SaltedOutpointHasher::operator()
size_t operator()(const COutPoint &outpoint) const noexcept
This must return size_t.
Definition: coins.h:97
Coin::Coin
Coin()
Empty constructor.
Definition: coins.h:37
CCoinsViewBacked::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:33
CCoinsViewErrorCatcher
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:358
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:290
CCoinsMap
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:152
CCoinsViewCursor::GetKey
virtual bool GetKey(COutPoint &key) const =0
Coin::GetHeight
uint32_t GetHeight() const
Definition: coins.h:44
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:278
Coin::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: coins.h:67
CCoinsViewCursor::GetBestBlock
const BlockHash & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:168
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:373
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
Coin::IsSpent
bool IsSpent() const
Definition: coins.h:46
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:143
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:133
CCoinsViewCache::SetBestBlock
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:205
CCoinsViewCache::FetchCoin
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:71
CCoinsCacheEntry::CCoinsCacheEntry
CCoinsCacheEntry(Coin coinIn)
Definition: coins.h:147
Coin::GetTxOut
const CTxOut & GetTxOut() const
Definition: coins.h:49
Coin::GetTxOut
CTxOut & GetTxOut()
Definition: coins.h:48
CCoinsViewCursor::Next
virtual void Next()=0
CTxOut::SetNull
void SetNull()
Definition: transaction.h:142
CCoinsView::~CCoinsView
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:205
CCoinsView::GetBestBlock
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:15
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:120
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:271
CCoinsViewCache::Cursor
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:258
Coin::Clear
void Clear()
Definition: coins.h:51
CCoinsViewBacked::GetBestBlock
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:39
Coin::IsCoinBase
bool IsCoinBase() const
Definition: coins.h:45