1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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.
6 #ifndef BITCOIN_COINS_H
7 #define BITCOIN_COINS_H
9 #include "compressor.h"
11 #include "serialize.h"
17 #include <boost/foreach.hpp>
18 #include <boost/unordered_map.hpp>
19 #include "zcash/IncrementalMerkleTree.hpp"
22 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
27 * - unspentness bitvector, for vout[2] and further; least significant byte first
28 * - the non-spent CTxOuts (via CTxOutCompressor)
31 * The nCode value consists of:
32 * - bit 1: IsCoinBase()
33 * - bit 2: vout[0] is not spent
34 * - bit 4: vout[1] is not spent
35 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
36 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
37 * least one non-spent output).
39 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
40 * <><><--------------------------------------------><---->
42 * version code vout[1] height
45 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
46 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
47 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
48 * * 8358: compact amount representation for 60000000000 (600 BTC)
49 * * 00: special txout type pay-to-pubkey-hash
50 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
54 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
55 * <><><--><--------------------------------------------------><----------------------------------------------><---->
57 * version code unspentness vout[4] vout[16] height
60 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
61 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
62 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
63 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
64 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
65 * * 00: special txout type pay-to-pubkey-hash
66 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
67 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
68 * * bbd123: compact amount representation for 110397 (0.001 BTC)
69 * * 00: special txout type pay-to-pubkey-hash
70 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
76 //! whether transaction is a coinbase
79 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
80 std::vector<CTxOut> vout;
82 //! at which height this transaction was included in the active block chain
85 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
86 //! as new tx version will probably only be introduced at certain heights
89 void FromTx(const CTransaction &tx, int nHeightIn) {
90 fCoinBase = tx.IsCoinBase();
93 nVersion = tx.nVersion;
97 //! construct a CCoins from a CTransaction, at a given height
98 CCoins(const CTransaction &tx, int nHeightIn) {
99 FromTx(tx, nHeightIn);
104 std::vector<CTxOut>().swap(vout);
109 //! empty constructor
110 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
112 //!remove spent outputs at the end of vout
114 while (vout.size() > 0 && vout.back().IsNull())
117 std::vector<CTxOut>().swap(vout);
120 void ClearUnspendable() {
121 BOOST_FOREACH(CTxOut &txout, vout) {
122 if (txout.scriptPubKey.IsUnspendable())
128 void swap(CCoins &to) {
129 std::swap(to.fCoinBase, fCoinBase);
131 std::swap(to.nHeight, nHeight);
132 std::swap(to.nVersion, nVersion);
136 friend bool operator==(const CCoins &a, const CCoins &b) {
137 // Empty CCoins objects are always equal.
138 if (a.IsPruned() && b.IsPruned())
140 return a.fCoinBase == b.fCoinBase &&
141 a.nHeight == b.nHeight &&
142 a.nVersion == b.nVersion &&
145 friend bool operator!=(const CCoins &a, const CCoins &b) {
149 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
151 bool IsCoinBase() const {
155 unsigned int GetSerializeSize(int nType, int nVersion) const {
156 unsigned int nSize = 0;
157 unsigned int nMaskSize = 0, nMaskCode = 0;
158 CalcMaskSize(nMaskSize, nMaskCode);
159 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
160 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
161 assert(fFirst || fSecond || nMaskCode);
162 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
164 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
165 // size of header code
166 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
170 for (unsigned int i = 0; i < vout.size(); i++)
171 if (!vout[i].IsNull())
172 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
174 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
178 template<typename Stream>
179 void Serialize(Stream &s, int nType, int nVersion) const {
180 unsigned int nMaskSize = 0, nMaskCode = 0;
181 CalcMaskSize(nMaskSize, nMaskCode);
182 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
183 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
184 assert(fFirst || fSecond || nMaskCode);
185 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
187 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
189 ::Serialize(s, VARINT(nCode), nType, nVersion);
191 for (unsigned int b = 0; b<nMaskSize; b++) {
192 unsigned char chAvail = 0;
193 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
194 if (!vout[2+b*8+i].IsNull())
196 ::Serialize(s, chAvail, nType, nVersion);
199 for (unsigned int i = 0; i < vout.size(); i++) {
200 if (!vout[i].IsNull())
201 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
204 ::Serialize(s, VARINT(nHeight), nType, nVersion);
207 template<typename Stream>
208 void Unserialize(Stream &s, int nType, int nVersion) {
209 unsigned int nCode = 0;
211 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
213 ::Unserialize(s, VARINT(nCode), nType, nVersion);
214 fCoinBase = nCode & 1;
215 std::vector<bool> vAvail(2, false);
216 vAvail[0] = (nCode & 2) != 0;
217 vAvail[1] = (nCode & 4) != 0;
218 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
220 while (nMaskCode > 0) {
221 unsigned char chAvail = 0;
222 ::Unserialize(s, chAvail, nType, nVersion);
223 for (unsigned int p = 0; p < 8; p++) {
224 bool f = (chAvail & (1 << p)) != 0;
231 vout.assign(vAvail.size(), CTxOut());
232 for (unsigned int i = 0; i < vAvail.size(); i++) {
234 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
237 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
241 //! mark a vout spent
242 bool Spend(uint32_t nPos);
244 //! check whether a particular output is still available
245 bool IsAvailable(unsigned int nPos) const {
246 return (nPos < vout.size() && !vout[nPos].IsNull());
249 //! check whether the entire CCoins is spent
250 //! note that only !IsPruned() CCoins can be serialized
251 bool IsPruned() const {
252 BOOST_FOREACH(const CTxOut &out, vout)
258 size_t DynamicMemoryUsage() const {
259 size_t ret = memusage::DynamicUsage(vout);
260 BOOST_FOREACH(const CTxOut &out, vout) {
261 const std::vector<unsigned char> *script = &out.scriptPubKey;
262 ret += memusage::DynamicUsage(*script);
268 class CCoinsKeyHasher
277 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
278 * unordered_map will behave unpredictably if the custom hasher returns a
279 * uint64_t, resulting in failures when syncing the chain (#4634).
281 size_t operator()(const uint256& key) const {
282 return key.GetHash(salt);
286 struct CCoinsCacheEntry
288 CCoins coins; // The actual cached data.
292 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
293 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
296 CCoinsCacheEntry() : coins(), flags(0) {}
299 struct CAnchorsCacheEntry
301 bool entered; // This will be false if the anchor is removed from the cache
302 ZCIncrementalMerkleTree tree; // The tree itself
306 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
309 CAnchorsCacheEntry() : entered(false), flags(0) {}
312 struct CNullifiersCacheEntry
314 bool entered; // If the nullifier is spent or not
318 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
321 CNullifiersCacheEntry() : entered(false), flags(0) {}
324 typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
325 typedef boost::unordered_map<uint256, CAnchorsCacheEntry, CCoinsKeyHasher> CAnchorsMap;
326 typedef boost::unordered_map<uint256, CNullifiersCacheEntry, CCoinsKeyHasher> CNullifiersMap;
332 uint64_t nTransactions;
333 uint64_t nTransactionOutputs;
334 uint64_t nSerializedSize;
335 uint256 hashSerialized;
336 CAmount nTotalAmount;
338 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
342 /** Abstract view on the open txout dataset. */
346 //! Retrieve the tree at a particular anchored root in the chain
347 virtual bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
349 //! Determine whether a nullifier is spent or not
350 virtual bool GetNullifier(const uint256 &nullifier) const;
352 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
353 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
355 //! Just check whether we have data for a given txid.
356 //! This may (but cannot always) return true for fully spent transactions
357 virtual bool HaveCoins(const uint256 &txid) const;
359 //! Retrieve the block hash whose state this CCoinsView currently represents
360 virtual uint256 GetBestBlock() const;
362 //! Get the current "tip" or the latest anchored tree root in the chain
363 virtual uint256 GetBestAnchor() const;
365 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
366 //! The passed mapCoins can be modified.
367 virtual bool BatchWrite(CCoinsMap &mapCoins,
368 const uint256 &hashBlock,
369 const uint256 &hashAnchor,
370 CAnchorsMap &mapAnchors,
371 CNullifiersMap &mapNullifiers);
373 //! Calculate statistics about the unspent transaction output set
374 virtual bool GetStats(CCoinsStats &stats) const;
376 //! As we use CCoinsViews polymorphically, have a virtual destructor
377 virtual ~CCoinsView() {}
381 /** CCoinsView backed by another CCoinsView */
382 class CCoinsViewBacked : public CCoinsView
388 CCoinsViewBacked(CCoinsView *viewIn);
389 bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
390 bool GetNullifier(const uint256 &nullifier) const;
391 bool GetCoins(const uint256 &txid, CCoins &coins) const;
392 bool HaveCoins(const uint256 &txid) const;
393 uint256 GetBestBlock() const;
394 uint256 GetBestAnchor() const;
395 void SetBackend(CCoinsView &viewIn);
396 bool BatchWrite(CCoinsMap &mapCoins,
397 const uint256 &hashBlock,
398 const uint256 &hashAnchor,
399 CAnchorsMap &mapAnchors,
400 CNullifiersMap &mapNullifiers);
401 bool GetStats(CCoinsStats &stats) const;
405 class CCoinsViewCache;
408 * A reference to a mutable cache entry. Encapsulating it allows us to run
409 * cleanup code after the modification is finished, and keeping track of
410 * concurrent modifications.
415 CCoinsViewCache& cache;
416 CCoinsMap::iterator it;
417 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
418 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
421 CCoins* operator->() { return &it->second.coins; }
422 CCoins& operator*() { return it->second.coins; }
424 friend class CCoinsViewCache;
427 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
428 class CCoinsViewCache : public CCoinsViewBacked
431 /* Whether this cache has an active modifier. */
436 * Make mutable so that we can "fill the cache" even from Get-methods
437 * declared as "const".
439 mutable uint256 hashBlock;
440 mutable CCoinsMap cacheCoins;
441 mutable uint256 hashAnchor;
442 mutable CAnchorsMap cacheAnchors;
443 mutable CNullifiersMap cacheNullifiers;
445 /* Cached dynamic memory usage for the inner CCoins objects. */
446 mutable size_t cachedCoinsUsage;
449 CCoinsViewCache(CCoinsView *baseIn);
452 // Standard CCoinsView methods
453 bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
454 bool GetNullifier(const uint256 &nullifier) const;
455 bool GetCoins(const uint256 &txid, CCoins &coins) const;
456 bool HaveCoins(const uint256 &txid) const;
457 uint256 GetBestBlock() const;
458 uint256 GetBestAnchor() const;
459 void SetBestBlock(const uint256 &hashBlock);
460 bool BatchWrite(CCoinsMap &mapCoins,
461 const uint256 &hashBlock,
462 const uint256 &hashAnchor,
463 CAnchorsMap &mapAnchors,
464 CNullifiersMap &mapNullifiers);
467 // Adds the tree to mapAnchors and sets the current commitment
468 // root to this root.
469 void PushAnchor(const ZCIncrementalMerkleTree &tree);
471 // Removes the current commitment root from mapAnchors and sets
472 // the new current root.
473 void PopAnchor(const uint256 &rt);
475 // Marks a nullifier as spent or not.
476 void SetNullifier(const uint256 &nullifier, bool spent);
479 * Return a pointer to CCoins in the cache, or NULL if not found. This is
480 * more efficient than GetCoins. Modifications to other cache entries are
481 * allowed while accessing the returned pointer.
483 const CCoins* AccessCoins(const uint256 &txid) const;
486 * Return a modifiable reference to a CCoins. If no entry with the given
487 * txid exists, a new one is created. Simultaneous modifications are not
490 CCoinsModifier ModifyCoins(const uint256 &txid);
493 * Push the modifications applied to this cache to its base.
494 * Failure to call this method before destruction will cause the changes to be forgotten.
495 * If false is returned, the state of this cache (and its backing view) will be undefined.
499 //! Calculate the size of the cache (in number of transactions)
500 unsigned int GetCacheSize() const;
502 //! Calculate the size of the cache (in bytes)
503 size_t DynamicMemoryUsage() const;
506 * Amount of bitcoins coming in to a transaction
507 * Note that lightweight clients may not know anything besides the hash of previous transactions,
508 * so may not be able to calculate this.
510 * @param[in] tx transaction for which we are checking input total
511 * @return Sum of value of all inputs (scriptSigs)
513 CAmount GetValueIn(const CTransaction& tx) const;
515 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
516 bool HaveInputs(const CTransaction& tx) const;
518 //! Check whether all joinsplit requirements (anchors/nullifiers) are satisfied
519 bool HaveJoinSplitRequirements(const CTransaction& tx) const;
521 //! Return priority of tx at height nHeight
522 double GetPriority(const CTransaction &tx, int nHeight) const;
524 const CTxOut &GetOutputFor(const CTxIn& input) const;
526 friend class CCoinsModifier;
529 CCoinsMap::iterator FetchCoins(const uint256 &txid);
530 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
533 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
535 CCoinsViewCache(const CCoinsViewCache &);
538 #endif // BITCOIN_COINS_H