Merge #10537: Few Minor per-utxo assert-semantics re-adds and tweak
[bitcoinplatinum.git] / src / coins.cpp
blob2dceaf09b6d70e6f3b3970f19bb77c48b4b1ee23
1 // Copyright (c) 2012-2016 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 "consensus/consensus.h"
8 #include "memusage.h"
9 #include "random.h"
11 #include <assert.h>
13 bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
14 bool CCoinsView::HaveCoin(const COutPoint &outpoint) const { return false; }
15 uint256 CCoinsView::GetBestBlock() const { return uint256(); }
16 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
17 CCoinsViewCursor *CCoinsView::Cursor() const { return 0; }
20 CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
21 bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
22 bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
23 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
24 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
25 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
26 CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
27 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
29 SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
31 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
33 size_t CCoinsViewCache::DynamicMemoryUsage() const {
34 return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
37 CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
38 CCoinsMap::iterator it = cacheCoins.find(outpoint);
39 if (it != cacheCoins.end())
40 return it;
41 Coin tmp;
42 if (!base->GetCoin(outpoint, tmp))
43 return cacheCoins.end();
44 CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
45 if (ret->second.coin.IsSpent()) {
46 // The parent only has an empty entry for this outpoint; we can consider our
47 // version as fresh.
48 ret->second.flags = CCoinsCacheEntry::FRESH;
50 cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
51 return ret;
54 bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
55 CCoinsMap::const_iterator it = FetchCoin(outpoint);
56 if (it != cacheCoins.end()) {
57 coin = it->second.coin;
58 return true;
60 return false;
63 void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
64 assert(!coin.IsSpent());
65 if (coin.out.scriptPubKey.IsUnspendable()) return;
66 CCoinsMap::iterator it;
67 bool inserted;
68 std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
69 bool fresh = false;
70 if (!inserted) {
71 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
73 if (!possible_overwrite) {
74 if (!it->second.coin.IsSpent()) {
75 throw std::logic_error("Adding new coin that replaces non-pruned entry");
77 fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
79 it->second.coin = std::move(coin);
80 it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
81 cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
84 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight) {
85 bool fCoinbase = tx.IsCoinBase();
86 const uint256& txid = tx.GetHash();
87 for (size_t i = 0; i < tx.vout.size(); ++i) {
88 // Pass fCoinbase as the possible_overwrite flag to AddCoin, in order to correctly
89 // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
90 cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), fCoinbase);
94 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
95 CCoinsMap::iterator it = FetchCoin(outpoint);
96 if (it == cacheCoins.end()) return false;
97 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
98 if (moveout) {
99 *moveout = std::move(it->second.coin);
101 if (it->second.flags & CCoinsCacheEntry::FRESH) {
102 cacheCoins.erase(it);
103 } else {
104 it->second.flags |= CCoinsCacheEntry::DIRTY;
105 it->second.coin.Clear();
107 return true;
110 static const Coin coinEmpty;
112 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
113 CCoinsMap::const_iterator it = FetchCoin(outpoint);
114 if (it == cacheCoins.end()) {
115 return coinEmpty;
116 } else {
117 return it->second.coin;
121 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
122 CCoinsMap::const_iterator it = FetchCoin(outpoint);
123 return (it != cacheCoins.end() && !it->second.coin.IsSpent());
126 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
127 CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
128 return it != cacheCoins.end();
131 uint256 CCoinsViewCache::GetBestBlock() const {
132 if (hashBlock.IsNull())
133 hashBlock = base->GetBestBlock();
134 return hashBlock;
137 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
138 hashBlock = hashBlockIn;
141 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
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.coin.IsSpent())) {
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.coin = std::move(it->second.coin);
153 cachedCoinsUsage += entry.coin.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;
161 } else {
162 // Assert that the child cache entry was not marked FRESH if the
163 // parent cache entry has unspent outputs. If this ever happens,
164 // it means the FRESH flag was misapplied and there is a logic
165 // error in the calling code.
166 if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent())
167 throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs");
169 // Found the entry in the parent cache
170 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
171 // The grandparent does not have an entry, and the child is
172 // modified and being pruned. This means we can just delete
173 // it from the parent.
174 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
175 cacheCoins.erase(itUs);
176 } else {
177 // A normal modification.
178 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
179 itUs->second.coin = std::move(it->second.coin);
180 cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
181 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
182 // NOTE: It is possible the child has a FRESH flag here in
183 // the event the entry we found in the parent is pruned. But
184 // we must not copy that FRESH flag to the parent as that
185 // pruned state likely still needs to be communicated to the
186 // grandparent.
190 CCoinsMap::iterator itOld = it++;
191 mapCoins.erase(itOld);
193 hashBlock = hashBlockIn;
194 return true;
197 bool CCoinsViewCache::Flush() {
198 bool fOk = base->BatchWrite(cacheCoins, hashBlock);
199 cacheCoins.clear();
200 cachedCoinsUsage = 0;
201 return fOk;
204 void CCoinsViewCache::Uncache(const COutPoint& hash)
206 CCoinsMap::iterator it = cacheCoins.find(hash);
207 if (it != cacheCoins.end() && it->second.flags == 0) {
208 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
209 cacheCoins.erase(it);
213 unsigned int CCoinsViewCache::GetCacheSize() const {
214 return cacheCoins.size();
217 CAmount CCoinsViewCache::GetValueIn(const CTransaction& tx) const
219 if (tx.IsCoinBase())
220 return 0;
222 CAmount nResult = 0;
223 for (unsigned int i = 0; i < tx.vin.size(); i++)
224 nResult += AccessCoin(tx.vin[i].prevout).out.nValue;
226 return nResult;
229 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
231 if (!tx.IsCoinBase()) {
232 for (unsigned int i = 0; i < tx.vin.size(); i++) {
233 if (!HaveCoin(tx.vin[i].prevout)) {
234 return false;
238 return true;
241 static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_BASE_SIZE / ::GetSerializeSize(CTxOut(), SER_NETWORK, PROTOCOL_VERSION); // TODO: merge with similar definition in undo.h.
243 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
245 COutPoint iter(txid, 0);
246 while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
247 const Coin& alternate = view.AccessCoin(iter);
248 if (!alternate.IsSpent()) return alternate;
249 ++iter.n;
251 return coinEmpty;