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.cpp 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright (c) 2012-2015 The Bitcoin Core developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "coins.h"
  5. #include "memusage.h"
  6. #include "random.h"
  7. #include <assert.h>
  8. /**
  9. * calculate number of bytes for the bitmask, and its number of non-zero bytes
  10. * each bit in the bitmask represents the availability of one output, but the
  11. * availabilities of the first two outputs are encoded separately
  12. */
  13. void CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
  14. unsigned int nLastUsedByte = 0;
  15. for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
  16. bool fZero = true;
  17. for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
  18. if (!vout[2+b*8+i].IsNull()) {
  19. fZero = false;
  20. continue;
  21. }
  22. }
  23. if (!fZero) {
  24. nLastUsedByte = b + 1;
  25. nNonzeroBytes++;
  26. }
  27. }
  28. nBytes += nLastUsedByte;
  29. }
  30. bool CCoins::Spend(uint32_t nPos)
  31. {
  32. if (nPos >= vout.size() || vout[nPos].IsNull())
  33. return false;
  34. vout[nPos].SetNull();
  35. Cleanup();
  36. return true;
  37. }
  38. bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }
  39. bool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }
  40. uint256 CCoinsView::GetBestBlock() const { return uint256(); }
  41. bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
  42. bool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }
  43. CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
  44. bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }
  45. bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }
  46. uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
  47. void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
  48. bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
  49. bool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }
  50. CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
  51. CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) { }
  52. CCoinsViewCache::~CCoinsViewCache()
  53. {
  54. assert(!hasModifier);
  55. }
  56. size_t CCoinsViewCache::DynamicMemoryUsage() const {
  57. return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
  58. }
  59. CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {
  60. CCoinsMap::iterator it = cacheCoins.find(txid);
  61. if (it != cacheCoins.end())
  62. return it;
  63. CCoins tmp;
  64. if (!base->GetCoins(txid, tmp))
  65. return cacheCoins.end();
  66. CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
  67. tmp.swap(ret->second.coins);
  68. if (ret->second.coins.IsPruned()) {
  69. // The parent only has an empty entry for this txid; we can consider our
  70. // version as fresh.
  71. ret->second.flags = CCoinsCacheEntry::FRESH;
  72. }
  73. cachedCoinsUsage += ret->second.coins.DynamicMemoryUsage();
  74. return ret;
  75. }
  76. bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
  77. CCoinsMap::const_iterator it = FetchCoins(txid);
  78. if (it != cacheCoins.end()) {
  79. coins = it->second.coins;
  80. return true;
  81. }
  82. return false;
  83. }
  84. CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
  85. assert(!hasModifier);
  86. std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
  87. size_t cachedCoinUsage = 0;
  88. if (ret.second) {
  89. if (!base->GetCoins(txid, ret.first->second.coins)) {
  90. // The parent view does not have this entry; mark it as fresh.
  91. ret.first->second.coins.Clear();
  92. ret.first->second.flags = CCoinsCacheEntry::FRESH;
  93. } else if (ret.first->second.coins.IsPruned()) {
  94. // The parent view only has a pruned entry for this; mark it as fresh.
  95. ret.first->second.flags = CCoinsCacheEntry::FRESH;
  96. }
  97. } else {
  98. cachedCoinUsage = ret.first->second.coins.DynamicMemoryUsage();
  99. }
  100. // Assume that whenever ModifyCoins is called, the entry will be modified.
  101. ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
  102. return CCoinsModifier(*this, ret.first, cachedCoinUsage);
  103. }
  104. CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid) {
  105. assert(!hasModifier);
  106. std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
  107. ret.first->second.coins.Clear();
  108. ret.first->second.flags = CCoinsCacheEntry::FRESH;
  109. ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
  110. return CCoinsModifier(*this, ret.first, 0);
  111. }
  112. const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
  113. CCoinsMap::const_iterator it = FetchCoins(txid);
  114. if (it == cacheCoins.end()) {
  115. return NULL;
  116. } else {
  117. return &it->second.coins;
  118. }
  119. }
  120. bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
  121. CCoinsMap::const_iterator it = FetchCoins(txid);
  122. // We're using vtx.empty() instead of IsPruned here for performance reasons,
  123. // as we only care about the case where a transaction was replaced entirely
  124. // in a reorganization (which wipes vout entirely, as opposed to spending
  125. // which just cleans individual outputs).
  126. return (it != cacheCoins.end() && !it->second.coins.vout.empty());
  127. }
  128. bool CCoinsViewCache::HaveCoinsInCache(const uint256 &txid) const {
  129. CCoinsMap::const_iterator it = cacheCoins.find(txid);
  130. return it != cacheCoins.end();
  131. }
  132. uint256 CCoinsViewCache::GetBestBlock() const {
  133. if (hashBlock.IsNull())
  134. hashBlock = base->GetBestBlock();
  135. return hashBlock;
  136. }
  137. void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
  138. hashBlock = hashBlockIn;
  139. }
  140. bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
  141. assert(!hasModifier);
  142. for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
  143. if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
  144. CCoinsMap::iterator itUs = cacheCoins.find(it->first);
  145. if (itUs == cacheCoins.end()) {
  146. // The parent cache does not have an entry, while the child does
  147. // We can ignore it if it's both FRESH and pruned in the child
  148. if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coins.IsPruned())) {
  149. // Otherwise we will need to create it in the parent
  150. // and move the data up and mark it as dirty
  151. CCoinsCacheEntry& entry = cacheCoins[it->first];
  152. entry.coins.swap(it->second.coins);
  153. cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
  154. entry.flags = CCoinsCacheEntry::DIRTY;
  155. // We can mark it FRESH in the parent if it was FRESH in the child
  156. // Otherwise it might have just been flushed from the parent's cache
  157. // and already exist in the grandparent
  158. if (it->second.flags & CCoinsCacheEntry::FRESH)
  159. entry.flags |= CCoinsCacheEntry::FRESH;
  160. }
  161. } else {
  162. // Found the entry in the parent cache
  163. if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
  164. // The grandparent does not have an entry, and the child is
  165. // modified and being pruned. This means we can just delete
  166. // it from the parent.
  167. cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
  168. cacheCoins.erase(itUs);
  169. } else {
  170. // A normal modification.
  171. cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
  172. itUs->second.coins.swap(it->second.coins);
  173. cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
  174. itUs->second.flags |= CCoinsCacheEntry::DIRTY;
  175. }
  176. }
  177. }
  178. CCoinsMap::iterator itOld = it++;
  179. mapCoins.erase(itOld);
  180. }
  181. hashBlock = hashBlockIn;
  182. return true;
  183. }
  184. bool CCoinsViewCache::Flush() {
  185. bool fOk = base->BatchWrite(cacheCoins, hashBlock);
  186. cacheCoins.clear();
  187. cachedCoinsUsage = 0;
  188. return fOk;
  189. }
  190. void CCoinsViewCache::Uncache(const uint256& hash)
  191. {
  192. CCoinsMap::iterator it = cacheCoins.find(hash);
  193. if (it != cacheCoins.end() && it->second.flags == 0) {
  194. cachedCoinsUsage -= it->second.coins.DynamicMemoryUsage();
  195. cacheCoins.erase(it);
  196. }
  197. }
  198. unsigned int CCoinsViewCache::GetCacheSize() const {
  199. return cacheCoins.size();
  200. }
  201. const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
  202. {
  203. const CCoins* coins = AccessCoins(input.prevout.hash);
  204. assert(coins && coins->IsAvailable(input.prevout.n));
  205. return coins->vout[input.prevout.n];
  206. }
  207. CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
  208. {
  209. if (tx.IsCoinBase())
  210. return 0;
  211. CAmount nResult = 0;
  212. for (unsigned int i = 0; i < tx.vin.size(); i++)
  213. nResult += GetOutputFor(tx.vin[i]).nValue;
  214. return nResult;
  215. }
  216. bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
  217. {
  218. if (!tx.IsCoinBase()) {
  219. for (unsigned int i = 0; i < tx.vin.size(); i++) {
  220. const COutPoint &prevout = tx.vin[i].prevout;
  221. const CCoins* coins = AccessCoins(prevout.hash);
  222. if (!coins || !coins->IsAvailable(prevout.n)) {
  223. return false;
  224. }
  225. }
  226. }
  227. return true;
  228. }
  229. double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight, CAmount &inChainInputValue) const
  230. {
  231. inChainInputValue = 0;
  232. if (tx.IsCoinBase())
  233. return 0.0;
  234. double dResult = 0.0;
  235. BOOST_FOREACH(const CTxIn& txin, tx.vin)
  236. {
  237. const CCoins* coins = AccessCoins(txin.prevout.hash);
  238. assert(coins);
  239. if (!coins->IsAvailable(txin.prevout.n)) continue;
  240. if (coins->nHeight <= nHeight) {
  241. dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
  242. inChainInputValue += coins->vout[txin.prevout.n].nValue;
  243. }
  244. }
  245. return tx.ComputePriority(dResult);
  246. }
  247. CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
  248. assert(!cache.hasModifier);
  249. cache.hasModifier = true;
  250. }
  251. CCoinsModifier::~CCoinsModifier()
  252. {
  253. assert(cache.hasModifier);
  254. cache.hasModifier = false;
  255. it->second.coins.Cleanup();
  256. cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
  257. if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
  258. cache.cacheCoins.erase(it);
  259. } else {
  260. // If the coin still exists after the modification, add the new usage
  261. cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();
  262. }
  263. }