Merge pull request #6372
[bitcoinplatinum.git] / src / coins.cpp
bloba41d5a310d6b9cb9b9e0537c2b2c3a4f96fbd866
1 // Copyright (c) 2012-2014 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.
5 #include "coins.h"
7 #include "memusage.h"
8 #include "random.h"
10 #include <assert.h>
12 /**
13 * calculate number of bytes for the bitmask, and its number of non-zero bytes
14 * each bit in the bitmask represents the availability of one output, but the
15 * availabilities of the first two outputs are encoded separately
17 void CCoins::CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
18 unsigned int nLastUsedByte = 0;
19 for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
20 bool fZero = true;
21 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
22 if (!vout[2+b*8+i].IsNull()) {
23 fZero = false;
24 continue;
27 if (!fZero) {
28 nLastUsedByte = b + 1;
29 nNonzeroBytes++;
32 nBytes += nLastUsedByte;
35 bool CCoins::Spend(uint32_t nPos)
37 if (nPos >= vout.size() || vout[nPos].IsNull())
38 return false;
39 vout[nPos].SetNull();
40 Cleanup();
41 return true;
44 bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }
45 bool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }
46 uint256 CCoinsView::GetBestBlock() const { return uint256(); }
47 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
48 bool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }
51 CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
52 bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }
53 bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }
54 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
55 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
56 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
57 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }
59 CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
61 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) { }
63 CCoinsViewCache::~CCoinsViewCache()
65 assert(!hasModifier);
68 size_t CCoinsViewCache::DynamicMemoryUsage() const {
69 return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
72 CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {
73 CCoinsMap::iterator it = cacheCoins.find(txid);
74 if (it != cacheCoins.end())
75 return it;
76 CCoins tmp;
77 if (!base->GetCoins(txid, tmp))
78 return cacheCoins.end();
79 CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
80 tmp.swap(ret->second.coins);
81 if (ret->second.coins.IsPruned()) {
82 // The parent only has an empty entry for this txid; we can consider our
83 // version as fresh.
84 ret->second.flags = CCoinsCacheEntry::FRESH;
86 cachedCoinsUsage += memusage::DynamicUsage(ret->second.coins);
87 return ret;
90 bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
91 CCoinsMap::const_iterator it = FetchCoins(txid);
92 if (it != cacheCoins.end()) {
93 coins = it->second.coins;
94 return true;
96 return false;
99 CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
100 assert(!hasModifier);
101 std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
102 size_t cachedCoinUsage = 0;
103 if (ret.second) {
104 if (!base->GetCoins(txid, ret.first->second.coins)) {
105 // The parent view does not have this entry; mark it as fresh.
106 ret.first->second.coins.Clear();
107 ret.first->second.flags = CCoinsCacheEntry::FRESH;
108 } else if (ret.first->second.coins.IsPruned()) {
109 // The parent view only has a pruned entry for this; mark it as fresh.
110 ret.first->second.flags = CCoinsCacheEntry::FRESH;
112 } else {
113 cachedCoinUsage = memusage::DynamicUsage(ret.first->second.coins);
115 // Assume that whenever ModifyCoins is called, the entry will be modified.
116 ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
117 return CCoinsModifier(*this, ret.first, cachedCoinUsage);
120 const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
121 CCoinsMap::const_iterator it = FetchCoins(txid);
122 if (it == cacheCoins.end()) {
123 return NULL;
124 } else {
125 return &it->second.coins;
129 bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
130 CCoinsMap::const_iterator it = FetchCoins(txid);
131 // We're using vtx.empty() instead of IsPruned here for performance reasons,
132 // as we only care about the case where a transaction was replaced entirely
133 // in a reorganization (which wipes vout entirely, as opposed to spending
134 // which just cleans individual outputs).
135 return (it != cacheCoins.end() && !it->second.coins.vout.empty());
138 uint256 CCoinsViewCache::GetBestBlock() const {
139 if (hashBlock.IsNull())
140 hashBlock = base->GetBestBlock();
141 return hashBlock;
144 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
145 hashBlock = hashBlockIn;
148 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
149 assert(!hasModifier);
150 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
151 if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
152 CCoinsMap::iterator itUs = cacheCoins.find(it->first);
153 if (itUs == cacheCoins.end()) {
154 if (!it->second.coins.IsPruned()) {
155 // The parent cache does not have an entry, while the child
156 // cache does have (a non-pruned) one. Move the data up, and
157 // mark it as fresh (if the grandparent did have it, we
158 // would have pulled it in at first GetCoins).
159 assert(it->second.flags & CCoinsCacheEntry::FRESH);
160 CCoinsCacheEntry& entry = cacheCoins[it->first];
161 entry.coins.swap(it->second.coins);
162 cachedCoinsUsage += memusage::DynamicUsage(entry.coins);
163 entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;
165 } else {
166 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
167 // The grandparent does not have an entry, and the child is
168 // modified and being pruned. This means we can just delete
169 // it from the parent.
170 cachedCoinsUsage -= memusage::DynamicUsage(itUs->second.coins);
171 cacheCoins.erase(itUs);
172 } else {
173 // A normal modification.
174 cachedCoinsUsage -= memusage::DynamicUsage(itUs->second.coins);
175 itUs->second.coins.swap(it->second.coins);
176 cachedCoinsUsage += memusage::DynamicUsage(itUs->second.coins);
177 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
181 CCoinsMap::iterator itOld = it++;
182 mapCoins.erase(itOld);
184 hashBlock = hashBlockIn;
185 return true;
188 bool CCoinsViewCache::Flush() {
189 bool fOk = base->BatchWrite(cacheCoins, hashBlock);
190 cacheCoins.clear();
191 cachedCoinsUsage = 0;
192 return fOk;
195 unsigned int CCoinsViewCache::GetCacheSize() const {
196 return cacheCoins.size();
199 const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
201 const CCoins* coins = AccessCoins(input.prevout.hash);
202 assert(coins && coins->IsAvailable(input.prevout.n));
203 return coins->vout[input.prevout.n];
206 CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
208 if (tx.IsCoinBase())
209 return 0;
211 CAmount nResult = 0;
212 for (unsigned int i = 0; i < tx.vin.size(); i++)
213 nResult += GetOutputFor(tx.vin[i]).nValue;
215 return nResult;
218 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
220 if (!tx.IsCoinBase()) {
221 for (unsigned int i = 0; i < tx.vin.size(); i++) {
222 const COutPoint &prevout = tx.vin[i].prevout;
223 const CCoins* coins = AccessCoins(prevout.hash);
224 if (!coins || !coins->IsAvailable(prevout.n)) {
225 return false;
229 return true;
232 double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const
234 if (tx.IsCoinBase())
235 return 0.0;
236 double dResult = 0.0;
237 BOOST_FOREACH(const CTxIn& txin, tx.vin)
239 const CCoins* coins = AccessCoins(txin.prevout.hash);
240 assert(coins);
241 if (!coins->IsAvailable(txin.prevout.n)) continue;
242 if (coins->nHeight < nHeight) {
243 dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
246 return tx.ComputePriority(dResult);
249 CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
250 assert(!cache.hasModifier);
251 cache.hasModifier = true;
254 CCoinsModifier::~CCoinsModifier()
256 assert(cache.hasModifier);
257 cache.hasModifier = false;
258 it->second.coins.Cleanup();
259 cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
260 if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
261 cache.cacheCoins.erase(it);
262 } else {
263 // If the coin still exists after the modification, add the new usage
264 cache.cachedCoinsUsage += memusage::DynamicUsage(it->second.coins);