Merge pull request #6508
[bitcoinplatinum.git] / src / coins.cpp
blobf0ea5c0459067ec43a5e507b675b1da23ffc959b
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 += ret->second.coins.DynamicMemoryUsage();
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 = ret.first->second.coins.DynamicMemoryUsage();
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 CCoinsModifier CCoinsViewCache::ModifyNewCoins(const uint256 &txid) {
121 assert(!hasModifier);
122 std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
123 ret.first->second.coins.Clear();
124 ret.first->second.flags = CCoinsCacheEntry::FRESH;
125 ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
126 return CCoinsModifier(*this, ret.first, 0);
129 const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
130 CCoinsMap::const_iterator it = FetchCoins(txid);
131 if (it == cacheCoins.end()) {
132 return NULL;
133 } else {
134 return &it->second.coins;
138 bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
139 CCoinsMap::const_iterator it = FetchCoins(txid);
140 // We're using vtx.empty() instead of IsPruned here for performance reasons,
141 // as we only care about the case where a transaction was replaced entirely
142 // in a reorganization (which wipes vout entirely, as opposed to spending
143 // which just cleans individual outputs).
144 return (it != cacheCoins.end() && !it->second.coins.vout.empty());
147 uint256 CCoinsViewCache::GetBestBlock() const {
148 if (hashBlock.IsNull())
149 hashBlock = base->GetBestBlock();
150 return hashBlock;
153 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
154 hashBlock = hashBlockIn;
157 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
158 assert(!hasModifier);
159 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
160 if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
161 CCoinsMap::iterator itUs = cacheCoins.find(it->first);
162 if (itUs == cacheCoins.end()) {
163 // The parent cache does not have an entry, while the child does
164 // We can ignore it if it's both FRESH and pruned in the child
165 if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coins.IsPruned())) {
166 // Otherwise we will need to create it in the parent
167 // and move the data up and mark it as dirty
168 CCoinsCacheEntry& entry = cacheCoins[it->first];
169 entry.coins.swap(it->second.coins);
170 cachedCoinsUsage += entry.coins.DynamicMemoryUsage();
171 entry.flags = CCoinsCacheEntry::DIRTY;
172 // We can mark it FRESH in the parent if it was FRESH in the child
173 // Otherwise it might have just been flushed from the parent's cache
174 // and already exist in the grandparent
175 if (it->second.flags & CCoinsCacheEntry::FRESH)
176 entry.flags |= CCoinsCacheEntry::FRESH;
178 } else {
179 // Found the entry in the parent cache
180 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
181 // The grandparent does not have an entry, and the child is
182 // modified and being pruned. This means we can just delete
183 // it from the parent.
184 cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
185 cacheCoins.erase(itUs);
186 } else {
187 // A normal modification.
188 cachedCoinsUsage -= itUs->second.coins.DynamicMemoryUsage();
189 itUs->second.coins.swap(it->second.coins);
190 cachedCoinsUsage += itUs->second.coins.DynamicMemoryUsage();
191 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
195 CCoinsMap::iterator itOld = it++;
196 mapCoins.erase(itOld);
198 hashBlock = hashBlockIn;
199 return true;
202 bool CCoinsViewCache::Flush() {
203 bool fOk = base->BatchWrite(cacheCoins, hashBlock);
204 cacheCoins.clear();
205 cachedCoinsUsage = 0;
206 return fOk;
209 unsigned int CCoinsViewCache::GetCacheSize() const {
210 return cacheCoins.size();
213 const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
215 const CCoins* coins = AccessCoins(input.prevout.hash);
216 assert(coins && coins->IsAvailable(input.prevout.n));
217 return coins->vout[input.prevout.n];
220 CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
222 if (tx.IsCoinBase())
223 return 0;
225 CAmount nResult = 0;
226 for (unsigned int i = 0; i < tx.vin.size(); i++)
227 nResult += GetOutputFor(tx.vin[i]).nValue;
229 return nResult;
232 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
234 if (!tx.IsCoinBase()) {
235 for (unsigned int i = 0; i < tx.vin.size(); i++) {
236 const COutPoint &prevout = tx.vin[i].prevout;
237 const CCoins* coins = AccessCoins(prevout.hash);
238 if (!coins || !coins->IsAvailable(prevout.n)) {
239 return false;
243 return true;
246 double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const
248 if (tx.IsCoinBase())
249 return 0.0;
250 double dResult = 0.0;
251 BOOST_FOREACH(const CTxIn& txin, tx.vin)
253 const CCoins* coins = AccessCoins(txin.prevout.hash);
254 assert(coins);
255 if (!coins->IsAvailable(txin.prevout.n)) continue;
256 if (coins->nHeight < nHeight) {
257 dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
260 return tx.ComputePriority(dResult);
263 CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
264 assert(!cache.hasModifier);
265 cache.hasModifier = true;
268 CCoinsModifier::~CCoinsModifier()
270 assert(cache.hasModifier);
271 cache.hasModifier = false;
272 it->second.coins.Cleanup();
273 cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
274 if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
275 cache.cacheCoins.erase(it);
276 } else {
277 // If the coin still exists after the modification, add the new usage
278 cache.cachedCoinsUsage += it->second.coins.DynamicMemoryUsage();