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.
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++) {
21 for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
22 if (!vout[2+b*8+i].IsNull()) {
28 nLastUsedByte = b + 1;
32 nBytes += nLastUsedByte;
35 bool CCoins::Spend(uint32_t nPos)
37 if (nPos >= vout.size() || vout[nPos].IsNull())
43 bool CCoinsView::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const { return false; }
44 bool CCoinsView::GetNullifier(const uint256 &nullifier) const { return false; }
45 bool CCoinsView::GetCoins(const uint256 &txid, CCoins &coins) const { return false; }
46 bool CCoinsView::HaveCoins(const uint256 &txid) const { return false; }
47 uint256 CCoinsView::GetBestBlock() const { return uint256(); }
48 uint256 CCoinsView::GetBestAnchor() const { return uint256(); };
49 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins,
50 const uint256 &hashBlock,
51 const uint256 &hashAnchor,
52 CAnchorsMap &mapAnchors,
53 CNullifiersMap &mapNullifiers) { return false; }
54 bool CCoinsView::GetStats(CCoinsStats &stats) const { return false; }
57 CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
59 bool CCoinsViewBacked::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const { return base->GetAnchorAt(rt, tree); }
60 bool CCoinsViewBacked::GetNullifier(const uint256 &nullifier) const { return base->GetNullifier(nullifier); }
61 bool CCoinsViewBacked::GetCoins(const uint256 &txid, CCoins &coins) const { return base->GetCoins(txid, coins); }
62 bool CCoinsViewBacked::HaveCoins(const uint256 &txid) const { return base->HaveCoins(txid); }
63 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
64 uint256 CCoinsViewBacked::GetBestAnchor() const { return base->GetBestAnchor(); }
65 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
66 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins,
67 const uint256 &hashBlock,
68 const uint256 &hashAnchor,
69 CAnchorsMap &mapAnchors,
70 CNullifiersMap &mapNullifiers) { return base->BatchWrite(mapCoins, hashBlock, hashAnchor, mapAnchors, mapNullifiers); }
71 bool CCoinsViewBacked::GetStats(CCoinsStats &stats) const { return base->GetStats(stats); }
73 CCoinsKeyHasher::CCoinsKeyHasher() : salt(GetRandHash()) {}
75 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), hasModifier(false), cachedCoinsUsage(0) { }
77 CCoinsViewCache::~CCoinsViewCache()
82 size_t CCoinsViewCache::DynamicMemoryUsage() const {
83 return memusage::DynamicUsage(cacheCoins) +
84 memusage::DynamicUsage(cacheAnchors) +
85 memusage::DynamicUsage(cacheNullifiers) +
89 CCoinsMap::const_iterator CCoinsViewCache::FetchCoins(const uint256 &txid) const {
90 CCoinsMap::iterator it = cacheCoins.find(txid);
91 if (it != cacheCoins.end())
94 if (!base->GetCoins(txid, tmp))
95 return cacheCoins.end();
96 CCoinsMap::iterator ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry())).first;
97 tmp.swap(ret->second.coins);
98 if (ret->second.coins.IsPruned()) {
99 // The parent only has an empty entry for this txid; we can consider our
101 ret->second.flags = CCoinsCacheEntry::FRESH;
103 cachedCoinsUsage += memusage::DynamicUsage(ret->second.coins);
108 bool CCoinsViewCache::GetAnchorAt(const uint256 &rt, ZCIncrementalMerkleTree &tree) const {
109 CAnchorsMap::const_iterator it = cacheAnchors.find(rt);
110 if (it != cacheAnchors.end()) {
111 if (it->second.entered) {
112 tree = it->second.tree;
119 if (!base->GetAnchorAt(rt, tree)) {
123 CAnchorsMap::iterator ret = cacheAnchors.insert(std::make_pair(rt, CAnchorsCacheEntry())).first;
124 ret->second.entered = true;
125 ret->second.tree = tree;
126 cachedCoinsUsage += memusage::DynamicUsage(ret->second.tree);
131 bool CCoinsViewCache::GetNullifier(const uint256 &nullifier) const {
132 CNullifiersMap::iterator it = cacheNullifiers.find(nullifier);
133 if (it != cacheNullifiers.end())
134 return it->second.entered;
136 CNullifiersCacheEntry entry;
137 bool tmp = base->GetNullifier(nullifier);
140 cacheNullifiers.insert(std::make_pair(nullifier, entry));
145 void CCoinsViewCache::PushAnchor(const ZCIncrementalMerkleTree &tree) {
146 uint256 newrt = tree.root();
148 auto currentRoot = GetBestAnchor();
150 // We don't want to overwrite an anchor we already have.
151 // This occurs when a block doesn't modify mapAnchors at all,
152 // because there are no joinsplits. We could get around this a
153 // different way (make all blocks modify mapAnchors somehow)
154 // but this is simpler to reason about.
155 if (currentRoot != newrt) {
156 auto insertRet = cacheAnchors.insert(std::make_pair(newrt, CAnchorsCacheEntry()));
157 CAnchorsMap::iterator ret = insertRet.first;
159 ret->second.entered = true;
160 ret->second.tree = tree;
161 ret->second.flags = CAnchorsCacheEntry::DIRTY;
163 if (insertRet.second) {
164 // An insert took place
165 cachedCoinsUsage += memusage::DynamicUsage(ret->second.tree);
172 void CCoinsViewCache::PopAnchor(const uint256 &newrt) {
173 auto currentRoot = GetBestAnchor();
175 // Blocks might not change the commitment tree, in which
176 // case restoring the "old" anchor during a reorg must
178 if (currentRoot != newrt) {
179 CAnchorsMap::iterator ret = cacheAnchors.insert(std::make_pair(currentRoot, CAnchorsCacheEntry())).first;
181 ret->second.entered = false;
182 ret->second.flags = CAnchorsCacheEntry::DIRTY;
188 void CCoinsViewCache::SetNullifier(const uint256 &nullifier, bool spent) {
189 std::pair<CNullifiersMap::iterator, bool> ret = cacheNullifiers.insert(std::make_pair(nullifier, CNullifiersCacheEntry()));
190 ret.first->second.entered = spent;
191 ret.first->second.flags |= CNullifiersCacheEntry::DIRTY;
194 bool CCoinsViewCache::GetCoins(const uint256 &txid, CCoins &coins) const {
195 CCoinsMap::const_iterator it = FetchCoins(txid);
196 if (it != cacheCoins.end()) {
197 coins = it->second.coins;
203 CCoinsModifier CCoinsViewCache::ModifyCoins(const uint256 &txid) {
204 assert(!hasModifier);
205 std::pair<CCoinsMap::iterator, bool> ret = cacheCoins.insert(std::make_pair(txid, CCoinsCacheEntry()));
206 size_t cachedCoinUsage = 0;
208 if (!base->GetCoins(txid, ret.first->second.coins)) {
209 // The parent view does not have this entry; mark it as fresh.
210 ret.first->second.coins.Clear();
211 ret.first->second.flags = CCoinsCacheEntry::FRESH;
212 } else if (ret.first->second.coins.IsPruned()) {
213 // The parent view only has a pruned entry for this; mark it as fresh.
214 ret.first->second.flags = CCoinsCacheEntry::FRESH;
217 cachedCoinUsage = memusage::DynamicUsage(ret.first->second.coins);
219 // Assume that whenever ModifyCoins is called, the entry will be modified.
220 ret.first->second.flags |= CCoinsCacheEntry::DIRTY;
221 return CCoinsModifier(*this, ret.first, cachedCoinUsage);
224 const CCoins* CCoinsViewCache::AccessCoins(const uint256 &txid) const {
225 CCoinsMap::const_iterator it = FetchCoins(txid);
226 if (it == cacheCoins.end()) {
229 return &it->second.coins;
233 bool CCoinsViewCache::HaveCoins(const uint256 &txid) const {
234 CCoinsMap::const_iterator it = FetchCoins(txid);
235 // We're using vtx.empty() instead of IsPruned here for performance reasons,
236 // as we only care about the case where a transaction was replaced entirely
237 // in a reorganization (which wipes vout entirely, as opposed to spending
238 // which just cleans individual outputs).
239 return (it != cacheCoins.end() && !it->second.coins.vout.empty());
242 uint256 CCoinsViewCache::GetBestBlock() const {
243 if (hashBlock.IsNull())
244 hashBlock = base->GetBestBlock();
249 uint256 CCoinsViewCache::GetBestAnchor() const {
250 if (hashAnchor.IsNull())
251 hashAnchor = base->GetBestAnchor();
255 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
256 hashBlock = hashBlockIn;
259 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins,
260 const uint256 &hashBlockIn,
261 const uint256 &hashAnchorIn,
262 CAnchorsMap &mapAnchors,
263 CNullifiersMap &mapNullifiers) {
264 assert(!hasModifier);
265 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
266 if (it->second.flags & CCoinsCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
267 CCoinsMap::iterator itUs = cacheCoins.find(it->first);
268 if (itUs == cacheCoins.end()) {
269 if (!it->second.coins.IsPruned()) {
270 // The parent cache does not have an entry, while the child
271 // cache does have (a non-pruned) one. Move the data up, and
272 // mark it as fresh (if the grandparent did have it, we
273 // would have pulled it in at first GetCoins).
274 assert(it->second.flags & CCoinsCacheEntry::FRESH);
275 CCoinsCacheEntry& entry = cacheCoins[it->first];
276 entry.coins.swap(it->second.coins);
277 cachedCoinsUsage += memusage::DynamicUsage(entry.coins);
278 entry.flags = CCoinsCacheEntry::DIRTY | CCoinsCacheEntry::FRESH;
281 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
282 // The grandparent does not have an entry, and the child is
283 // modified and being pruned. This means we can just delete
284 // it from the parent.
285 cachedCoinsUsage -= memusage::DynamicUsage(itUs->second.coins);
286 cacheCoins.erase(itUs);
288 // A normal modification.
289 cachedCoinsUsage -= memusage::DynamicUsage(itUs->second.coins);
290 itUs->second.coins.swap(it->second.coins);
291 cachedCoinsUsage += memusage::DynamicUsage(itUs->second.coins);
292 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
296 CCoinsMap::iterator itOld = it++;
297 mapCoins.erase(itOld);
300 for (CAnchorsMap::iterator child_it = mapAnchors.begin(); child_it != mapAnchors.end();)
302 if (child_it->second.flags & CAnchorsCacheEntry::DIRTY) {
303 CAnchorsMap::iterator parent_it = cacheAnchors.find(child_it->first);
305 if (parent_it == cacheAnchors.end()) {
306 if (child_it->second.entered) {
307 // Parent doesn't have an entry, but child has a new commitment root.
309 CAnchorsCacheEntry& entry = cacheAnchors[child_it->first];
310 entry.entered = true;
311 entry.tree = child_it->second.tree;
312 entry.flags = CAnchorsCacheEntry::DIRTY;
314 cachedCoinsUsage += memusage::DynamicUsage(entry.tree);
317 if (parent_it->second.entered != child_it->second.entered) {
318 // The parent may have removed the entry.
319 parent_it->second.entered = child_it->second.entered;
320 parent_it->second.flags |= CAnchorsCacheEntry::DIRTY;
325 CAnchorsMap::iterator itOld = child_it++;
326 mapAnchors.erase(itOld);
329 for (CNullifiersMap::iterator child_it = mapNullifiers.begin(); child_it != mapNullifiers.end();)
331 if (child_it->second.flags & CNullifiersCacheEntry::DIRTY) { // Ignore non-dirty entries (optimization).
332 CNullifiersMap::iterator parent_it = cacheNullifiers.find(child_it->first);
334 if (parent_it == cacheNullifiers.end()) {
335 if (child_it->second.entered) {
336 // Parent doesn't have an entry, but child has a SPENT nullifier.
337 // Move the spent nullifier up.
339 CNullifiersCacheEntry& entry = cacheNullifiers[child_it->first];
340 entry.entered = true;
341 entry.flags = CNullifiersCacheEntry::DIRTY;
344 if (parent_it->second.entered != child_it->second.entered) {
345 parent_it->second.entered = child_it->second.entered;
346 parent_it->second.flags |= CNullifiersCacheEntry::DIRTY;
350 CNullifiersMap::iterator itOld = child_it++;
351 mapNullifiers.erase(itOld);
354 hashAnchor = hashAnchorIn;
355 hashBlock = hashBlockIn;
359 bool CCoinsViewCache::Flush() {
360 bool fOk = base->BatchWrite(cacheCoins, hashBlock, hashAnchor, cacheAnchors, cacheNullifiers);
362 cacheAnchors.clear();
363 cacheNullifiers.clear();
364 cachedCoinsUsage = 0;
368 unsigned int CCoinsViewCache::GetCacheSize() const {
369 return cacheCoins.size();
372 const CTxOut &CCoinsViewCache::GetOutputFor(const CTxIn& input) const
374 const CCoins* coins = AccessCoins(input.prevout.hash);
375 assert(coins && coins->IsAvailable(input.prevout.n));
376 return coins->vout[input.prevout.n];
379 const CScript &CCoinsViewCache::GetSpendFor(const CTxIn& input) const
381 const CCoins* coins = AccessCoins(input.prevout.hash);
383 return coins->vout[input.prevout.n].scriptPubKey;
386 uint64_t komodo_interest(int32_t txheight,uint64_t nValue,uint32_t nLockTime,uint32_t tiptime);
388 CAmount CCoinsViewCache::GetValueIn(int32_t nHeight,int64_t *interestp,const CTransaction& tx,uint32_t tiptime) const
390 uint32_t timestamp,minutes; int64_t interest;
392 if ( tx.IsCoinBase() != 0 )
394 CAmount value,nResult = 0;
395 for (unsigned int i = 0; i < tx.vin.size(); i++)
397 value = GetOutputFor(tx.vin[i]).nValue;
399 interest = komodo_interest(nHeight,value,tx.nLockTime,tiptime);
400 #ifdef KOMODO_ENABLE_INTEREST
403 (*interestp) += interest;
405 nResult += tx.GetJoinSplitValueIn();
410 bool CCoinsViewCache::HaveJoinSplitRequirements(const CTransaction& tx) const
412 boost::unordered_map<uint256, ZCIncrementalMerkleTree, CCoinsKeyHasher> intermediates;
414 BOOST_FOREACH(const JSDescription &joinsplit, tx.vjoinsplit)
416 BOOST_FOREACH(const uint256& nullifier, joinsplit.nullifiers)
418 if (GetNullifier(nullifier)) {
419 // If the nullifier is set, this transaction
425 ZCIncrementalMerkleTree tree;
426 auto it = intermediates.find(joinsplit.anchor);
427 if (it != intermediates.end()) {
429 } else if (!GetAnchorAt(joinsplit.anchor, tree)) {
433 BOOST_FOREACH(const uint256& commitment, joinsplit.commitments)
435 tree.append(commitment);
438 intermediates.insert(std::make_pair(tree.root(), tree));
444 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
446 if (!tx.IsCoinBase()) {
447 for (unsigned int i = 0; i < tx.vin.size(); i++) {
448 const COutPoint &prevout = tx.vin[i].prevout;
449 const CCoins* coins = AccessCoins(prevout.hash);
450 if (!coins || !coins->IsAvailable(prevout.n)) {
458 double CCoinsViewCache::GetPriority(const CTransaction &tx, int nHeight) const
462 double dResult = 0.0;
463 BOOST_FOREACH(const CTxIn& txin, tx.vin)
465 const CCoins* coins = AccessCoins(txin.prevout.hash);
467 if (!coins->IsAvailable(txin.prevout.n)) continue;
468 if (coins->nHeight < nHeight) {
469 dResult += coins->vout[txin.prevout.n].nValue * (nHeight-coins->nHeight);
472 return tx.ComputePriority(dResult);
475 CCoinsModifier::CCoinsModifier(CCoinsViewCache& cache_, CCoinsMap::iterator it_, size_t usage) : cache(cache_), it(it_), cachedCoinUsage(usage) {
476 assert(!cache.hasModifier);
477 cache.hasModifier = true;
480 CCoinsModifier::~CCoinsModifier()
482 assert(cache.hasModifier);
483 cache.hasModifier = false;
484 it->second.coins.Cleanup();
485 cache.cachedCoinsUsage -= cachedCoinUsage; // Subtract the old usage
486 if ((it->second.flags & CCoinsCacheEntry::FRESH) && it->second.coins.IsPruned()) {
487 cache.cacheCoins.erase(it);
489 // If the coin still exists after the modification, add the new usage
490 cache.cachedCoinsUsage += memusage::DynamicUsage(it->second.coins);