1 // Copyright (c) 2012-2019 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
5 #include <coins.h>
6
7 #include <consensus/consensus.h>
8 #include <logging.h>
9 #include <random.h>
10 #include <version.h>
11
GetCoin(const COutPoint & outpoint,Coin & coin) const12 bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
GetBestBlock() const13 uint256 CCoinsView::GetBestBlock() const { return uint256(); }
GetHeadBlocks() const14 std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
GetName(const valtype & name,CNameData & data) const15 bool CCoinsView::GetName(const valtype &name, CNameData &data) const { return false; }
GetNameHistory(const valtype & name,CNameHistory & data) const16 bool CCoinsView::GetNameHistory(const valtype &name, CNameHistory &data) const { return false; }
GetNamesForHeight(unsigned nHeight,std::set<valtype> & names) const17 bool CCoinsView::GetNamesForHeight(unsigned nHeight, std::set<valtype>& names) const { return false; }
IterateNames() const18 CNameIterator* CCoinsView::IterateNames() const { assert (false); }
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlock,const CNameCache & names)19 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, const CNameCache &names) { return false; }
Cursor() const20 CCoinsViewCursor *CCoinsView::Cursor() const { return nullptr; }
ValidateNameDB(ChainstateManager & chainman,const std::function<void ()> & interruption_point) const21 bool CCoinsView::ValidateNameDB(ChainstateManager& chainman, const std::function<void()>& interruption_point) const { return false; }
22
HaveCoin(const COutPoint & outpoint) const23 bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
24 {
25 Coin coin;
26 return GetCoin(outpoint, coin);
27 }
28
CCoinsViewBacked(CCoinsView * viewIn)29 CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
GetCoin(const COutPoint & outpoint,Coin & coin) const30 bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
HaveCoin(const COutPoint & outpoint) const31 bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
GetBestBlock() const32 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
GetHeadBlocks() const33 std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
GetName(const valtype & name,CNameData & data) const34 bool CCoinsViewBacked::GetName(const valtype &name, CNameData &data) const { return base->GetName(name, data); }
GetNameHistory(const valtype & name,CNameHistory & data) const35 bool CCoinsViewBacked::GetNameHistory(const valtype &name, CNameHistory &data) const { return base->GetNameHistory(name, data); }
GetNamesForHeight(unsigned nHeight,std::set<valtype> & names) const36 bool CCoinsViewBacked::GetNamesForHeight(unsigned nHeight, std::set<valtype>& names) const { return base->GetNamesForHeight(nHeight, names); }
IterateNames() const37 CNameIterator* CCoinsViewBacked::IterateNames() const { return base->IterateNames(); }
SetBackend(CCoinsView & viewIn)38 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlock,const CNameCache & names)39 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, const CNameCache &names) { return base->BatchWrite(mapCoins, hashBlock, names); }
Cursor() const40 CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
EstimateSize() const41 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
ValidateNameDB(ChainstateManager & chainman,const std::function<void ()> & interruption_point) const42 bool CCoinsViewBacked::ValidateNameDB(ChainstateManager& chainman, const std::function<void()>& interruption_point) const { return base->ValidateNameDB(chainman, interruption_point); }
43
SaltedOutpointHasher()44 SaltedOutpointHasher::SaltedOutpointHasher() : k0(GetRand(std::numeric_limits<uint64_t>::max())), k1(GetRand(std::numeric_limits<uint64_t>::max())) {}
45
CCoinsViewCache(CCoinsView * baseIn)46 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
47
DynamicMemoryUsage() const48 size_t CCoinsViewCache::DynamicMemoryUsage() const {
49 return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
50 }
51
FetchCoin(const COutPoint & outpoint) const52 CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
53 CCoinsMap::iterator it = cacheCoins.find(outpoint);
54 if (it != cacheCoins.end())
55 return it;
56 Coin tmp;
57 if (!base->GetCoin(outpoint, tmp))
58 return cacheCoins.end();
59 CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
60 if (ret->second.coin.IsSpent()) {
61 // The parent only has an empty entry for this outpoint; we can consider our
62 // version as fresh.
63 ret->second.flags = CCoinsCacheEntry::FRESH;
64 }
65 cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
66 return ret;
67 }
68
GetCoin(const COutPoint & outpoint,Coin & coin) const69 bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
70 CCoinsMap::const_iterator it = FetchCoin(outpoint);
71 if (it != cacheCoins.end()) {
72 coin = it->second.coin;
73 return !coin.IsSpent();
74 }
75 return false;
76 }
77
AddCoin(const COutPoint & outpoint,Coin && coin,bool possible_overwrite)78 void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
79 assert(!coin.IsSpent());
80 if (coin.out.scriptPubKey.IsUnspendable()) return;
81 CCoinsMap::iterator it;
82 bool inserted;
83 std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
84 bool fresh = false;
85 if (!inserted) {
86 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
87 }
88 if (!possible_overwrite) {
89 if (!it->second.coin.IsSpent()) {
90 throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
91 }
92 // If the coin exists in this cache as a spent coin and is DIRTY, then
93 // its spentness hasn't been flushed to the parent cache. We're
94 // re-adding the coin to this cache now but we can't mark it as FRESH.
95 // If we mark it FRESH and then spend it before the cache is flushed
96 // we would remove it from this cache and would never flush spentness
97 // to the parent cache.
98 //
99 // Re-adding a spent coin can happen in the case of a re-org (the coin
100 // is 'spent' when the block adding it is disconnected and then
101 // re-added when it is also added in a newly connected block).
102 //
103 // If the coin doesn't exist in the current cache, or is spent but not
104 // DIRTY, then it can be marked FRESH.
105 fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
106 }
107 it->second.coin = std::move(coin);
108 it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
109 cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
110 }
111
AddCoins(CCoinsViewCache & cache,const CTransaction & tx,int nHeight,bool check_for_overwrite)112 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
113 bool fCoinbase = tx.IsCoinBase();
114 const uint256& txid = tx.GetHash();
115 for (size_t i = 0; i < tx.vout.size(); ++i) {
116 bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
117 // Coinbase transactions can always be overwritten, in order to correctly
118 // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
119 cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
120 }
121 }
122
SpendCoin(const COutPoint & outpoint,Coin * moveout)123 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
124 CCoinsMap::iterator it = FetchCoin(outpoint);
125 if (it == cacheCoins.end()) return false;
126 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
127 if (moveout) {
128 *moveout = std::move(it->second.coin);
129 }
130 if (it->second.flags & CCoinsCacheEntry::FRESH) {
131 cacheCoins.erase(it);
132 } else {
133 it->second.flags |= CCoinsCacheEntry::DIRTY;
134 it->second.coin.Clear();
135 }
136 return true;
137 }
138
139 static const Coin coinEmpty;
140
AccessCoin(const COutPoint & outpoint) const141 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
142 CCoinsMap::const_iterator it = FetchCoin(outpoint);
143 if (it == cacheCoins.end()) {
144 return coinEmpty;
145 } else {
146 return it->second.coin;
147 }
148 }
149
HaveCoin(const COutPoint & outpoint) const150 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
151 CCoinsMap::const_iterator it = FetchCoin(outpoint);
152 return (it != cacheCoins.end() && !it->second.coin.IsSpent());
153 }
154
HaveCoinInCache(const COutPoint & outpoint) const155 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
156 CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
157 return (it != cacheCoins.end() && !it->second.coin.IsSpent());
158 }
159
GetBestBlock() const160 uint256 CCoinsViewCache::GetBestBlock() const {
161 if (hashBlock.IsNull())
162 hashBlock = base->GetBestBlock();
163 return hashBlock;
164 }
165
SetBestBlock(const uint256 & hashBlockIn)166 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
167 hashBlock = hashBlockIn;
168 }
169
GetName(const valtype & name,CNameData & data) const170 bool CCoinsViewCache::GetName(const valtype &name, CNameData& data) const {
171 if (cacheNames.isDeleted(name))
172 return false;
173 if (cacheNames.get(name, data))
174 return true;
175
176 /* Note: This does not attempt to cache name queries. The cache
177 only keeps track of changes! */
178
179 return base->GetName(name, data);
180 }
181
GetNameHistory(const valtype & name,CNameHistory & data) const182 bool CCoinsViewCache::GetNameHistory(const valtype &name, CNameHistory& data) const {
183 if (cacheNames.getHistory(name, data))
184 return true;
185
186 /* Note: This does not attempt to cache backend queries. The cache
187 only keeps track of changes! */
188
189 return base->GetNameHistory(name, data);
190 }
191
GetNamesForHeight(unsigned nHeight,std::set<valtype> & names) const192 bool CCoinsViewCache::GetNamesForHeight(unsigned nHeight, std::set<valtype>& names) const {
193 /* Query the base view first, and then apply the cached changes (if
194 there are any). */
195
196 if (!base->GetNamesForHeight(nHeight, names))
197 return false;
198
199 cacheNames.updateNamesForHeight(nHeight, names);
200 return true;
201 }
202
IterateNames() const203 CNameIterator* CCoinsViewCache::IterateNames() const {
204 return cacheNames.iterateNames(base->IterateNames());
205 }
206
207 /* undo is set if the change is due to disconnecting blocks / going back in
208 time. The ordinary case (!undo) means that we update the name normally,
209 going forward in time. This is important for keeping track of the
210 name history. */
SetName(const valtype & name,const CNameData & data,bool undo)211 void CCoinsViewCache::SetName(const valtype &name, const CNameData& data, bool undo) {
212 CNameData oldData;
213 if (GetName(name, oldData))
214 {
215 cacheNames.removeExpireIndex(name, oldData.getHeight());
216
217 /* Update the name history. If we are undoing, we expect that
218 the top history item matches the data being set now. If we
219 are not undoing, push the overwritten data onto the history stack.
220 Note that we only have to do this if the name already existed
221 in the database. Otherwise, no special action is required
222 for the name history. */
223 if (fNameHistory)
224 {
225 CNameHistory history;
226 if (!GetNameHistory(name, history))
227 {
228 /* Ensure that the history stack is indeed (still) empty
229 and was not modified by the failing GetNameHistory call. */
230 assert(history.empty());
231 }
232
233 if (undo)
234 history.pop(data);
235 else
236 history.push(oldData);
237
238 cacheNames.setHistory(name, history);
239 }
240 } else
241 assert (!undo);
242
243 cacheNames.set(name, data);
244 cacheNames.addExpireIndex(name, data.getHeight());
245 }
246
DeleteName(const valtype & name)247 void CCoinsViewCache::DeleteName(const valtype &name) {
248 CNameData oldData;
249 if (GetName(name, oldData))
250 cacheNames.removeExpireIndex(name, oldData.getHeight());
251 else
252 assert(false);
253
254 if (fNameHistory)
255 {
256 /* When deleting a name, the history should already be clean. */
257 CNameHistory history;
258 assert (!GetNameHistory(name, history) || history.empty());
259 }
260
261 cacheNames.remove(name);
262 }
263
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlockIn,const CNameCache & names)264 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, const CNameCache &names) {
265 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
266 // Ignore non-dirty entries (optimization).
267 if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
268 continue;
269 }
270 CCoinsMap::iterator itUs = cacheCoins.find(it->first);
271 if (itUs == cacheCoins.end()) {
272 // The parent cache does not have an entry, while the child cache does.
273 // We can ignore it if it's both spent and FRESH in the child
274 if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
275 // Create the coin in the parent cache, move the data up
276 // and mark it as dirty.
277 CCoinsCacheEntry& entry = cacheCoins[it->first];
278 entry.coin = std::move(it->second.coin);
279 cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
280 entry.flags = CCoinsCacheEntry::DIRTY;
281 // We can mark it FRESH in the parent if it was FRESH in the child
282 // Otherwise it might have just been flushed from the parent's cache
283 // and already exist in the grandparent
284 if (it->second.flags & CCoinsCacheEntry::FRESH) {
285 entry.flags |= CCoinsCacheEntry::FRESH;
286 }
287 }
288 } else {
289 // Found the entry in the parent cache
290 if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
291 // The coin was marked FRESH in the child cache, but the coin
292 // exists in the parent cache. If this ever happens, it means
293 // the FRESH flag was misapplied and there is a logic error in
294 // the calling code.
295 throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
296 }
297
298 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
299 // The grandparent cache does not have an entry, and the coin
300 // has been spent. We can just delete it from the parent cache.
301 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
302 cacheCoins.erase(itUs);
303 } else {
304 // A normal modification.
305 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
306 itUs->second.coin = std::move(it->second.coin);
307 cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
308 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
309 // NOTE: It isn't safe to mark the coin as FRESH in the parent
310 // cache. If it already existed and was spent in the parent
311 // cache then marking it FRESH would prevent that spentness
312 // from being flushed to the grandparent.
313 }
314 }
315 }
316 hashBlock = hashBlockIn;
317 cacheNames.apply(names);
318 return true;
319 }
320
Flush()321 bool CCoinsViewCache::Flush() {
322 /* This function is called when validating the name mempool, and BatchWrite
323 actually fails if hashBlock is not set. Thus we have to make sure here
324 that it is a valid no-op when nothing is cached. */
325 if (hashBlock.IsNull() && cacheCoins.empty() && cacheNames.empty())
326 return true;
327
328 bool fOk = base->BatchWrite(cacheCoins, hashBlock, cacheNames);
329 cacheCoins.clear();
330 cachedCoinsUsage = 0;
331 cacheNames.clear();
332 return fOk;
333 }
334
Uncache(const COutPoint & hash)335 void CCoinsViewCache::Uncache(const COutPoint& hash)
336 {
337 CCoinsMap::iterator it = cacheCoins.find(hash);
338 if (it != cacheCoins.end() && it->second.flags == 0) {
339 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
340 cacheCoins.erase(it);
341 }
342 }
343
GetCacheSize() const344 unsigned int CCoinsViewCache::GetCacheSize() const {
345 // Do not take name operations into account here.
346 return cacheCoins.size();
347 }
348
HaveInputs(const CTransaction & tx) const349 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
350 {
351 if (!tx.IsCoinBase()) {
352 for (unsigned int i = 0; i < tx.vin.size(); i++) {
353 if (!HaveCoin(tx.vin[i].prevout)) {
354 return false;
355 }
356 }
357 }
358 return true;
359 }
360
ReallocateCache()361 void CCoinsViewCache::ReallocateCache()
362 {
363 // Cache should be empty when we're calling this.
364 assert(cacheCoins.size() == 0);
365 cacheCoins.~CCoinsMap();
366 ::new (&cacheCoins) CCoinsMap();
367 }
368
369 static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), PROTOCOL_VERSION);
370 static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
371
AccessByTxid(const CCoinsViewCache & view,const uint256 & txid)372 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
373 {
374 COutPoint iter(txid, 0);
375 while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
376 const Coin& alternate = view.AccessCoin(iter);
377 if (!alternate.IsSpent()) return alternate;
378 ++iter.n;
379 }
380 return coinEmpty;
381 }
382
GetCoin(const COutPoint & outpoint,Coin & coin) const383 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
384 try {
385 return CCoinsViewBacked::GetCoin(outpoint, coin);
386 } catch(const std::runtime_error& e) {
387 for (auto f : m_err_callbacks) {
388 f();
389 }
390 LogPrintf("Error reading from database: %s\n", e.what());
391 // Starting the shutdown sequence and returning false to the caller would be
392 // interpreted as 'entry not found' (as opposed to unable to read data), and
393 // could lead to invalid interpretation. Just exit immediately, as we can't
394 // continue anyway, and all writes should be atomic.
395 std::abort();
396 }
397 }
398