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 #define KOMODO_ENABLE_INTEREST //enabling this is a hardfork, activate with new RR method
11 #include "compressor.h"
12 #include "core_memusage.h"
14 #include "serialize.h"
20 #include <boost/foreach.hpp>
21 #include <boost/unordered_map.hpp>
22 #include "zcash/IncrementalMerkleTree.hpp"
25 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
30 * - unspentness bitvector, for vout[2] and further; least significant byte first
31 * - the non-spent CTxOuts (via CTxOutCompressor)
34 * The nCode value consists of:
35 * - bit 1: IsCoinBase()
36 * - bit 2: vout[0] is not spent
37 * - bit 4: vout[1] is not spent
38 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
39 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
40 * least one non-spent output).
42 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
43 * <><><--------------------------------------------><---->
45 * version code vout[1] height
48 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
49 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
50 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
51 * * 8358: compact amount representation for 60000000000 (600 BTC)
52 * * 00: special txout type pay-to-pubkey-hash
53 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
57 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
58 * <><><--><--------------------------------------------------><----------------------------------------------><---->
60 * version code unspentness vout[4] vout[16] height
63 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
64 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
65 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
66 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
67 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
68 * * 00: special txout type pay-to-pubkey-hash
69 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
70 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
71 * * bbd123: compact amount representation for 110397 (0.001 BTC)
72 * * 00: special txout type pay-to-pubkey-hash
73 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
79 //! whether transaction is a coinbase
82 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
83 std::vector<CTxOut> vout;
85 //! at which height this transaction was included in the active block chain
88 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
89 //! as new tx version will probably only be introduced at certain heights
93 void FromTx(const CTransaction &tx, int nHeightIn) {
94 fCoinBase = tx.IsCoinBase();
97 nVersion = tx.nVersion;
98 //nLockTime = tx.nLockTime;
102 //! construct a CCoins from a CTransaction, at a given height
103 CCoins(const CTransaction &tx, int nHeightIn) {
104 FromTx(tx, nHeightIn);
109 std::vector<CTxOut>().swap(vout);
114 //! empty constructor
115 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
117 //!remove spent outputs at the end of vout
119 while (vout.size() > 0 && vout.back().IsNull())
122 std::vector<CTxOut>().swap(vout);
125 void ClearUnspendable() {
126 BOOST_FOREACH(CTxOut &txout, vout) {
127 if (txout.scriptPubKey.IsUnspendable())
133 void swap(CCoins &to) {
134 std::swap(to.fCoinBase, fCoinBase);
136 std::swap(to.nHeight, nHeight);
137 std::swap(to.nVersion, nVersion);
141 friend bool operator==(const CCoins &a, const CCoins &b) {
142 // Empty CCoins objects are always equal.
143 if (a.IsPruned() && b.IsPruned())
145 return a.fCoinBase == b.fCoinBase &&
146 a.nHeight == b.nHeight &&
147 a.nVersion == b.nVersion &&
150 friend bool operator!=(const CCoins &a, const CCoins &b) {
154 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
156 bool IsCoinBase() const {
160 unsigned int GetSerializeSize(int nType, int nVersion) const {
161 unsigned int nSize = 0;
162 unsigned int nMaskSize = 0, nMaskCode = 0;
163 CalcMaskSize(nMaskSize, nMaskCode);
164 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
165 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
166 assert(fFirst || fSecond || nMaskCode);
167 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
169 nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
170 // size of header code
171 nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
175 for (unsigned int i = 0; i < vout.size(); i++)
176 if (!vout[i].IsNull())
177 nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
179 nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
183 template<typename Stream>
184 void Serialize(Stream &s, int nType, int nVersion) const {
185 unsigned int nMaskSize = 0, nMaskCode = 0;
186 CalcMaskSize(nMaskSize, nMaskCode);
187 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
188 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
189 assert(fFirst || fSecond || nMaskCode);
190 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
192 ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
194 ::Serialize(s, VARINT(nCode), nType, nVersion);
196 for (unsigned int b = 0; b<nMaskSize; b++) {
197 unsigned char chAvail = 0;
198 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
199 if (!vout[2+b*8+i].IsNull())
201 ::Serialize(s, chAvail, nType, nVersion);
204 for (unsigned int i = 0; i < vout.size(); i++) {
205 if (!vout[i].IsNull())
206 ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
209 ::Serialize(s, VARINT(nHeight), nType, nVersion);
212 template<typename Stream>
213 void Unserialize(Stream &s, int nType, int nVersion) {
214 unsigned int nCode = 0;
216 ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
218 ::Unserialize(s, VARINT(nCode), nType, nVersion);
219 fCoinBase = nCode & 1;
220 std::vector<bool> vAvail(2, false);
221 vAvail[0] = (nCode & 2) != 0;
222 vAvail[1] = (nCode & 4) != 0;
223 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
225 while (nMaskCode > 0) {
226 unsigned char chAvail = 0;
227 ::Unserialize(s, chAvail, nType, nVersion);
228 for (unsigned int p = 0; p < 8; p++) {
229 bool f = (chAvail & (1 << p)) != 0;
236 vout.assign(vAvail.size(), CTxOut());
237 for (unsigned int i = 0; i < vAvail.size(); i++) {
239 ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
242 ::Unserialize(s, VARINT(nHeight), nType, nVersion);
246 //! mark a vout spent
247 bool Spend(uint32_t nPos);
249 //! check whether a particular output is still available
250 bool IsAvailable(unsigned int nPos) const {
251 return (nPos < vout.size() && !vout[nPos].IsNull());
254 //! check whether the entire CCoins is spent
255 //! note that only !IsPruned() CCoins can be serialized
256 bool IsPruned() const {
257 BOOST_FOREACH(const CTxOut &out, vout)
263 size_t DynamicMemoryUsage() const {
264 size_t ret = memusage::DynamicUsage(vout);
265 BOOST_FOREACH(const CTxOut &out, vout) {
266 ret += RecursiveDynamicUsage(out.scriptPubKey);
272 class CCoinsKeyHasher
281 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
282 * unordered_map will behave unpredictably if the custom hasher returns a
283 * uint64_t, resulting in failures when syncing the chain (#4634).
285 size_t operator()(const uint256& key) const {
286 return key.GetHash(salt);
290 struct CCoinsCacheEntry
292 CCoins coins; // The actual cached data.
296 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
297 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
300 CCoinsCacheEntry() : coins(), flags(0) {}
303 struct CAnchorsCacheEntry
305 bool entered; // This will be false if the anchor is removed from the cache
306 ZCIncrementalMerkleTree tree; // The tree itself
310 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
313 CAnchorsCacheEntry() : entered(false), flags(0) {}
316 struct CNullifiersCacheEntry
318 bool entered; // If the nullifier is spent or not
322 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
325 CNullifiersCacheEntry() : entered(false), flags(0) {}
328 typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
329 typedef boost::unordered_map<uint256, CAnchorsCacheEntry, CCoinsKeyHasher> CAnchorsMap;
330 typedef boost::unordered_map<uint256, CNullifiersCacheEntry, CCoinsKeyHasher> CNullifiersMap;
336 uint64_t nTransactions;
337 uint64_t nTransactionOutputs;
338 uint64_t nSerializedSize;
339 uint256 hashSerialized;
340 CAmount nTotalAmount;
342 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
346 /** Abstract view on the open txout dataset. */
350 //! Retrieve the tree at a particular anchored root in the chain
351 virtual bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
353 //! Determine whether a nullifier is spent or not
354 virtual bool GetNullifier(const uint256 &nullifier) const;
356 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
357 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
359 //! Just check whether we have data for a given txid.
360 //! This may (but cannot always) return true for fully spent transactions
361 virtual bool HaveCoins(const uint256 &txid) const;
363 //! Retrieve the block hash whose state this CCoinsView currently represents
364 virtual uint256 GetBestBlock() const;
366 //! Get the current "tip" or the latest anchored tree root in the chain
367 virtual uint256 GetBestAnchor() const;
369 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
370 //! The passed mapCoins can be modified.
371 virtual bool BatchWrite(CCoinsMap &mapCoins,
372 const uint256 &hashBlock,
373 const uint256 &hashAnchor,
374 CAnchorsMap &mapAnchors,
375 CNullifiersMap &mapNullifiers);
377 //! Calculate statistics about the unspent transaction output set
378 virtual bool GetStats(CCoinsStats &stats) const;
380 //! As we use CCoinsViews polymorphically, have a virtual destructor
381 virtual ~CCoinsView() {}
385 /** CCoinsView backed by another CCoinsView */
386 class CCoinsViewBacked : public CCoinsView
392 CCoinsViewBacked(CCoinsView *viewIn);
393 bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
394 bool GetNullifier(const uint256 &nullifier) const;
395 bool GetCoins(const uint256 &txid, CCoins &coins) const;
396 bool HaveCoins(const uint256 &txid) const;
397 uint256 GetBestBlock() const;
398 uint256 GetBestAnchor() const;
399 void SetBackend(CCoinsView &viewIn);
400 bool BatchWrite(CCoinsMap &mapCoins,
401 const uint256 &hashBlock,
402 const uint256 &hashAnchor,
403 CAnchorsMap &mapAnchors,
404 CNullifiersMap &mapNullifiers);
405 bool GetStats(CCoinsStats &stats) const;
409 class CCoinsViewCache;
412 * A reference to a mutable cache entry. Encapsulating it allows us to run
413 * cleanup code after the modification is finished, and keeping track of
414 * concurrent modifications.
419 CCoinsViewCache& cache;
420 CCoinsMap::iterator it;
421 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
422 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
425 CCoins* operator->() { return &it->second.coins; }
426 CCoins& operator*() { return it->second.coins; }
428 friend class CCoinsViewCache;
431 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
432 class CCoinsViewCache : public CCoinsViewBacked
435 /* Whether this cache has an active modifier. */
440 * Make mutable so that we can "fill the cache" even from Get-methods
441 * declared as "const".
443 mutable uint256 hashBlock;
444 mutable CCoinsMap cacheCoins;
445 mutable uint256 hashAnchor;
446 mutable CAnchorsMap cacheAnchors;
447 mutable CNullifiersMap cacheNullifiers;
449 /* Cached dynamic memory usage for the inner CCoins objects. */
450 mutable size_t cachedCoinsUsage;
453 CCoinsViewCache(CCoinsView *baseIn);
456 // Standard CCoinsView methods
457 bool GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const;
458 bool GetNullifier(const uint256 &nullifier) const;
459 bool GetCoins(const uint256 &txid, CCoins &coins) const;
460 bool HaveCoins(const uint256 &txid) const;
461 uint256 GetBestBlock() const;
462 uint256 GetBestAnchor() const;
463 void SetBestBlock(const uint256 &hashBlock);
464 bool BatchWrite(CCoinsMap &mapCoins,
465 const uint256 &hashBlock,
466 const uint256 &hashAnchor,
467 CAnchorsMap &mapAnchors,
468 CNullifiersMap &mapNullifiers);
471 // Adds the tree to mapAnchors and sets the current commitment
472 // root to this root.
473 void PushAnchor(const ZCIncrementalMerkleTree &tree);
475 // Removes the current commitment root from mapAnchors and sets
476 // the new current root.
477 void PopAnchor(const uint256 &rt);
479 // Marks a nullifier as spent or not.
480 void SetNullifier(const uint256 &nullifier, bool spent);
483 * Return a pointer to CCoins in the cache, or NULL if not found. This is
484 * more efficient than GetCoins. Modifications to other cache entries are
485 * allowed while accessing the returned pointer.
487 const CCoins* AccessCoins(const uint256 &txid) const;
490 * Return a modifiable reference to a CCoins. If no entry with the given
491 * txid exists, a new one is created. Simultaneous modifications are not
494 CCoinsModifier ModifyCoins(const uint256 &txid);
497 * Push the modifications applied to this cache to its base.
498 * Failure to call this method before destruction will cause the changes to be forgotten.
499 * If false is returned, the state of this cache (and its backing view) will be undefined.
503 //! Calculate the size of the cache (in number of transactions)
504 unsigned int GetCacheSize() const;
506 //! Calculate the size of the cache (in bytes)
507 size_t DynamicMemoryUsage() const;
510 * Amount of bitcoins coming in to a transaction
511 * Note that lightweight clients may not know anything besides the hash of previous transactions,
512 * so may not be able to calculate this.
514 * @param[in] tx transaction for which we are checking input total
515 * @return Sum of value of all inputs (scriptSigs)
517 CAmount GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t prevblocktime) const;
519 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
520 bool HaveInputs(const CTransaction& tx) const;
522 //! Check whether all joinsplit requirements (anchors/nullifiers) are satisfied
523 bool HaveJoinSplitRequirements(const CTransaction& tx) const;
525 //! Return priority of tx at height nHeight
526 double GetPriority(const CTransaction &tx, int nHeight) const;
528 const CTxOut &GetOutputFor(const CTxIn& input) const;
529 const CScript &GetSpendFor(const CTxIn& input) const;
531 friend class CCoinsModifier;
534 CCoinsMap::iterator FetchCoins(const uint256 &txid);
535 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
538 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
540 CCoinsViewCache(const CCoinsViewCache &);
543 #endif // BITCOIN_COINS_H