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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2015 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.
  5. #ifndef BITCOIN_COINS_H
  6. #define BITCOIN_COINS_H
  7. #include "compressor.h"
  8. #include "core_memusage.h"
  9. #include "memusage.h"
  10. #include "serialize.h"
  11. #include "uint256.h"
  12. #include <assert.h>
  13. #include <stdint.h>
  14. #include <boost/foreach.hpp>
  15. #include <boost/unordered_map.hpp>
  16. /**
  17. * Pruned version of CTransaction: only retains metadata and unspent transaction outputs
  18. *
  19. * Serialized format:
  20. * - VARINT(nVersion)
  21. * - VARINT(nCode)
  22. * - unspentness bitvector, for vout[2] and further; least significant byte first
  23. * - the non-spent CTxOuts (via CTxOutCompressor)
  24. * - VARINT(nHeight)
  25. *
  26. * The nCode value consists of:
  27. * - bit 0: IsCoinBase()
  28. * - bit 1: vout[0] is not spent
  29. * - bit 2: vout[1] is not spent
  30. * - The higher bits encode N, the number of non-zero bytes in the following bitvector.
  31. * - In case both bit 1 and bit 2 are unset, they encode N-1, as there must be at
  32. * least one non-spent output).
  33. *
  34. * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
  35. * <><><--------------------------------------------><---->
  36. * | \ | /
  37. * version code vout[1] height
  38. *
  39. * - version = 1
  40. * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
  41. * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
  42. * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
  43. * * 8358: compact amount representation for 60000000000 (600 BTC)
  44. * * 00: special txout type pay-to-pubkey-hash
  45. * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
  46. * - height = 203998
  47. *
  48. *
  49. * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
  50. * <><><--><--------------------------------------------------><----------------------------------------------><---->
  51. * / \ \ | | /
  52. * version code unspentness vout[4] vout[16] height
  53. *
  54. * - version = 1
  55. * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
  56. * 2 (1, +1 because both bit 1 and bit 2 are unset) non-zero bitvector bytes follow)
  57. * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
  58. * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
  59. * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
  60. * * 00: special txout type pay-to-pubkey-hash
  61. * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
  62. * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
  63. * * bbd123: compact amount representation for 110397 (0.001 BTC)
  64. * * 00: special txout type pay-to-pubkey-hash
  65. * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
  66. * - height = 120891
  67. */
  68. class CCoins
  69. {
  70. public:
  71. //! whether transaction is a coinbase
  72. bool fCoinBase;
  73. //! unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
  74. std::vector<CTxOut> vout;
  75. //! at which height this transaction was included in the active block chain
  76. int nHeight;
  77. //! version of the CTransaction; accesses to this value should probably check for nHeight as well,
  78. //! as new tx version will probably only be introduced at certain heights
  79. int nVersion;
  80. void FromTx(const CTransaction &tx, int nHeightIn) {
  81. fCoinBase = tx.IsCoinBase();
  82. vout = tx.vout;
  83. nHeight = nHeightIn;
  84. nVersion = tx.nVersion;
  85. ClearUnspendable();
  86. }
  87. //! construct a CCoins from a CTransaction, at a given height
  88. CCoins(const CTransaction &tx, int nHeightIn) {
  89. FromTx(tx, nHeightIn);
  90. }
  91. void Clear() {
  92. fCoinBase = false;
  93. std::vector<CTxOut>().swap(vout);
  94. nHeight = 0;
  95. nVersion = 0;
  96. }
  97. //! empty constructor
  98. CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
  99. //!remove spent outputs at the end of vout
  100. void Cleanup() {
  101. while (vout.size() > 0 && vout.back().IsNull())
  102. vout.pop_back();
  103. if (vout.empty())
  104. std::vector<CTxOut>().swap(vout);
  105. }
  106. void ClearUnspendable() {
  107. BOOST_FOREACH(CTxOut &txout, vout) {
  108. if (txout.scriptPubKey.IsUnspendable())
  109. txout.SetNull();
  110. }
  111. Cleanup();
  112. }
  113. void swap(CCoins &to) {
  114. std::swap(to.fCoinBase, fCoinBase);
  115. to.vout.swap(vout);
  116. std::swap(to.nHeight, nHeight);
  117. std::swap(to.nVersion, nVersion);
  118. }
  119. //! equality test
  120. friend bool operator==(const CCoins &a, const CCoins &b) {
  121. // Empty CCoins objects are always equal.
  122. if (a.IsPruned() && b.IsPruned())
  123. return true;
  124. return a.fCoinBase == b.fCoinBase &&
  125. a.nHeight == b.nHeight &&
  126. a.nVersion == b.nVersion &&
  127. a.vout == b.vout;
  128. }
  129. friend bool operator!=(const CCoins &a, const CCoins &b) {
  130. return !(a == b);
  131. }
  132. void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const;
  133. bool IsCoinBase() const {
  134. return fCoinBase;
  135. }
  136. unsigned int GetSerializeSize(int nType, int nVersion) const {
  137. unsigned int nSize = 0;
  138. unsigned int nMaskSize = 0, nMaskCode = 0;
  139. CalcMaskSize(nMaskSize, nMaskCode);
  140. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  141. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  142. assert(fFirst || fSecond || nMaskCode);
  143. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  144. // version
  145. nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
  146. // size of header code
  147. nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
  148. // spentness bitmask
  149. nSize += nMaskSize;
  150. // txouts themself
  151. for (unsigned int i = 0; i < vout.size(); i++)
  152. if (!vout[i].IsNull())
  153. nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
  154. // height
  155. nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
  156. return nSize;
  157. }
  158. template<typename Stream>
  159. void Serialize(Stream &s, int nType, int nVersion) const {
  160. unsigned int nMaskSize = 0, nMaskCode = 0;
  161. CalcMaskSize(nMaskSize, nMaskCode);
  162. bool fFirst = vout.size() > 0 && !vout[0].IsNull();
  163. bool fSecond = vout.size() > 1 && !vout[1].IsNull();
  164. assert(fFirst || fSecond || nMaskCode);
  165. unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
  166. // version
  167. ::Serialize(s, VARINT(this->nVersion), nType, nVersion);
  168. // header code
  169. ::Serialize(s, VARINT(nCode), nType, nVersion);
  170. // spentness bitmask
  171. for (unsigned int b = 0; b<nMaskSize; b++) {
  172. unsigned char chAvail = 0;
  173. for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
  174. if (!vout[2+b*8+i].IsNull())
  175. chAvail |= (1 << i);
  176. ::Serialize(s, chAvail, nType, nVersion);
  177. }
  178. // txouts themself
  179. for (unsigned int i = 0; i < vout.size(); i++) {
  180. if (!vout[i].IsNull())
  181. ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
  182. }
  183. // coinbase height
  184. ::Serialize(s, VARINT(nHeight), nType, nVersion);
  185. }
  186. template<typename Stream>
  187. void Unserialize(Stream &s, int nType, int nVersion) {
  188. unsigned int nCode = 0;
  189. // version
  190. ::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
  191. // header code
  192. ::Unserialize(s, VARINT(nCode), nType, nVersion);
  193. fCoinBase = nCode & 1;
  194. std::vector<bool> vAvail(2, false);
  195. vAvail[0] = (nCode & 2) != 0;
  196. vAvail[1] = (nCode & 4) != 0;
  197. unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
  198. // spentness bitmask
  199. while (nMaskCode > 0) {
  200. unsigned char chAvail = 0;
  201. ::Unserialize(s, chAvail, nType, nVersion);
  202. for (unsigned int p = 0; p < 8; p++) {
  203. bool f = (chAvail & (1 << p)) != 0;
  204. vAvail.push_back(f);
  205. }
  206. if (chAvail != 0)
  207. nMaskCode--;
  208. }
  209. // txouts themself
  210. vout.assign(vAvail.size(), CTxOut());
  211. for (unsigned int i = 0; i < vAvail.size(); i++) {
  212. if (vAvail[i])
  213. ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
  214. }
  215. // coinbase height
  216. ::Unserialize(s, VARINT(nHeight), nType, nVersion);
  217. Cleanup();
  218. }
  219. //! mark a vout spent
  220. bool Spend(uint32_t nPos);
  221. //! check whether a particular output is still available
  222. bool IsAvailable(unsigned int nPos) const {
  223. return (nPos < vout.size() && !vout[nPos].IsNull());
  224. }
  225. //! check whether the entire CCoins is spent
  226. //! note that only !IsPruned() CCoins can be serialized
  227. bool IsPruned() const {
  228. BOOST_FOREACH(const CTxOut &out, vout)
  229. if (!out.IsNull())
  230. return false;
  231. return true;
  232. }
  233. size_t DynamicMemoryUsage() const {
  234. size_t ret = memusage::DynamicUsage(vout);
  235. BOOST_FOREACH(const CTxOut &out, vout) {
  236. ret += RecursiveDynamicUsage(out.scriptPubKey);
  237. }
  238. return ret;
  239. }
  240. };
  241. class CCoinsKeyHasher
  242. {
  243. private:
  244. uint256 salt;
  245. public:
  246. CCoinsKeyHasher();
  247. /**
  248. * This *must* return size_t. With Boost 1.46 on 32-bit systems the
  249. * unordered_map will behave unpredictably if the custom hasher returns a
  250. * uint64_t, resulting in failures when syncing the chain (#4634).
  251. */
  252. size_t operator()(const uint256& key) const {
  253. return key.GetHash(salt);
  254. }
  255. };
  256. struct CCoinsCacheEntry
  257. {
  258. CCoins coins; // The actual cached data.
  259. unsigned char flags;
  260. enum Flags {
  261. DIRTY = (1 << 0), // This cache entry is potentially different from the version in the parent view.
  262. FRESH = (1 << 1), // The parent view does not have this entry (or it is pruned).
  263. };
  264. CCoinsCacheEntry() : coins(), flags(0) {}
  265. };
  266. typedef boost::unordered_map<uint256, CCoinsCacheEntry, CCoinsKeyHasher> CCoinsMap;
  267. struct CCoinsStats
  268. {
  269. int nHeight;
  270. uint256 hashBlock;
  271. uint64_t nTransactions;
  272. uint64_t nTransactionOutputs;
  273. uint64_t nSerializedSize;
  274. uint256 hashSerialized;
  275. CAmount nTotalAmount;
  276. CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), nTotalAmount(0) {}
  277. };
  278. /** Abstract view on the open txout dataset. */
  279. class CCoinsView
  280. {
  281. public:
  282. //! Retrieve the CCoins (unspent transaction outputs) for a given txid
  283. virtual bool GetCoins(const uint256 &txid, CCoins &coins) const;
  284. //! Just check whether we have data for a given txid.
  285. //! This may (but cannot always) return true for fully spent transactions
  286. virtual bool HaveCoins(const uint256 &txid) const;
  287. //! Retrieve the block hash whose state this CCoinsView currently represents
  288. virtual uint256 GetBestBlock() const;
  289. //! Do a bulk modification (multiple CCoins changes + BestBlock change).
  290. //! The passed mapCoins can be modified.
  291. virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  292. //! Calculate statistics about the unspent transaction output set
  293. virtual bool GetStats(CCoinsStats &stats) const;
  294. //! As we use CCoinsViews polymorphically, have a virtual destructor
  295. virtual ~CCoinsView() {}
  296. };
  297. /** CCoinsView backed by another CCoinsView */
  298. class CCoinsViewBacked : public CCoinsView
  299. {
  300. protected:
  301. CCoinsView *base;
  302. public:
  303. CCoinsViewBacked(CCoinsView *viewIn);
  304. bool GetCoins(const uint256 &txid, CCoins &coins) const;
  305. bool HaveCoins(const uint256 &txid) const;
  306. uint256 GetBestBlock() const;
  307. void SetBackend(CCoinsView &viewIn);
  308. bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  309. bool GetStats(CCoinsStats &stats) const;
  310. };
  311. class CCoinsViewCache;
  312. /**
  313. * A reference to a mutable cache entry. Encapsulating it allows us to run
  314. * cleanup code after the modification is finished, and keeping track of
  315. * concurrent modifications.
  316. */
  317. class CCoinsModifier
  318. {
  319. private:
  320. CCoinsViewCache& cache;
  321. CCoinsMap::iterator it;
  322. size_t cachedCoinUsage; // Cached memory usage of the CCoins object before modification
  323. CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage);
  324. public:
  325. CCoins* operator->() { return &it->second.coins; }
  326. CCoins& operator*() { return it->second.coins; }
  327. ~CCoinsModifier();
  328. friend class CCoinsViewCache;
  329. };
  330. /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
  331. class CCoinsViewCache : public CCoinsViewBacked
  332. {
  333. protected:
  334. /* Whether this cache has an active modifier. */
  335. bool hasModifier;
  336. /**
  337. * Make mutable so that we can "fill the cache" even from Get-methods
  338. * declared as "const".
  339. */
  340. mutable uint256 hashBlock;
  341. mutable CCoinsMap cacheCoins;
  342. /* Cached dynamic memory usage for the inner CCoins objects. */
  343. mutable size_t cachedCoinsUsage;
  344. public:
  345. CCoinsViewCache(CCoinsView *baseIn);
  346. ~CCoinsViewCache();
  347. // Standard CCoinsView methods
  348. bool GetCoins(const uint256 &txid, CCoins &coins) const;
  349. bool HaveCoins(const uint256 &txid) const;
  350. uint256 GetBestBlock() const;
  351. void SetBestBlock(const uint256 &hashBlock);
  352. bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
  353. /**
  354. * Check if we have the given tx already loaded in this cache.
  355. * The semantics are the same as HaveCoins(), but no calls to
  356. * the backing CCoinsView are made.
  357. */
  358. bool HaveCoinsInCache(const uint256 &txid) const;
  359. /**
  360. * Return a pointer to CCoins in the cache, or NULL if not found. This is
  361. * more efficient than GetCoins. Modifications to other cache entries are
  362. * allowed while accessing the returned pointer.
  363. */
  364. const CCoins* AccessCoins(const uint256 &txid) const;
  365. /**
  366. * Return a modifiable reference to a CCoins. If no entry with the given
  367. * txid exists, a new one is created. Simultaneous modifications are not
  368. * allowed.
  369. */
  370. CCoinsModifier ModifyCoins(const uint256 &txid);
  371. /**
  372. * Return a modifiable reference to a CCoins. Assumes that no entry with the given
  373. * txid exists and creates a new one. This saves a database access in the case where
  374. * the coins were to be wiped out by FromTx anyway. This should not be called with
  375. * the 2 historical coinbase duplicate pairs because the new coins are marked fresh, and
  376. * in the event the duplicate coinbase was spent before a flush, the now pruned coins
  377. * would not properly overwrite the first coinbase of the pair. Simultaneous modifications
  378. * are not allowed.
  379. */
  380. CCoinsModifier ModifyNewCoins(const uint256 &txid);
  381. /**
  382. * Push the modifications applied to this cache to its base.
  383. * Failure to call this method before destruction will cause the changes to be forgotten.
  384. * If false is returned, the state of this cache (and its backing view) will be undefined.
  385. */
  386. bool Flush();
  387. /**
  388. * Removes the transaction with the given hash from the cache, if it is
  389. * not modified.
  390. */
  391. void Uncache(const uint256 &txid);
  392. //! Calculate the size of the cache (in number of transactions)
  393. unsigned int GetCacheSize() const;
  394. //! Calculate the size of the cache (in bytes)
  395. size_t DynamicMemoryUsage() const;
  396. /**
  397. * Amount of bitcoins coming in to a transaction
  398. * Note that lightweight clients may not know anything besides the hash of previous transactions,
  399. * so may not be able to calculate this.
  400. *
  401. * @param[in] tx transaction for which we are checking input total
  402. * @return Sum of value of all inputs (scriptSigs)
  403. */
  404. CAmount GetValueIn(const CTransaction& tx) const;
  405. //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
  406. bool HaveInputs(const CTransaction& tx) const;
  407. /**
  408. * Return priority of tx at height nHeight. Also calculate the sum of the values of the inputs
  409. * that are already in the chain. These are the inputs that will age and increase priority as
  410. * new blocks are added to the chain.
  411. */
  412. double GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const;
  413. const CTxOut &GetOutputFor(const CTxIn& input) const;
  414. friend class CCoinsModifier;
  415. private:
  416. CCoinsMap::iterator FetchCoins(const uint256 &txid);
  417. CCoinsMap::const_iterator FetchCoins(const uint256 &txid) const;
  418. /**
  419. * By making the copy constructor private, we prevent accidentally using it when one intends to create a cache on top of a base cache.
  420. */
  421. CCoinsViewCache(const CCoinsViewCache &);
  422. };
  423. #endif // BITCOIN_COINS_H