1 // Copyright (c) 2012-2020 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>(); }
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlock)15 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
Cursor() const16 std::unique_ptr<CCoinsViewCursor> CCoinsView::Cursor() const { return nullptr; }
17 
HaveCoin(const COutPoint & outpoint) const18 bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
19 {
20     Coin coin;
21     return GetCoin(outpoint, coin);
22 }
23 
CCoinsViewBacked(CCoinsView * viewIn)24 CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
GetCoin(const COutPoint & outpoint,Coin & coin) const25 bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
HaveCoin(const COutPoint & outpoint) const26 bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
GetBestBlock() const27 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
GetHeadBlocks() const28 std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
SetBackend(CCoinsView & viewIn)29 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlock)30 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
Cursor() const31 std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
EstimateSize() const32 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
33 
CCoinsViewCache(CCoinsView * baseIn)34 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
35 
DynamicMemoryUsage() const36 size_t CCoinsViewCache::DynamicMemoryUsage() const {
37     return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
38 }
39 
FetchCoin(const COutPoint & outpoint) const40 CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
41     CCoinsMap::iterator it = cacheCoins.find(outpoint);
42     if (it != cacheCoins.end())
43         return it;
44     Coin tmp;
45     if (!base->GetCoin(outpoint, tmp))
46         return cacheCoins.end();
47     CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
48     if (ret->second.coin.IsSpent()) {
49         // The parent only has an empty entry for this outpoint; we can consider our
50         // version as fresh.
51         ret->second.flags = CCoinsCacheEntry::FRESH;
52     }
53     cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
54     return ret;
55 }
56 
GetCoin(const COutPoint & outpoint,Coin & coin) const57 bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
58     CCoinsMap::const_iterator it = FetchCoin(outpoint);
59     if (it != cacheCoins.end()) {
60         coin = it->second.coin;
61         return !coin.IsSpent();
62     }
63     return false;
64 }
65 
AddCoin(const COutPoint & outpoint,Coin && coin,bool possible_overwrite)66 void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
67     assert(!coin.IsSpent());
68     if (coin.out.scriptPubKey.IsUnspendable()) return;
69     CCoinsMap::iterator it;
70     bool inserted;
71     std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
72     bool fresh = false;
73     if (!inserted) {
74         cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
75     }
76     if (!possible_overwrite) {
77         if (!it->second.coin.IsSpent()) {
78             throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
79         }
80         // If the coin exists in this cache as a spent coin and is DIRTY, then
81         // its spentness hasn't been flushed to the parent cache. We're
82         // re-adding the coin to this cache now but we can't mark it as FRESH.
83         // If we mark it FRESH and then spend it before the cache is flushed
84         // we would remove it from this cache and would never flush spentness
85         // to the parent cache.
86         //
87         // Re-adding a spent coin can happen in the case of a re-org (the coin
88         // is 'spent' when the block adding it is disconnected and then
89         // re-added when it is also added in a newly connected block).
90         //
91         // If the coin doesn't exist in the current cache, or is spent but not
92         // DIRTY, then it can be marked FRESH.
93         fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
94     }
95     it->second.coin = std::move(coin);
96     it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
97     cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
98 }
99 
EmplaceCoinInternalDANGER(COutPoint && outpoint,Coin && coin)100 void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) {
101     cachedCoinsUsage += coin.DynamicMemoryUsage();
102     cacheCoins.emplace(
103         std::piecewise_construct,
104         std::forward_as_tuple(std::move(outpoint)),
105         std::forward_as_tuple(std::move(coin), CCoinsCacheEntry::DIRTY));
106 }
107 
AddCoins(CCoinsViewCache & cache,const CTransaction & tx,int nHeight,bool check_for_overwrite)108 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
109     bool fCoinbase = tx.IsCoinBase();
110     const uint256& txid = tx.GetHash();
111     for (size_t i = 0; i < tx.vout.size(); ++i) {
112         bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
113         // Coinbase transactions can always be overwritten, in order to correctly
114         // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
115         cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
116     }
117 }
118 
SpendCoin(const COutPoint & outpoint,Coin * moveout)119 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
120     CCoinsMap::iterator it = FetchCoin(outpoint);
121     if (it == cacheCoins.end()) return false;
122     cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
123     if (moveout) {
124         *moveout = std::move(it->second.coin);
125     }
126     if (it->second.flags & CCoinsCacheEntry::FRESH) {
127         cacheCoins.erase(it);
128     } else {
129         it->second.flags |= CCoinsCacheEntry::DIRTY;
130         it->second.coin.Clear();
131     }
132     return true;
133 }
134 
135 static const Coin coinEmpty;
136 
AccessCoin(const COutPoint & outpoint) const137 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
138     CCoinsMap::const_iterator it = FetchCoin(outpoint);
139     if (it == cacheCoins.end()) {
140         return coinEmpty;
141     } else {
142         return it->second.coin;
143     }
144 }
145 
HaveCoin(const COutPoint & outpoint) const146 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
147     CCoinsMap::const_iterator it = FetchCoin(outpoint);
148     return (it != cacheCoins.end() && !it->second.coin.IsSpent());
149 }
150 
HaveCoinInCache(const COutPoint & outpoint) const151 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
152     CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
153     return (it != cacheCoins.end() && !it->second.coin.IsSpent());
154 }
155 
GetBestBlock() const156 uint256 CCoinsViewCache::GetBestBlock() const {
157     if (hashBlock.IsNull())
158         hashBlock = base->GetBestBlock();
159     return hashBlock;
160 }
161 
SetBestBlock(const uint256 & hashBlockIn)162 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
163     hashBlock = hashBlockIn;
164 }
165 
BatchWrite(CCoinsMap & mapCoins,const uint256 & hashBlockIn)166 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
167     for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
168         // Ignore non-dirty entries (optimization).
169         if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
170             continue;
171         }
172         CCoinsMap::iterator itUs = cacheCoins.find(it->first);
173         if (itUs == cacheCoins.end()) {
174             // The parent cache does not have an entry, while the child cache does.
175             // We can ignore it if it's both spent and FRESH in the child
176             if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
177                 // Create the coin in the parent cache, move the data up
178                 // and mark it as dirty.
179                 CCoinsCacheEntry& entry = cacheCoins[it->first];
180                 entry.coin = std::move(it->second.coin);
181                 cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
182                 entry.flags = CCoinsCacheEntry::DIRTY;
183                 // We can mark it FRESH in the parent if it was FRESH in the child
184                 // Otherwise it might have just been flushed from the parent's cache
185                 // and already exist in the grandparent
186                 if (it->second.flags & CCoinsCacheEntry::FRESH) {
187                     entry.flags |= CCoinsCacheEntry::FRESH;
188                 }
189             }
190         } else {
191             // Found the entry in the parent cache
192             if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
193                 // The coin was marked FRESH in the child cache, but the coin
194                 // exists in the parent cache. If this ever happens, it means
195                 // the FRESH flag was misapplied and there is a logic error in
196                 // the calling code.
197                 throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
198             }
199 
200             if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
201                 // The grandparent cache does not have an entry, and the coin
202                 // has been spent. We can just delete it from the parent cache.
203                 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
204                 cacheCoins.erase(itUs);
205             } else {
206                 // A normal modification.
207                 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
208                 itUs->second.coin = std::move(it->second.coin);
209                 cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
210                 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
211                 // NOTE: It isn't safe to mark the coin as FRESH in the parent
212                 // cache. If it already existed and was spent in the parent
213                 // cache then marking it FRESH would prevent that spentness
214                 // from being flushed to the grandparent.
215             }
216         }
217     }
218     hashBlock = hashBlockIn;
219     return true;
220 }
221 
Flush()222 bool CCoinsViewCache::Flush() {
223     bool fOk = base->BatchWrite(cacheCoins, hashBlock);
224     cacheCoins.clear();
225     cachedCoinsUsage = 0;
226     return fOk;
227 }
228 
Uncache(const COutPoint & hash)229 void CCoinsViewCache::Uncache(const COutPoint& hash)
230 {
231     CCoinsMap::iterator it = cacheCoins.find(hash);
232     if (it != cacheCoins.end() && it->second.flags == 0) {
233         cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
234         cacheCoins.erase(it);
235     }
236 }
237 
GetCacheSize() const238 unsigned int CCoinsViewCache::GetCacheSize() const {
239     return cacheCoins.size();
240 }
241 
HaveInputs(const CTransaction & tx) const242 bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
243 {
244     if (!tx.IsCoinBase()) {
245         for (unsigned int i = 0; i < tx.vin.size(); i++) {
246             if (!HaveCoin(tx.vin[i].prevout)) {
247                 return false;
248             }
249         }
250     }
251     return true;
252 }
253 
ReallocateCache()254 void CCoinsViewCache::ReallocateCache()
255 {
256     // Cache should be empty when we're calling this.
257     assert(cacheCoins.size() == 0);
258     cacheCoins.~CCoinsMap();
259     ::new (&cacheCoins) CCoinsMap();
260 }
261 
262 static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut(), PROTOCOL_VERSION);
263 static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
264 
AccessByTxid(const CCoinsViewCache & view,const uint256 & txid)265 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
266 {
267     COutPoint iter(txid, 0);
268     while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
269         const Coin& alternate = view.AccessCoin(iter);
270         if (!alternate.IsSpent()) return alternate;
271         ++iter.n;
272     }
273     return coinEmpty;
274 }
275 
GetCoin(const COutPoint & outpoint,Coin & coin) const276 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
277     try {
278         return CCoinsViewBacked::GetCoin(outpoint, coin);
279     } catch(const std::runtime_error& e) {
280         for (auto f : m_err_callbacks) {
281             f();
282         }
283         LogPrintf("Error reading from database: %s\n", e.what());
284         // Starting the shutdown sequence and returning false to the caller would be
285         // interpreted as 'entry not found' (as opposed to unable to read data), and
286         // could lead to invalid interpretation. Just exit immediately, as we can't
287         // continue anyway, and all writes should be atomic.
288         std::abort();
289     }
290 }
291