You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

coins.h 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2013 The Bitcoin developers
  3. // Distributed under the MIT/X11 software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. #ifndef BITCOIN_COINS_H
  6. #define BITCOIN_COINS_H
  7. #include "core.h"
  8. #include "serialize.h"
  9. #include "uint256.h"
  10. #include <assert.h>
  11. #include <stdint.h>
  12. #include <boost/foreach.hpp>
  13. #include <boost/unordered_map.hpp>
  14. /** pruned version of CTransaction: only retains metadata and unspent transaction outputs
  15. *
  16. * Serialized format:
  17. * - VARINT(nVersion)
  18. * - VARINT(nCode)
  19. * - unspentness bitvector, for vout[2] and further; least significant byte first
  20. * - the non-spent CTxOuts (via CTxOutCompressor)
  21. * - VARINT(nHeight)
  22. *
  23. * The nCode value consists of:
  24. * - bit 1: IsCoinBase()
  25. * - bit 2: vout[0] is not spent
  26. * - bit 4: vout[1] is not spent
  27. * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
  28. * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
  29. * least one non-spent output).
  30. *
  31. * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
  32. * <><><--------------------------------------------><---->
  33. * | \ | /
  34. * version code vout[1] height
  35. *
  36. * - version = 1
  37. * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
  38. * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
  39. * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
  40. * * 8358: compact amount representation for 60000000000 (600 BTC)
  41. * * 00: special txout type pay-to-pubkey-hash
  42. * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
  43. * - height = 203998
  44. *
  45. *
  46. * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
  47. * <><><--><--------------------------------------------------><----------------------------------------------><---->
  48. * / \ \ | | /
  49. * version code unspentness vout[4] vout[16] height
  50. *
  51. * - version = 1
  52. * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
  53. * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
  54. * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
  55. * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
  56. * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
  57. * * 00: special txout type pay-to-pubkey-hash
  58. * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
  59. * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
  60. * * bbd123: compact amount representation for 110397 (0.001 BTC)
  61. * * 00: special txout type pay-to-pubkey-hash
  62. * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
  63. * - height = 120891
  64. */
  65. class CCoins
  66. {
  67. public:
  68. // whether transaction is a coinbase
  69. bool fCoinBase;
  70. // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
  71. std::vector<CTxOut> vout;
  72. // at which height this transaction was included in the active block chain
  73. int nHeight;
  74. // version of the CTransaction; accesses to this value should probably check for nHeight as well,
  75. // as new tx version will probably only be introduced at certain heights
  76. int nVersion;
  77. // construct a CCoins from a CTransaction, at a given height
  78. CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) {
  79. ClearUnspendable();
  80. }
  81. // empty constructor
  82. CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
  83. // remove spent outputs at the end of vout
  84. void Cleanup() {
  85. while (vout.size() > 0 && vout.back().IsNull())
  86. vout.pop_back();
  87. if (vout.empty())
  88. std::vector<CTxOut>().swap(vout);
  89. }
  90. void ClearUnspendable() {
  91. BOOST_FOREACH(CTxOut &txout, vout) {
  92. if (txout.scriptPubKey.IsUnspendable())
  93. txout.SetNull();
  94. }
  95. Cleanup();
  96. }
  97. void swap(CCoins &to) {
  98. std::swap(to.fCoinBase, fCoinBase);
  99. to.vout.swap(vout);
  100. std::swap(to.nHeight, nHeight);
  101. std::swap(to.nVersion, nVersion);
  102. }
  103. // equality test
  104. friend bool operator==(const CCoins &a, const CCoins &b) {
  105. // Empty CCoins objects are always equal.
  106. if (a.IsPruned() && b.IsPruned())
  107. return true;
  108. return a.fCoinBase == b.fCoinBase &&
  109. a.nHeight == b.nHeight &&
  110. a.nVersion == b.nVersion &&
  111. a.vout == b.vout;
  112. }
  113. friend bool operator!=(const CCoins &a, const CCoins &b) {
  114. return !(a == b);
  115. }
  116. void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
  117. bool IsCoinBase() const {
  118. return fCoinBase;
  119. }
  120. unsigned int GetSerializeSize(int nType, int nVersion) const {
  121. unsigned int nSize = 0;
  122. unsigned int nMaskSize = 0, nMaskCode = 0;
  123. CalcMaskSize(nMaskSize, nMaskCode);
  124. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  125. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  126. assert(fFirst || fSecond || nMaskCode);
  127. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  128. // version
  129. nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
  130. // size of header code
  131. nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
  132. // spentness bitmask
  133. nSize += nMaskSize;
  134. // txouts themself
  135. for (unsigned int i = 0; i < vout.size(); i++)
  136. if (!vout[i].IsNull())
  137. nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
  138. // height
  139. nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
  140. return nSize;
  141. }
  142. template<typename Stream>
  143. void Serialize(Stream &s, int nType, int nVersion) const {
  144. unsigned int nMaskSize = 0, nMaskCode = 0;
  145. CalcMaskSize(nMaskSize, nMaskCode);
  146. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  147. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  148. assert(fFirst || fSecond || nMaskCode);
  149. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  150. // version
  151. ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
  152. // header code
  153. ::Serialize(s, VARINT(nCode), nType, nVersion);
  154. // spentness bitmask
  155. for (unsigned int b = 0; b<nMaskSize; b++) {
  156. unsigned char chAvail = 0;
  157. for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
  158. if (!vout[2+b*8+i].IsNull())
  159. chAvail |= (1 << i);
  160. ::Serialize(s, chAvail, nType, nVersion);
  161. }
  162. // txouts themself
  163. for (unsigned int i = 0; i < vout.size(); i++) {
  164. if (!vout[i].IsNull())
  165. ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
  166. }
  167. // coinbase height
  168. ::Serialize(s, VARINT(nHeight), nType, nVersion);
  169. }
  170. template<typename Stream>
  171. void Unserialize(Stream &s, int nType, int nVersion) {
  172. unsigned int nCode = 0;
  173. // version
  174. ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
  175. // header code
  176. ::Unserialize(s, VARINT(nCode), nType, nVersion);
  177. fCoinBase = nCode & 1;
  178. std::vector<bool> vAvail(2, false);
  179. vAvail[0] = nCode & 2;
  180. vAvail[1] = nCode & 4;
  181. unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
  182. // spentness bitmask
  183. while (nMaskCode > 0) {
  184. unsigned char chAvail = 0;
  185. ::Unserialize(s, chAvail, nType, nVersion);
  186. for (unsigned int p = 0; p < 8; p++) {
  187. bool f = (chAvail & (1 << p)) != 0;
  188. vAvail.push_back(f);
  189. }
  190. if (chAvail != 0)
  191. nMaskCode--;
  192. }
  193. // txouts themself
  194. vout.assign(vAvail.size(), CTxOut());
  195. for (unsigned int i = 0; i < vAvail.size(); i++) {
  196. if (vAvail[i])
  197. ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
  198. }
  199. // coinbase height
  200. ::Unserialize(s, VARINT(nHeight), nType, nVersion);
  201. Cleanup();
  202. }
  203. // mark an outpoint spent, and construct undo information
  204. bool Spend(const COutPoint &out, CTxInUndo &undo);
  205. // mark a vout spent
  206. bool Spend(int nPos);
  207. // check whether a particular output is still available
  208. bool IsAvailable(unsigned int nPos) const {
  209. return (nPos < vout.size() && !vout[nPos].IsNull());
  210. }
  211. // check whether the entire CCoins is spent
  212. // note that only !IsPruned() CCoins can be serialized
  213. bool IsPruned() const {
  214. BOOST_FOREACH(const CTxOut &out, vout)
  215. if (!out.IsNull())
  216. return false;
  217. return true;
  218. }
  219. };
  220. class CCoinsKeyHasher
  221. {
  222. private:
  223. uint256 salt;
  224. public:
  225. CCoinsKeyHasher();
  226. // This *must* return size_t. With Boost 1.46 on 32-bit systems the
  227. // unordered_map will behave unpredictably if the custom hasher returns a
  228. // uint64_t, resulting in failures when syncing the chain (#4634).
  229. size_t operator()(const uint256& key) const {
  230. return key.GetHash(salt);
  231. }
  232. };
  233. typedef boost::unordered_map<uint256, CCoins, CCoinsKeyHasher> CCoinsMap;
  234. struct CCoinsStats
  235. {
  236. int nHeight;
  237. uint256 hashBlock;
  238. uint64_t nTransactions;
  239. uint64_t nTransactionOutputs;
  240. uint64_t nSerializedSize;
  241. uint256 hashSerialized;
  242. int64_t nTotalAmount;
  243. CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
  244. };
  245. /** Abstract view on the open txout dataset. */
  246. class CCoinsView
  247. {
  248. public:
  249. // Retrieve the CCoins (unspent transaction outputs) for a given txid
  250. virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
  251. // Modify the CCoins for a given txid
  252. virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
  253. // Just check whether we have data for a given txid.
  254. // This may (but cannot always) return true for fully spent transactions
  255. virtual bool HaveCoins(const uint256 &txid) const;
  256. // Retrieve the block hash whose state this CCoinsView currently represents
  257. virtual uint256 GetBestBlock() const;
  258. // Modify the currently active block hash
  259. virtual bool SetBestBlock(const uint256 &hashBlock);
  260. // Do a bulk modification (multiple SetCoins + one SetBestBlock).
  261. // The passed mapCoins can be modified.
  262. virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  263. // Calculate statistics about the unspent transaction output set
  264. virtual bool GetStats(CCoinsStats &stats) const;
  265. // As we use CCoinsViews polymorphically, have a virtual destructor
  266. virtual ~CCoinsView() {}
  267. };
  268. /** CCoinsView backed by another CCoinsView */
  269. class CCoinsViewBacked : public CCoinsView
  270. {
  271. protected:
  272. CCoinsView *base;
  273. public:
  274. CCoinsViewBacked(CCoinsView &viewIn);
  275. bool GetCoins(const uint256 &txid, CCoins &coins) const;
  276. bool SetCoins(const uint256 &txid, const CCoins &coins);
  277. bool HaveCoins(const uint256 &txid) const;
  278. uint256 GetBestBlock() const;
  279. bool SetBestBlock(const uint256 &hashBlock);
  280. void SetBackend(CCoinsView &viewIn);
  281. bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  282. bool GetStats(CCoinsStats &stats) const;
  283. };
  284. /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
  285. class CCoinsViewCache : public CCoinsViewBacked
  286. {
  287. protected:
  288. /* Make mutable so that we can "fill the cache" even from Get-methods
  289. declared as "const". */
  290. mutable uint256 hashBlock;
  291. mutable CCoinsMap cacheCoins;
  292. public:
  293. CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
  294. // Standard CCoinsView methods
  295. bool GetCoins(const uint256 &txid, CCoins &coins) const;
  296. bool SetCoins(const uint256 &txid, const CCoins &coins);
  297. bool HaveCoins(const uint256 &txid) const;
  298. uint256 GetBestBlock() const;
  299. bool SetBestBlock(const uint256 &hashBlock);
  300. bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  301. // Return a modifiable reference to a CCoins. Check HaveCoins first.
  302. // Many methods explicitly require a CCoinsViewCache because of this method, to reduce
  303. // copying.
  304. CCoins &GetCoins(const uint256 &txid);
  305. const CCoins &GetCoins(const uint256 &txid) const;
  306. // Push the modifications applied to this cache to its base.
  307. // Failure to call this method before destruction will cause the changes to be forgotten.
  308. // If false is returned, the state of this cache (and its backing view) will be undefined.
  309. bool Flush();
  310. // Calculate the size of the cache (in number of transactions)
  311. unsigned int GetCacheSize() const;
  312. /** Amount of bitcoins coming in to a transaction
  313. Note that lightweight clients may not know anything besides the hash of previous transactions,
  314. so may not be able to calculate this.
  315. @param[in] tx transaction for which we are checking input total
  316. @return Sum of value of all inputs (scriptSigs)
  317. */
  318. int64_t GetValueIn(const CTransaction& tx) const;
  319. // Check whether all prevouts of the transaction are present in the UTXO set represented by this view
  320. bool HaveInputs(const CTransaction& tx) const;
  321. // Return priority of tx at height nHeight
  322. double GetPriority(const CTransaction &tx, int nHeight) const;
  323. const CTxOut &GetOutputFor(const CTxIn& input) const;
  324. private:
  325. CCoinsMap::iterator FetchCoins(const uint256 &txid);
  326. CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
  327. };
  328. #endif