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"
10 #include "core_memusage.h"
12 #include "serialize.h"
18 #include <boost/foreach.hpp>
19 #include <boost/unordered_map.hpp>
20 #include "zcash/IncrementalMerkleTree.hpp"
23 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
28 * - unspentness bitvector, for vout[2] and further; least significant byte first
29 * - the non-spent CTxOuts (via CTxOutCompressor)
32 * The nCode value consists of:
33 * - bit 1: IsCoinBase()
34 * - bit 2: vout[0] is not spent
35 * - bit 4: vout[1] is not spent
36 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
37 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
38 * least one non-spent output).
40 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
41 * <><><--------------------------------------------><---->
43 * version code vout[1] height
46 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
47 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
48 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
49 * * 8358: compact amount representation for 60000000000 (600 BTC)
50 * * 00: special txout type pay-to-pubkey-hash
51 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
55 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
56 * <><><--><--------------------------------------------------><----------------------------------------------><---->
58 * version code unspentness vout[4] vout[16] height
61 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
62 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
63 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
64 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
65 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
66 * * 00: special txout type pay-to-pubkey-hash
67 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
68 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
69 * * bbd123: compact amount representation for 110397 (0.001 BTC)
70 * * 00: special txout type pay-to-pubkey-hash
71 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
77 //! whether transaction is a coinbase
80 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
81 std::vector<CTxOut> vout;
83 //! at which height this transaction was included in the active block chain
86 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
87 //! as new tx version will probably only be introduced at certain heights
90 void FromTx(const CTransaction &tx, int nHeightIn) {
91 fCoinBase = tx.IsCoinBase();
94 nVersion = tx.nVersion;
98 //! construct a CCoins from a CTransaction, at a given height
99 CCoins(const CTransaction &tx, int nHeightIn) {
100 FromTx(tx, nHeightIn);
105 std::vector<CTxOut>().swap(vout);
110 //! empty constructor
111 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
113 //!remove spent outputs at the end of vout
115 while (vout.size() > 0 && vout.back().IsNull())
118 std::vector<CTxOut>().swap(vout);
121 void ClearUnspendable() {
122 BOOST_FOREACH(CTxOut &txout, vout) {
123 if (txout.scriptPubKey.IsUnspendable())
129 void swap(CCoins &to) {
130 std::swap(to.fCoinBase, fCoinBase);
132 std::swap(to.nHeight, nHeight);
133 std::swap(to.nVersion, nVersion);
137 friend bool operator==(const CCoins &a, const CCoins &b) {
138 // Empty CCoins objects are always equal.
139 if (a.IsPruned() && b.IsPruned())
141 return a.fCoinBase == b.fCoinBase &&
142 a.nHeight == b.nHeight &&
143 a.nVersion == b.nVersion &&
146 friend bool operator!=(const CCoins &a, const CCoins &b) {
150 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
152 bool IsCoinBase() const {
156 unsigned int GetSerializeSize(int nType, int nVersion) const {
157 unsigned int nSize = 0;
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);
165 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
166 // size of header code
167 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
171 for (unsigned int i = 0; i < vout.size(); i++)
172 if (!vout[i].IsNull())
173 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
175 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
179 template<typename Stream>
180 void Serialize(Stream &s, int nType, int nVersion) const {
181 unsigned int nMaskSize = 0, nMaskCode = 0;
182 CalcMaskSize(nMaskSize, nMaskCode);
183 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
184 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
185 assert(fFirst || fSecond || nMaskCode);
186 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
188 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
190 ::Serialize(s, VARINT(nCode), nType, nVersion);
192 for (unsigned int b = 0; b<nMaskSize; b++) {
193 unsigned char chAvail = 0;
194 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
195 if (!vout[2+b*8+i].IsNull())
197 ::Serialize(s, chAvail, nType, nVersion);
200 for (unsigned int i = 0; i < vout.size(); i++) {
201 if (!vout[i].IsNull())
202 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
205 ::Serialize(s, VARINT(nHeight), nType, nVersion);
208 template<typename Stream>
209 void Unserialize(Stream &s, int nType, int nVersion) {
210 unsigned int nCode = 0;
212 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
214 ::Unserialize(s, VARINT(nCode), nType, nVersion);
215 fCoinBase = nCode & 1;
216 std::vector<bool> vAvail(2, false);
217 vAvail[0] = (nCode & 2) != 0;
218 vAvail[1] = (nCode & 4) != 0;
219 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
221 while (nMaskCode > 0) {
222 unsigned char chAvail = 0;
223 ::Unserialize(s, chAvail, nType, nVersion);
224 for (unsigned int p = 0; p < 8; p++) {
225 bool f = (chAvail & (1 << p)) != 0;
232 vout.assign(vAvail.size(), CTxOut());
233 for (unsigned int i = 0; i < vAvail.size(); i++) {
235 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
238 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
242 //! mark a vout spent
243 bool Spend(uint32_t nPos);
245 //! check whether a particular output is still available
246 bool IsAvailable(unsigned int nPos) const {
247 return (nPos < vout.size() && !vout[nPos].IsNull());
250 //! check whether the entire CCoins is spent
251 //! note that only !IsPruned() CCoins can be serialized
252 bool IsPruned() const {
253 BOOST_FOREACH(const CTxOut &out, vout)
259 size_t DynamicMemoryUsage() const {
260 size_t ret = memusage::DynamicUsage(vout);
261 BOOST_FOREACH(const CTxOut &out, vout) {
262 ret += RecursiveDynamicUsage(out.scriptPubKey);
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