Branch data Line data Source code
1 : : // Copyright (c) 2012-2022 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 <util/trace.h>
11 : :
12 : 0 : bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
13 : 0 : uint256 CCoinsView::GetBestBlock() const { return uint256(); }
14 : 0 : std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
15 : 0 : bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase) { return false; }
16 : 0 : std::unique_ptr<CCoinsViewCursor> CCoinsView::Cursor() const { return nullptr; }
17 : :
18 : 0 : bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
19 : : {
20 : 0 : Coin coin;
21 [ # # ]: 0 : return GetCoin(outpoint, coin);
22 : 0 : }
23 : :
24 : 0 : CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
25 : 0 : bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
26 : 0 : bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
27 : 0 : uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
28 : 0 : std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
29 : 0 : void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
30 : 0 : bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase) { return base->BatchWrite(mapCoins, hashBlock, erase); }
31 : 0 : std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
32 : 0 : size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
33 : :
34 [ # # ][ # # ]: 0 : CCoinsViewCache::CCoinsViewCache(CCoinsView* baseIn, bool deterministic) :
35 : 0 : CCoinsViewBacked(baseIn), m_deterministic(deterministic),
36 [ # # ][ # # ]: 0 : cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic), CCoinsMap::key_equal{}, &m_cache_coins_memory_resource)
37 : 0 : {}
38 : :
39 : 0 : size_t CCoinsViewCache::DynamicMemoryUsage() const {
40 : 0 : return memusage::DynamicUsage(cacheCoins) + cachedCoinsUsage;
41 : : }
42 : :
43 : 0 : CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
44 : 0 : CCoinsMap::iterator it = cacheCoins.find(outpoint);
45 [ # # ]: 0 : if (it != cacheCoins.end())
46 : 0 : return it;
47 : 0 : Coin tmp;
48 [ # # ][ # # ]: 0 : if (!base->GetCoin(outpoint, tmp))
49 : 0 : return cacheCoins.end();
50 [ # # ]: 0 : CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
51 [ # # ][ # # ]: 0 : if (ret->second.coin.IsSpent()) {
52 : : // The parent only has an empty entry for this outpoint; we can consider our
53 : : // version as fresh.
54 : 0 : ret->second.flags = CCoinsCacheEntry::FRESH;
55 : 0 : }
56 [ # # ]: 0 : cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
57 : 0 : return ret;
58 : 0 : }
59 : :
60 : 0 : bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
61 : 0 : CCoinsMap::const_iterator it = FetchCoin(outpoint);
62 [ # # ]: 0 : if (it != cacheCoins.end()) {
63 : 0 : coin = it->second.coin;
64 : 0 : return !coin.IsSpent();
65 : : }
66 : 0 : return false;
67 : 0 : }
68 : :
69 : 0 : void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
70 [ # # ]: 0 : assert(!coin.IsSpent());
71 [ # # ]: 0 : if (coin.out.scriptPubKey.IsUnspendable()) return;
72 : 0 : CCoinsMap::iterator it;
73 : : bool inserted;
74 : 0 : std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
75 : 0 : bool fresh = false;
76 [ # # ]: 0 : if (!inserted) {
77 : 0 : cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
78 : 0 : }
79 [ # # ]: 0 : if (!possible_overwrite) {
80 [ # # ]: 0 : if (!it->second.coin.IsSpent()) {
81 [ # # ]: 0 : throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
82 : : }
83 : : // If the coin exists in this cache as a spent coin and is DIRTY, then
84 : : // its spentness hasn't been flushed to the parent cache. We're
85 : : // re-adding the coin to this cache now but we can't mark it as FRESH.
86 : : // If we mark it FRESH and then spend it before the cache is flushed
87 : : // we would remove it from this cache and would never flush spentness
88 : : // to the parent cache.
89 : : //
90 : : // Re-adding a spent coin can happen in the case of a re-org (the coin
91 : : // is 'spent' when the block adding it is disconnected and then
92 : : // re-added when it is also added in a newly connected block).
93 : : //
94 : : // If the coin doesn't exist in the current cache, or is spent but not
95 : : // DIRTY, then it can be marked FRESH.
96 : 0 : fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
97 : 0 : }
98 : 0 : it->second.coin = std::move(coin);
99 : 0 : it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
100 : 0 : cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
101 : : TRACE5(utxocache, add,
102 : : outpoint.hash.data(),
103 : : (uint32_t)outpoint.n,
104 : : (uint32_t)it->second.coin.nHeight,
105 : : (int64_t)it->second.coin.out.nValue,
106 : : (bool)it->second.coin.IsCoinBase());
107 : 0 : }
108 : :
109 : 0 : void CCoinsViewCache::EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin) {
110 : 0 : cachedCoinsUsage += coin.DynamicMemoryUsage();
111 : 0 : cacheCoins.emplace(
112 : : std::piecewise_construct,
113 : 0 : std::forward_as_tuple(std::move(outpoint)),
114 : 0 : std::forward_as_tuple(std::move(coin), CCoinsCacheEntry::DIRTY));
115 : 0 : }
116 : :
117 : 0 : void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
118 : 0 : bool fCoinbase = tx.IsCoinBase();
119 : 0 : const Txid& txid = tx.GetHash();
120 [ # # ]: 0 : for (size_t i = 0; i < tx.vout.size(); ++i) {
121 [ # # ]: 0 : bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
122 : : // Coinbase transactions can always be overwritten, in order to correctly
123 : : // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
124 [ # # ]: 0 : cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
125 : 0 : }
126 : 0 : }
127 : :
128 : 0 : bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
129 : 0 : CCoinsMap::iterator it = FetchCoin(outpoint);
130 [ # # ]: 0 : if (it == cacheCoins.end()) return false;
131 : 0 : cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
132 : : TRACE5(utxocache, spent,
133 : : outpoint.hash.data(),
134 : : (uint32_t)outpoint.n,
135 : : (uint32_t)it->second.coin.nHeight,
136 : : (int64_t)it->second.coin.out.nValue,
137 : : (bool)it->second.coin.IsCoinBase());
138 [ # # ]: 0 : if (moveout) {
139 : 0 : *moveout = std::move(it->second.coin);
140 : 0 : }
141 [ # # ]: 0 : if (it->second.flags & CCoinsCacheEntry::FRESH) {
142 : 0 : cacheCoins.erase(it);
143 : 0 : } else {
144 : 0 : it->second.flags |= CCoinsCacheEntry::DIRTY;
145 : 0 : it->second.coin.Clear();
146 : : }
147 : 0 : return true;
148 : 0 : }
149 : :
150 : 2 : static const Coin coinEmpty;
151 : :
152 : 0 : const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
153 : 0 : CCoinsMap::const_iterator it = FetchCoin(outpoint);
154 [ # # ]: 0 : if (it == cacheCoins.end()) {
155 : 0 : return coinEmpty;
156 : : } else {
157 : 0 : return it->second.coin;
158 : : }
159 : 0 : }
160 : :
161 : 0 : bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
162 : 0 : CCoinsMap::const_iterator it = FetchCoin(outpoint);
163 [ # # ]: 0 : return (it != cacheCoins.end() && !it->second.coin.IsSpent());
164 : : }
165 : :
166 : 0 : bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
167 : 0 : CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
168 [ # # ]: 0 : return (it != cacheCoins.end() && !it->second.coin.IsSpent());
169 : : }
170 : :
171 : 0 : uint256 CCoinsViewCache::GetBestBlock() const {
172 [ # # ]: 0 : if (hashBlock.IsNull())
173 : 0 : hashBlock = base->GetBestBlock();
174 : 0 : return hashBlock;
175 : : }
176 : :
177 : 0 : void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
178 : 0 : hashBlock = hashBlockIn;
179 : 0 : }
180 : :
181 : 0 : bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn, bool erase) {
182 [ # # ]: 0 : for (CCoinsMap::iterator it = mapCoins.begin();
183 : 0 : it != mapCoins.end();
184 [ # # ]: 0 : it = erase ? mapCoins.erase(it) : std::next(it)) {
185 : : // Ignore non-dirty entries (optimization).
186 [ # # ]: 0 : if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
187 : 0 : continue;
188 : : }
189 : 0 : CCoinsMap::iterator itUs = cacheCoins.find(it->first);
190 [ # # ]: 0 : if (itUs == cacheCoins.end()) {
191 : : // The parent cache does not have an entry, while the child cache does.
192 : : // We can ignore it if it's both spent and FRESH in the child
193 [ # # ][ # # ]: 0 : if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
194 : : // Create the coin in the parent cache, move the data up
195 : : // and mark it as dirty.
196 : 0 : CCoinsCacheEntry& entry = cacheCoins[it->first];
197 [ # # ]: 0 : if (erase) {
198 : : // The `move` call here is purely an optimization; we rely on the
199 : : // `mapCoins.erase` call in the `for` expression to actually remove
200 : : // the entry from the child map.
201 : 0 : entry.coin = std::move(it->second.coin);
202 : 0 : } else {
203 : 0 : entry.coin = it->second.coin;
204 : : }
205 : 0 : cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
206 : 0 : entry.flags = CCoinsCacheEntry::DIRTY;
207 : : // We can mark it FRESH in the parent if it was FRESH in the child
208 : : // Otherwise it might have just been flushed from the parent's cache
209 : : // and already exist in the grandparent
210 [ # # ]: 0 : if (it->second.flags & CCoinsCacheEntry::FRESH) {
211 : 0 : entry.flags |= CCoinsCacheEntry::FRESH;
212 : 0 : }
213 : 0 : }
214 : 0 : } else {
215 : : // Found the entry in the parent cache
216 [ # # ][ # # ]: 0 : if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
217 : : // The coin was marked FRESH in the child cache, but the coin
218 : : // exists in the parent cache. If this ever happens, it means
219 : : // the FRESH flag was misapplied and there is a logic error in
220 : : // the calling code.
221 [ # # ]: 0 : throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
222 : : }
223 : :
224 [ # # ][ # # ]: 0 : if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
225 : : // The grandparent cache does not have an entry, and the coin
226 : : // has been spent. We can just delete it from the parent cache.
227 : 0 : cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
228 : 0 : cacheCoins.erase(itUs);
229 : 0 : } else {
230 : : // A normal modification.
231 : 0 : cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
232 [ # # ]: 0 : if (erase) {
233 : : // The `move` call here is purely an optimization; we rely on the
234 : : // `mapCoins.erase` call in the `for` expression to actually remove
235 : : // the entry from the child map.
236 : 0 : itUs->second.coin = std::move(it->second.coin);
237 : 0 : } else {
238 : 0 : itUs->second.coin = it->second.coin;
239 [ # # ]: 0 : }
240 : 0 : cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
241 : 0 : itUs->second.flags |= CCoinsCacheEntry::DIRTY;
242 : : // NOTE: It isn't safe to mark the coin as FRESH in the parent
243 : 0 : // cache. If it already existed and was spent in the parent
244 : : // cache then marking it FRESH would prevent that spentness
245 : : // from being flushed to the grandparent.
246 : : }
247 : : }
248 : 0 : }
249 : 0 : hashBlock = hashBlockIn;
250 : 0 : return true;
251 : 0 : }
252 : :
253 : 0 : bool CCoinsViewCache::Flush() {
254 : 0 : bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/true);
255 [ # # ]: 0 : if (fOk) {
256 [ # # ]: 0 : if (!cacheCoins.empty()) {
257 : : /* BatchWrite must erase all cacheCoins elements when erase=true. */
258 [ # # ]: 0 : throw std::logic_error("Not all cached coins were erased");
259 : : }
260 : 0 : ReallocateCache();
261 : 0 : }
262 : 0 : cachedCoinsUsage = 0;
263 : 0 : return fOk;
264 : 0 : }
265 : :
266 : 0 : bool CCoinsViewCache::Sync()
267 : : {
268 : 0 : bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/false);
269 : : // Instead of clearing `cacheCoins` as we would in Flush(), just clear the
270 : : // FRESH/DIRTY flags of any coin that isn't spent.
271 [ # # ]: 0 : for (auto it = cacheCoins.begin(); it != cacheCoins.end(); ) {
272 [ # # ]: 0 : if (it->second.coin.IsSpent()) {
273 : 0 : cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
274 : 0 : it = cacheCoins.erase(it);
275 : 0 : } else {
276 : 0 : it->second.flags = 0;
277 : 0 : ++it;
278 : : }
279 : : }
280 : 0 : return fOk;
281 : : }
282 : :
283 : 0 : void CCoinsViewCache::Uncache(const COutPoint& hash)
284 : : {
285 : 0 : CCoinsMap::iterator it = cacheCoins.find(hash);
286 [ # # ][ # # ]: 0 : if (it != cacheCoins.end() && it->second.flags == 0) {
287 : 0 : cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
288 : : TRACE5(utxocache, uncache,
289 : : hash.hash.data(),
290 : : (uint32_t)hash.n,
291 : : (uint32_t)it->second.coin.nHeight,
292 : : (int64_t)it->second.coin.out.nValue,
293 : : (bool)it->second.coin.IsCoinBase());
294 : 0 : cacheCoins.erase(it);
295 : 0 : }
296 : 0 : }
297 : :
298 : 0 : unsigned int CCoinsViewCache::GetCacheSize() const {
299 : 0 : return cacheCoins.size();
300 : : }
301 : :
302 : 0 : bool CCoinsViewCache::HaveInputs(const CTransaction& tx) const
303 : : {
304 [ # # ]: 0 : if (!tx.IsCoinBase()) {
305 [ # # ]: 0 : for (unsigned int i = 0; i < tx.vin.size(); i++) {
306 [ # # ]: 0 : if (!HaveCoin(tx.vin[i].prevout)) {
307 : 0 : return false;
308 : : }
309 : 0 : }
310 : 0 : }
311 : 0 : return true;
312 : 0 : }
313 : :
314 : 0 : void CCoinsViewCache::ReallocateCache()
315 : : {
316 : : // Cache should be empty when we're calling this.
317 [ # # ]: 0 : assert(cacheCoins.size() == 0);
318 : 0 : cacheCoins.~CCoinsMap();
319 : 0 : m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
320 : 0 : ::new (&m_cache_coins_memory_resource) CCoinsMapMemoryResource{};
321 : 0 : ::new (&cacheCoins) CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic}, CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
322 : 0 : }
323 : :
324 : 0 : void CCoinsViewCache::SanityCheck() const
325 : : {
326 : 0 : size_t recomputed_usage = 0;
327 [ # # ]: 0 : for (const auto& [_, entry] : cacheCoins) {
328 : 0 : unsigned attr = 0;
329 [ # # ]: 0 : if (entry.flags & CCoinsCacheEntry::DIRTY) attr |= 1;
330 [ # # ]: 0 : if (entry.flags & CCoinsCacheEntry::FRESH) attr |= 2;
331 [ # # ]: 0 : if (entry.coin.IsSpent()) attr |= 4;
332 : : // Only 5 combinations are possible.
333 [ # # ][ # # ]: 0 : assert(attr != 2 && attr != 4 && attr != 7);
[ # # ]
334 : :
335 : : // Recompute cachedCoinsUsage.
336 : 0 : recomputed_usage += entry.coin.DynamicMemoryUsage();
337 : : }
338 [ # # ]: 0 : assert(recomputed_usage == cachedCoinsUsage);
339 : 0 : }
340 : :
341 [ + - ]: 2 : static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT = WITNESS_SCALE_FACTOR * ::GetSerializeSize(CTxOut());
342 : 2 : static const size_t MAX_OUTPUTS_PER_BLOCK = MAX_BLOCK_WEIGHT / MIN_TRANSACTION_OUTPUT_WEIGHT;
343 : :
344 : 0 : const Coin& AccessByTxid(const CCoinsViewCache& view, const Txid& txid)
345 : : {
346 : 0 : COutPoint iter(txid, 0);
347 [ # # ]: 0 : while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
348 : 0 : const Coin& alternate = view.AccessCoin(iter);
349 [ # # ]: 0 : if (!alternate.IsSpent()) return alternate;
350 : 0 : ++iter.n;
351 : : }
352 : 0 : return coinEmpty;
353 : 0 : }
354 : :
355 : : template <typename Func>
356 : 0 : static bool ExecuteBackedWrapper(Func func, const std::vector<std::function<void()>>& err_callbacks)
357 : : {
358 : : try {
359 [ # # ][ # # ]: 0 : return func();
360 [ # # ][ # # ]: 0 : } catch(const std::runtime_error& e) {
361 [ # # ][ # # ]: 0 : for (const auto& f : err_callbacks) {
362 [ # # ][ # # ]: 0 : f();
363 : : }
364 [ # # ][ # # ]: 0 : LogPrintf("Error reading from database: %s\n", e.what());
[ # # ][ # # ]
[ # # ][ # # ]
365 : : // Starting the shutdown sequence and returning false to the caller would be
366 : : // interpreted as 'entry not found' (as opposed to unable to read data), and
367 : : // could lead to invalid interpretation. Just exit immediately, as we can't
368 : : // continue anyway, and all writes should be atomic.
369 : 0 : std::abort();
370 [ # # ][ # # ]: 0 : }
371 : 0 : }
372 : :
373 : 0 : bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
374 : 0 : return ExecuteBackedWrapper([&]() { return CCoinsViewBacked::GetCoin(outpoint, coin); }, m_err_callbacks);
375 : : }
376 : :
377 : 0 : bool CCoinsViewErrorCatcher::HaveCoin(const COutPoint &outpoint) const {
378 : 0 : return ExecuteBackedWrapper([&]() { return CCoinsViewBacked::HaveCoin(outpoint); }, m_err_callbacks);
379 : : }
|