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"
22 #include <unordered_map>
24 #include <boost/foreach.hpp>
25 #include <boost/unordered_map.hpp>
26 #include "zcash/IncrementalMerkleTree.hpp"
27 #include "veruslaunch.h"
30 * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
35 * - unspentness bitvector, for vout[2] and further; least significant byte first
36 * - the non-spent CTxOuts (via CTxOutCompressor)
39 * The nCode value consists of:
40 * - bit 1: IsCoinBase()
41 * - bit 2: vout[0] is not spent
42 * - bit 4: vout[1] is not spent
43 * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
44 * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
45 * least one non-spent output).
47 * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
48 * <><><--------------------------------------------><---->
50 * version code vout[1] height
53 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
54 * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
55 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
56 * * 8358: compact amount representation for 60000000000 (600 BTC)
57 * * 00: special txout type pay-to-pubkey-hash
58 * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
62 * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
63 * <><><--><--------------------------------------------------><----------------------------------------------><---->
65 * version code unspentness vout[4] vout[16] height
68 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
69 * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
70 * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
71 * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
72 * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
73 * * 00: special txout type pay-to-pubkey-hash
74 * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
75 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
76 * * bbd123: compact amount representation for 110397 (0.001 BTC)
77 * * 00: special txout type pay-to-pubkey-hash
78 * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
84 //! whether transaction is a coinbase
87 //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
88 std::vector<CTxOut> vout;
90 //! at which height this transaction was included in the active block chain
93 //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
94 //! as new tx version will probably only be introduced at certain heights
98 void FromTx(const CTransaction &tx, int nHeightIn) {
99 fCoinBase = tx.IsCoinBase();
102 nVersion = tx.nVersion;
103 //nLockTime = tx.nLockTime;
107 //! construct a CCoins from a CTransaction, at a given height
108 CCoins(const CTransaction &tx, int nHeightIn) {
109 FromTx(tx, nHeightIn);
114 std::vector<CTxOut>().swap(vout);
119 //! empty constructor
120 CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
122 //!remove spent outputs at the end of vout
124 while (vout.size() > 0 && vout.back().IsNull())
127 std::vector<CTxOut>().swap(vout);
130 void ClearUnspendable() {
131 BOOST_FOREACH(CTxOut &txout, vout) {
132 if (txout.scriptPubKey.IsUnspendable())
138 void swap(CCoins &to) {
139 std::swap(to.fCoinBase, fCoinBase);
141 std::swap(to.nHeight, nHeight);
142 std::swap(to.nVersion, nVersion);
146 friend bool operator==(const CCoins &a, const CCoins &b) {
147 // Empty CCoins objects are always equal.
148 if (a.IsPruned() && b.IsPruned())
150 return a.fCoinBase == b.fCoinBase &&
151 a.nHeight == b.nHeight &&
152 a.nVersion == b.nVersion &&
155 friend bool operator!=(const CCoins &a, const CCoins &b) {
159 void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
161 bool IsCoinBase() const {
165 template<typename Stream>
166 void Serialize(Stream &s) const {
167 unsigned int nMaskSize = 0, nMaskCode = 0;
168 CalcMaskSize(nMaskSize, nMaskCode);
169 bool fFirst = vout.size() > 0 && !vout[0].IsNull();
170 bool fSecond = vout.size() > 1 && !vout[1].IsNull();
171 assert(fFirst || fSecond || nMaskCode);
172 unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
174 ::Serialize(s, VARINT(this->nVersion));
176 ::Serialize(s, VARINT(nCode));
178 for (unsigned int b = 0; b<nMaskSize; b++) {
179 unsigned char chAvail = 0;
180 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
181 if (!vout[2+b*8+i].IsNull())
183 ::Serialize(s, chAvail);
186 for (unsigned int i = 0; i < vout.size(); i++) {
187 if (!vout[i].IsNull())
188 ::Serialize(s, CTxOutCompressor(REF(vout[i])));
191 ::Serialize(s, VARINT(nHeight));
194 template<typename Stream>
195 void Unserialize(Stream &s) {
196 unsigned int nCode = 0;
198 ::Unserialize(s, VARINT(this->nVersion));
200 ::Unserialize(s, VARINT(nCode));
201 fCoinBase = nCode & 1;
202 std::vector<bool> vAvail(2, false);
203 vAvail[0] = (nCode & 2) != 0;
204 vAvail[1] = (nCode & 4) != 0;
205 unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
207 while (nMaskCode > 0) {
208 unsigned char chAvail = 0;
209 ::Unserialize(s, chAvail);
210 for (unsigned int p = 0; p < 8; p++) {
211 bool f = (chAvail & (1 << p)) != 0;
218 vout.assign(vAvail.size(), CTxOut());
219 for (unsigned int i = 0; i < vAvail.size(); i++) {
221 ::Unserialize(s, REF(CTxOutCompressor(vout[i])));
224 ::Unserialize(s, VARINT(nHeight));
228 //! mark a vout spent
229 bool Spend(uint32_t nPos);
231 //! check whether a particular output is still available
232 bool IsAvailable(unsigned int nPos) const {
233 return (nPos < vout.size() && !vout[nPos].IsNull());
236 //! check whether the entire CCoins is spent
237 //! note that only !IsPruned() CCoins can be serialized
238 bool IsPruned() const {
239 BOOST_FOREACH(const CTxOut &out, vout)
245 size_t DynamicMemoryUsage() const {
246 size_t ret = memusage::DynamicUsage(vout);
247 BOOST_FOREACH(const CTxOut &out, vout) {
248 ret += RecursiveDynamicUsage(out.scriptPubKey);
253 int64_t TotalTxValue() const {
255 BOOST_FOREACH(const CTxOut &out, vout) {
262 class CCoinsKeyHasher
271 * This *must* return size_t. With Boost 1.46 on 32-bit systems the
272 * unordered_map will behave unpredictably if the custom hasher returns a
273 * uint64_t, resulting in failures when syncing the chain (#4634).
275 size_t operator()(const uint256& key) const {
276 return key.GetHash(salt);
280 struct CCoinsCacheEntry
282 CCoins coins; // The actual cached data.
286 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
287 FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
290 CCoinsCacheEntry() : coins(), flags(0) {}
293 struct CAnchorsSproutCacheEntry
295 bool entered; // This will be false if the anchor is removed from the cache
296 SproutMerkleTree tree; // The tree itself
300 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
303 CAnchorsSproutCacheEntry() : entered(false), flags(0) {}
306 struct CAnchorsSaplingCacheEntry
308 bool entered; // This will be false if the anchor is removed from the cache
309 SaplingMerkleTree tree; // The tree itself
313 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
316 CAnchorsSaplingCacheEntry() : entered(false), flags(0) {}
319 struct CNullifiersCacheEntry
321 bool entered; // If the nullifier is spent or not
325 DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
328 CNullifiersCacheEntry() : entered(false), flags(0) {}
337 typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
338 typedef boost::unordered_map<uint256, CAnchorsSproutCacheEntry, CCoinsKeyHasher> CAnchorsSproutMap;
339 typedef boost::unordered_map<uint256, CAnchorsSaplingCacheEntry, CCoinsKeyHasher> CAnchorsSaplingMap;
340 typedef boost::unordered_map<uint256, CNullifiersCacheEntry, CCoinsKeyHasher> CNullifiersMap;
346 uint64_t nTransactions;
347 uint64_t nTransactionOutputs;
348 uint64_t nSerializedSize;
349 uint256 hashSerialized;
350 CAmount nTotalAmount;
352 CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
356 /** Abstract view on the open txout dataset. */
360 //! Retrieve the tree (Sprout) at a particular anchored root in the chain
361 virtual bool GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const;
363 //! Retrieve the tree (Sapling) at a particular anchored root in the chain
364 virtual bool GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const;
366 //! Determine whether a nullifier is spent or not
367 virtual bool GetNullifier(const uint256 &nullifier, ShieldedType type) const;
369 //! Retrieve the CCoins (unspent transaction outputs) for a given txid
370 virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
372 //! Just check whether we have data for a given txid.
373 //! This may (but cannot always) return true for fully spent transactions
374 virtual bool HaveCoins(const uint256 &txid) const;
376 //! Retrieve the block hash whose state this CCoinsView currently represents
377 virtual uint256 GetBestBlock() const;
379 //! Get the current "tip" or the latest anchored tree root in the chain
380 virtual uint256 GetBestAnchor(ShieldedType type) const;
382 //! Do a bulk modification (multiple CCoins changes + BestBlock change).
383 //! The passed mapCoins can be modified.
384 virtual bool BatchWrite(CCoinsMap &mapCoins,
385 const uint256 &hashBlock,
386 const uint256 &hashSproutAnchor,
387 const uint256 &hashSaplingAnchor,
388 CAnchorsSproutMap &mapSproutAnchors,
389 CAnchorsSaplingMap &mapSaplingAnchors,
390 CNullifiersMap &mapSproutNullifiers,
391 CNullifiersMap &mapSaplingNullifiers);
393 //! Calculate statistics about the unspent transaction output set
394 virtual bool GetStats(CCoinsStats &stats) const;
396 //! As we use CCoinsViews polymorphically, have a virtual destructor
397 virtual ~CCoinsView() {}
401 /** CCoinsView backed by another CCoinsView */
402 class CCoinsViewBacked : public CCoinsView
408 CCoinsViewBacked(CCoinsView *viewIn);
409 bool GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const;
410 bool GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const;
411 bool GetNullifier(const uint256 &nullifier, ShieldedType type) const;
412 bool GetCoins(const uint256 &txid, CCoins &coins) const;
413 bool HaveCoins(const uint256 &txid) const;
414 uint256 GetBestBlock() const;
415 uint256 GetBestAnchor(ShieldedType type) const;
416 void SetBackend(CCoinsView &viewIn);
417 bool BatchWrite(CCoinsMap &mapCoins,
418 const uint256 &hashBlock,
419 const uint256 &hashSproutAnchor,
420 const uint256 &hashSaplingAnchor,
421 CAnchorsSproutMap &mapSproutAnchors,
422 CAnchorsSaplingMap &mapSaplingAnchors,
423 CNullifiersMap &mapSproutNullifiers,
424 CNullifiersMap &mapSaplingNullifiers);
425 bool GetStats(CCoinsStats &stats) const;
429 class CCoinsViewCache;
432 * A reference to a mutable cache entry. Encapsulating it allows us to run
433 * cleanup code after the modification is finished, and keeping track of
434 * concurrent modifications.
439 CCoinsViewCache& cache;
440 CCoinsMap::iterator it;
441 size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
442 CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
445 CCoins* operator->() { return &it->second.coins; }
446 CCoins& operator*() { return it->second.coins; }
448 friend class CCoinsViewCache;
451 class CTransactionExceptionData
454 CScript scriptPubKey;
456 CTransactionExceptionData() : scriptPubKey(), voutMask() {}
462 std::unordered_map<std::string, CTransactionExceptionData> lmap;
463 CLaunchMap() : lmap()
465 //printf("txid: %s -> addr: %s\n", whitelist_ids[i], whitelist_addrs[i]);
466 CBitcoinAddress bcaddr(whitelist_address);
468 if (bcaddr.GetKeyID_NoCheck(key))
470 std::vector<unsigned char> address = std::vector<unsigned char>(key.begin(), key.end());
471 for (int i = 0; i < WHITELIST_COUNT; i++)
473 std::string hash = uint256S(whitelist_ids[i]).ToString();
474 lmap[hash].scriptPubKey << OP_DUP << OP_HASH160 << address << OP_EQUALVERIFY << OP_CHECKSIG;
475 lmap[hash].voutMask = whitelist_masks[i];
480 static CLaunchMap launchMap = CLaunchMap();
482 /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
483 class CCoinsViewCache : public CCoinsViewBacked
486 /* Whether this cache has an active modifier. */
490 * Make mutable so that we can "fill the cache" even from Get-methods
491 * declared as "const".
493 mutable uint256 hashBlock;
494 mutable CCoinsMap cacheCoins;
495 mutable uint256 hashSproutAnchor;
496 mutable uint256 hashSaplingAnchor;
497 mutable CAnchorsSproutMap cacheSproutAnchors;
498 mutable CAnchorsSaplingMap cacheSaplingAnchors;
499 mutable CNullifiersMap cacheSproutNullifiers;
500 mutable CNullifiersMap cacheSaplingNullifiers;
502 /* Cached dynamic memory usage for the inner CCoins objects. */
503 mutable size_t cachedCoinsUsage;
506 CCoinsViewCache(CCoinsView *baseIn);
509 // Standard CCoinsView methods
510 static CLaunchMap &LaunchMap() { return launchMap; }
511 bool GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const;
512 bool GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const;
513 bool GetNullifier(const uint256 &nullifier, ShieldedType type) const;
514 bool GetCoins(const uint256 &txid, CCoins &coins) const;
515 bool HaveCoins(const uint256 &txid) const;
516 uint256 GetBestBlock() const;
517 uint256 GetBestAnchor(ShieldedType type) const;
518 void SetBestBlock(const uint256 &hashBlock);
519 bool BatchWrite(CCoinsMap &mapCoins,
520 const uint256 &hashBlock,
521 const uint256 &hashSproutAnchor,
522 const uint256 &hashSaplingAnchor,
523 CAnchorsSproutMap &mapSproutAnchors,
524 CAnchorsSaplingMap &mapSaplingAnchors,
525 CNullifiersMap &mapSproutNullifiers,
526 CNullifiersMap &mapSaplingNullifiers);
529 // Adds the tree to mapSproutAnchors (or mapSaplingAnchors based on the type of tree)
530 // and sets the current commitment root to this root.
531 template<typename Tree> void PushAnchor(const Tree &tree);
533 // Removes the current commitment root from mapAnchors and sets
534 // the new current root.
535 void PopAnchor(const uint256 &rt, ShieldedType type);
537 // Marks nullifiers for a given transaction as spent or not.
538 void SetNullifiers(const CTransaction& tx, bool spent);
541 * Return a pointer to CCoins in the cache, or NULL if not found. This is
542 * more efficient than GetCoins. Modifications to other cache entries are
543 * allowed while accessing the returned pointer.
545 const CCoins* AccessCoins(const uint256 &txid) const;
548 * Return a modifiable reference to a CCoins. If no entry with the given
549 * txid exists, a new one is created. Simultaneous modifications are not
552 CCoinsModifier ModifyCoins(const uint256 &txid);
555 * Push the modifications applied to this cache to its base.
556 * Failure to call this method before destruction will cause the changes to be forgotten.
557 * If false is returned, the state of this cache (and its backing view) will be undefined.
561 //! Calculate the size of the cache (in number of transactions)
562 unsigned int GetCacheSize() const;
564 //! Calculate the size of the cache (in bytes)
565 size_t DynamicMemoryUsage() const;
568 * Amount of bitcoins coming in to a transaction
569 * Note that lightweight clients may not know anything besides the hash of previous transactions,
570 * so may not be able to calculate this.
572 * @param[in] tx transaction for which we are checking input total
573 * @return Sum of value of all inputs (scriptSigs), (positive valueBalance or zero) and JoinSplit vpub_new
575 CAmount GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t prevblocktime) const;
577 //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
578 bool HaveInputs(const CTransaction& tx) const;
580 //! Check whether all joinsplit requirements (anchors/nullifiers) are satisfied
581 bool HaveJoinSplitRequirements(const CTransaction& tx) const;
583 //! Return priority of tx at height nHeight
584 double GetPriority(const CTransaction &tx, int nHeight) const;
586 const CTxOut &GetOutputFor(const CTxIn& input) const;
587 const CScript &GetSpendFor(const CTxIn& input) const;
588 static const CScript &GetSpendFor(const CCoins *coins, const CTxIn& input);
590 friend class CCoinsModifier;
593 CCoinsMap::iterator FetchCoins(const uint256 &txid);
594 CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
597 * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
599 CCoinsViewCache(const CCoinsViewCache &);
601 //! Generalized interface for popping anchors
602 template<typename Tree, typename Cache, typename CacheEntry>
603 void AbstractPopAnchor(
604 const uint256 &newrt,
610 //! Generalized interface for pushing anchors
611 template<typename Tree, typename Cache, typename CacheIterator, typename CacheEntry>
612 void AbstractPushAnchor(
619 //! Interface for bringing an anchor into the cache.
620 template<typename Tree>
621 void BringBestAnchorIntoCache(
622 const uint256 ¤tRoot,
627 #endif // BITCOIN_COINS_H