Dogecoin Core  1.14.2
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 "core_memusage.h"
11 #include "hash.h"
12 #include "memusage.h"
13 #include "serialize.h"
14 #include "uint256.h"
15 
16 #include <assert.h>
17 #include <stdint.h>
18 
19 #include <boost/foreach.hpp>
20 #include <boost/unordered_map.hpp>
21 
74 class CCoins
75 {
76 public:
78  bool fCoinBase;
79 
81  std::vector<CTxOut> vout;
82 
84  int nHeight;
85 
88  int nVersion;
89 
90  void FromTx(const CTransaction &tx, int nHeightIn) {
91  fCoinBase = tx.IsCoinBase();
92  vout = tx.vout;
93  nHeight = nHeightIn;
94  nVersion = tx.nVersion;
96  }
97 
99  CCoins(const CTransaction &tx, int nHeightIn) {
100  FromTx(tx, nHeightIn);
101  }
102 
103  void Clear() {
104  fCoinBase = false;
105  std::vector<CTxOut>().swap(vout);
106  nHeight = 0;
107  nVersion = 0;
108  }
109 
111  CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
112 
114  void Cleanup() {
115  while (vout.size() > 0 && vout.back().IsNull())
116  vout.pop_back();
117  if (vout.empty())
118  std::vector<CTxOut>().swap(vout);
119  }
120 
122  BOOST_FOREACH(CTxOut &txout, vout) {
123  if (txout.scriptPubKey.IsUnspendable())
124  txout.SetNull();
125  }
126  Cleanup();
127  }
128 
129  void swap(CCoins &to) {
130  std::swap(to.fCoinBase, fCoinBase);
131  to.vout.swap(vout);
132  std::swap(to.nHeight, nHeight);
133  std::swap(to.nVersion, nVersion);
134  }
135 
137  friend bool operator==(const CCoins &a, const CCoins &b) {
138  // Empty CCoins objects are always equal.
139  if (a.IsPruned() && b.IsPruned())
140  return true;
141  return a.fCoinBase == b.fCoinBase &&
142  a.nHeight == b.nHeight &&
143  a.nVersion == b.nVersion &&
144  a.vout == b.vout;
145  }
146  friend bool operator!=(const CCoins &a, const CCoins &b) {
147  return !(a == b);
148  }
149 
150  void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
151 
152  bool IsCoinBase() const {
153  return fCoinBase;
154  }
155 
156  template<typename Stream>
157  void Serialize(Stream &s) const {
158  unsigned int nMaskSize = 0, nMaskCode = 0;
159  CalcMaskSize(nMaskSize, nMaskCode);
160  bool fFirst = vout.size() > 0 && !vout[0].IsNull();
161  bool fSecond = vout.size() > 1 && !vout[1].IsNull();
162  assert(fFirst || fSecond || nMaskCode);
163  unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
164  // version
165  ::Serialize(s, VARINT(this->nVersion));
166  // header code
167  ::Serialize(s, VARINT(nCode));
168  // spentness bitmask
169  for (unsigned int b = 0; b<nMaskSize; b++) {
170  unsigned char chAvail = 0;
171  for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
172  if (!vout[2+b*8+i].IsNull())
173  chAvail |= (1 << i);
174  ::Serialize(s, chAvail);
175  }
176  // txouts themself
177  for (unsigned int i = 0; i < vout.size(); i++) {
178  if (!vout[i].IsNull())
180  }
181  // coinbase height
183  }
184 
185  template<typename Stream>
186  void Unserialize(Stream &s) {
187  unsigned int nCode = 0;
188  // version
189  ::Unserialize(s, VARINT(this->nVersion));
190  // header code
191  ::Unserialize(s, VARINT(nCode));
192  fCoinBase = nCode & 1;
193  std::vector<bool> vAvail(2, false);
194  vAvail[0] = (nCode & 2) != 0;
195  vAvail[1] = (nCode & 4) != 0;
196  unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
197  // spentness bitmask
198  while (nMaskCode > 0) {
199  unsigned char chAvail = 0;
200  ::Unserialize(s, chAvail);
201  for (unsigned int p = 0; p < 8; p++) {
202  bool f = (chAvail & (1 << p)) != 0;
203  vAvail.push_back(f);
204  }
205  if (chAvail != 0)
206  nMaskCode--;
207  }
208  // txouts themself
209  vout.assign(vAvail.size(), CTxOut());
210  for (unsigned int i = 0; i < vAvail.size(); i++) {
211  if (vAvail[i])
213  }
214  // coinbase height
216  Cleanup();
217  }
218 
220  bool Spend(uint32_t nPos);
221 
223  bool IsAvailable(unsigned int nPos) const {
224  return (nPos < vout.size() && !vout[nPos].IsNull());
225  }
226 
229  bool IsPruned() const {
230  BOOST_FOREACH(const CTxOut &out, vout)
231  if (!out.IsNull())
232  return false;
233  return true;
234  }
235 
236  size_t DynamicMemoryUsage() const {
237  size_t ret = memusage::DynamicUsage(vout);
238  BOOST_FOREACH(const CTxOut &out, vout) {
239  ret += RecursiveDynamicUsage(out.scriptPubKey);
240  }
241  return ret;
242  }
243 };
244 
246 {
247 private:
249  const uint64_t k0, k1;
250 
251 public:
253 
259  size_t operator()(const uint256& txid) const {
260  return SipHashUint256(k0, k1, txid);
261  }
262 };
263 
265 {
266  CCoins coins; // The actual cached data.
267  unsigned char flags;
268 
269  enum Flags {
270  DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
271  FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
272  /* Note that FRESH is a performance optimization with which we can
273  * erase coins that are fully spent if we know we do not need to
274  * flush the changes to the parent cache. It is always safe to
275  * not mark FRESH if that condition is not guaranteed.
276  */
277  };
278 
280 };
281 
282 typedef boost::unordered_map<uint256, CCoinsCacheEntry, SaltedTxidHasher> CCoinsMap;
283 
286 {
287 public:
288  CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
289  virtual ~CCoinsViewCursor();
290 
291  virtual bool GetKey(uint256 &key) const = 0;
292  virtual bool GetValue(CCoins &coins) const = 0;
293  /* Don't care about GetKeySize here */
294  virtual unsigned int GetValueSize() const = 0;
295 
296  virtual bool Valid() const = 0;
297  virtual void Next() = 0;
298 
300  const uint256 &GetBestBlock() const { return hashBlock; }
301 private:
303 };
304 
307 {
308 public:
310  virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
311 
314  virtual bool HaveCoins(const uint256 &txid) const;
315 
317  virtual uint256 GetBestBlock() const;
318 
321  virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
322 
324  virtual CCoinsViewCursor *Cursor() const;
325 
327  virtual ~CCoinsView() {}
328 };
329 
330 
333 {
334 protected:
336 
337 public:
338  CCoinsViewBacked(CCoinsView *viewIn);
339  bool GetCoins(const uint256 &txid, CCoins &coins) const;
340  bool HaveCoins(const uint256 &txid) const;
341  uint256 GetBestBlock() const;
342  void SetBackend(CCoinsView &viewIn);
343  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
344  CCoinsViewCursor *Cursor() const;
345 };
346 
347 
348 class CCoinsViewCache;
349 
356 {
357 private:
359  CCoinsMap::iterator it;
360  size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
361  CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
362 
363 public:
364  CCoins* operator->() { return &it->second.coins; }
365  CCoins& operator*() { return it->second.coins; }
366  ~CCoinsModifier();
367  friend class CCoinsViewCache;
368 };
369 
372 {
373 protected:
374  /* Whether this cache has an active modifier. */
376 
377 
384 
385  /* Cached dynamic memory usage for the inner CCoins objects. */
386  mutable size_t cachedCoinsUsage;
387 
388 public:
389  CCoinsViewCache(CCoinsView *baseIn);
391 
392  // Standard CCoinsView methods
393  bool GetCoins(const uint256 &txid, CCoins &coins) const;
394  bool HaveCoins(const uint256 &txid) const;
395  uint256 GetBestBlock() const;
396  void SetBestBlock(const uint256 &hashBlock);
397  bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
398 
404  bool HaveCoinsInCache(const uint256 &txid) const;
405 
411  const CCoins* AccessCoins(const uint256 &txid) const;
412 
418  CCoinsModifier ModifyCoins(const uint256 &txid);
419 
429  CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase);
430 
436  bool Flush();
437 
442  void Uncache(const uint256 &txid);
443 
445  unsigned int GetCacheSize() const;
446 
448  size_t DynamicMemoryUsage() const;
449 
458  CAmount GetValueIn(const CTransaction& tx) const;
459 
461  bool HaveInputs(const CTransaction& tx) const;
462 
468  double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const;
469 
470  const CTxOut &GetOutputFor(const CTxIn& input) const;
471 
472  friend class CCoinsModifier;
473 
474 private:
475  CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
476 
481 };
482 
483 #endif // BITCOIN_COINS_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:15
Pruned version of CTransaction: only retains metadata and unspent transaction outputs.
Definition: coins.h:75
bool Spend(uint32_t nPos)
mark a vout spent
Definition: coins.cpp:35
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
Definition: coins.h:81
CCoins(const CTransaction &tx, int nHeightIn)
construct a CCoins from a CTransaction, at a given height
Definition: coins.h:99
friend bool operator!=(const CCoins &a, const CCoins &b)
Definition: coins.h:146
void Clear()
Definition: coins.h:103
CCoins()
empty constructor
Definition: coins.h:111
bool IsPruned() const
check whether the entire CCoins is spent note that only !IsPruned() CCoins can be serialized
Definition: coins.h:229
friend bool operator==(const CCoins &a, const CCoins &b)
equality test
Definition: coins.h:137
void Cleanup()
remove spent outputs at the end of vout
Definition: coins.h:114
void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const
calculate number of bytes for the bitmask, and its number of non-zero bytes each bit in the bitmask r...
Definition: coins.cpp:17
size_t DynamicMemoryUsage() const
Definition: coins.h:236
void swap(CCoins &to)
Definition: coins.h:129
int nVersion
version of the CTransaction; accesses to this value should probably check for nHeight as well,...
Definition: coins.h:88
bool IsCoinBase() const
Definition: coins.h:152
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
Definition: coins.h:223
void FromTx(const CTransaction &tx, int nHeightIn)
Definition: coins.h:90
void Serialize(Stream &s) const
Definition: coins.h:157
void ClearUnspendable()
Definition: coins.h:121
bool fCoinBase
whether transaction is a coinbase
Definition: coins.h:78
void Unserialize(Stream &s)
Definition: coins.h:186
int nHeight
at which height this transaction was included in the active block chain
Definition: coins.h:84
A reference to a mutable cache entry.
Definition: coins.h:356
CCoinsMap::iterator it
Definition: coins.h:359
CCoinsViewCache & cache
Definition: coins.h:358
CCoins & operator*()
Definition: coins.h:365
CCoins * operator->()
Definition: coins.h:364
size_t cachedCoinUsage
Definition: coins.h:360
CCoinsModifier(CCoinsViewCache &cache_, CCoinsMap::iterator it_, size_t usage)
Definition: coins.cpp:317
CCoinsView backed by another CCoinsView.
Definition: coins.h:333
CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:57
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:54
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:52
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:55
CCoinsView * base
Definition: coins.h:335
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple CCoins changes + BestBlock change).
Definition: coins.cpp:56
bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
Definition: coins.cpp:53
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:51
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:372
uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:178
CAmount GetValueIn(const CTransaction &tx) const
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
Definition: coins.cpp:272
bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:90
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:382
bool hasModifier
Definition: coins.h:375
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:61
const CTxOut & GetOutputFor(const CTxIn &input) const
Definition: coins.cpp:265
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple CCoins changes + BestBlock change).
Definition: coins.cpp:188
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:284
bool HaveCoinsInCache(const uint256 &txid) const
Check if we have the given tx already loaded in this cache.
Definition: coins.cpp:173
~CCoinsViewCache()
Definition: coins.cpp:63
const CCoins * AccessCoins(const uint256 &txid) const
Return a pointer to CCoins in the cache, or NULL if not found.
Definition: coins.cpp:155
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transactions)
Definition: coins.cpp:261
CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const
Definition: coins.cpp:72
size_t cachedCoinsUsage
Definition: coins.h:386
double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
Return priority of tx at height nHeight.
Definition: coins.cpp:298
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:184
bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
Definition: coins.cpp:164
void Uncache(const uint256 &txid)
Removes the transaction with the given hash from the cache, if it is not modified.
Definition: coins.cpp:252
CCoinsModifier ModifyCoins(const uint256 &txid)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:99
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:245
CCoinsModifier ModifyNewCoins(const uint256 &txid, bool coinbase)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:134
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:68
CCoinsViewCache(const CCoinsViewCache &)
By making the copy constructor private, we prevent accidentally using it when one intends to create a...
CCoinsMap cacheCoins
Definition: coins.h:383
Cursor for iterating over CoinsView state.
Definition: coins.h:286
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:288
virtual bool GetKey(uint256 &key) const =0
virtual unsigned int GetValueSize() const =0
uint256 hashBlock
Definition: coins.h:302
virtual bool GetValue(CCoins &coins) const =0
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:300
virtual ~CCoinsViewCursor()
Definition: coins.cpp:336
Abstract view on the open txout dataset.
Definition: coins.h:307
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:48
virtual bool GetCoins(const uint256 &txid, CCoins &coins) const
Retrieve the CCoins (unspent transaction outputs) for a given txid.
Definition: coins.cpp:44
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:327
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple CCoins changes + BestBlock change).
Definition: coins.cpp:47
virtual bool HaveCoins(const uint256 &txid) const
Just check whether we have data for a given txid.
Definition: coins.cpp:45
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:46
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:635
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:308
const std::vector< CTxOut > vout
Definition: transaction.h:327
bool IsCoinBase() const
Definition: transaction.h:383
const int32_t nVersion
Definition: transaction.h:325
An input of a transaction.
Definition: transaction.h:63
wrapper for CTxOut that provides a more compact serialization
Definition: compressor.h:94
An output of a transaction.
Definition: transaction.h:133
CScript scriptPubKey
Definition: transaction.h:136
void SetNull()
Definition: transaction.h:153
bool IsNull() const
Definition: transaction.h:159
const uint64_t k1
Definition: coins.h:249
size_t operator()(const uint256 &txid) const
This must return size_t.
Definition: coins.h:259
const uint64_t k0
Salt.
Definition: coins.h:249
256-bit opaque blob.
Definition: uint256.h:123
boost::unordered_map< uint256, CCoinsCacheEntry, SaltedTxidHasher > CCoinsMap
Definition: coins.h:282
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256 &val)
Optimized SipHash-2-4 implementation for uint256.
Definition: hash.cpp:172
#define VARINT(obj)
Definition: serialize.h:348
T & REF(const T &val)
Used to bypass the rule against non-const reference to temporary where it makes sense with wrappers s...
Definition: serialize.h:47
Definition: coins.h:265
unsigned char flags
Definition: coins.h:267
Flags
Definition: coins.h:269
@ FRESH
Definition: coins.h:271
@ DIRTY
Definition: coins.h:270
CCoins coins
Definition: coins.h:266
CCoinsCacheEntry()
Definition: coins.h:279