Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #ifndef BITCOIN_COINS_H
7 : : #define BITCOIN_COINS_H
8 : :
9 : : #include <attributes.h>
10 : : #include <compressor.h>
11 : : #include <core_memusage.h>
12 : : #include <memusage.h>
13 : : #include <primitives/transaction.h>
14 : : #include <serialize.h>
15 : : #include <support/allocators/pool.h>
16 : : #include <uint256.h>
17 : : #include <util/check.h>
18 : : #include <util/hasher.h>
19 : :
20 : : #include <cassert>
21 : : #include <cstdint>
22 : :
23 : : #include <functional>
24 : : #include <unordered_map>
25 : :
26 : : /**
27 : : * A UTXO entry.
28 : : *
29 : : * Serialized format:
30 : : * - VARINT((coinbase ? 1 : 0) | (height << 1))
31 : : * - the non-spent CTxOut (via TxOutCompression)
32 : : */
33 [ - - + - : 7304799 : class Coin
- - - - +
- ][ + + #
# # # # #
# # ][ + -
+ - + - +
- + - + -
+ - + - -
+ - - + -
+ - - + -
- + - + -
+ - + - +
+ ]
34 : : {
35 : : public:
36 : : //! unspent transaction output
37 : : CTxOut out;
38 : :
39 : : //! whether containing transaction was a coinbase
40 : : unsigned int fCoinBase : 1;
41 : :
42 : : //! at which height this containing transaction was included in the active block chain
43 : : uint32_t nHeight : 31;
44 : :
45 : : //! construct a Coin from a CTxOut and height/coinbase information.
46 [ + + ]: 62 : Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
47 [ + - + + ]: 110451 : Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
[ + - ]
48 : :
49 : 129438 : void Clear() {
50 : 129438 : out.SetNull();
51 : 129438 : fCoinBase = false;
52 [ - + + + : 129438 : nHeight = 0;
+ - ]
53 : 61393 : }
54 : :
55 : : //! empty constructor
56 [ + - ]: 5001728 : Coin() : fCoinBase(false), nHeight(0) { }
[ + - + - ]
[ - - - -
+ - ][ + -
+ - + - -
+ - + +
+ ]
57 : :
58 : 1302 : bool IsCoinBase() const {
59 [ + + - - ]: 1302 : return fCoinBase;
[ + + ]
60 : : }
61 : :
62 : : template<typename Stream>
63 : 84428 : void Serialize(Stream &s) const {
64 [ - + ]: 84428 : assert(!IsSpent());
65 : 84428 : uint32_t code = nHeight * uint32_t{2} + fCoinBase;
66 : 84428 : ::Serialize(s, VARINT(code));
67 : 84428 : ::Serialize(s, Using<TxOutCompression>(out));
68 : 84428 : }
69 : :
70 : : template<typename Stream>
71 : 73879 : void Unserialize(Stream &s) {
72 : 73879 : uint32_t code = 0;
73 : 73879 : ::Unserialize(s, VARINT(code));
74 : 73879 : nHeight = code >> 1;
75 : 73879 : fCoinBase = code & 1;
76 : 73879 : ::Unserialize(s, Using<TxOutCompression>(out));
77 : 73877 : }
78 : :
79 : : /** Either this coin never existed (see e.g. coinEmpty in coins.cpp), or it
80 : : * did exist and has been spent.
81 : : */
82 [ + - ]: 14344102 : bool IsSpent() const {
83 [ + + # # ]: 13528005 : return out.IsNull();
[ - - - +
+ - - + -
- ][ - + +
+ - + ][ +
+ + + + +
+ + + + +
+ + + - +
+ + + + -
+ ][ - + +
- # # # #
# # # # #
# # # # #
# # # # ]
[ + - + -
+ - + - +
+ - + + -
+ - + - +
+ + + + +
+ + + - +
+ + + + +
+ + - + ]
84 : : }
85 : :
86 : 2226607 : size_t DynamicMemoryUsage() const {
87 [ + + + + : 3037868 : return memusage::DynamicUsage(out.scriptPubKey);
+ + - + -
- + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
- + ]
[ - + + + ]
88 : : }
89 : : };
90 : :
91 : : struct CCoinsCacheEntry;
92 : : using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
93 : :
94 : : /**
95 : : * A Coin in one level of the coins database caching hierarchy.
96 : : *
97 : : * A coin can either be:
98 : : * - unspent or spent (in which case the Coin object will be nulled out - see Coin.Clear())
99 : : * - DIRTY or not DIRTY
100 : : * - FRESH or not FRESH
101 : : *
102 : : * Out of these 2^3 = 8 states, only some combinations are valid:
103 : : * - unspent, FRESH, DIRTY (e.g. a new coin created in the cache)
104 : : * - unspent, not FRESH, DIRTY (e.g. a coin changed in the cache during a reorg)
105 : : * - unspent, not FRESH, not DIRTY (e.g. an unspent coin fetched from the parent cache)
106 : : * - spent, not FRESH, DIRTY (e.g. a coin is spent and spentness needs to be flushed to the parent)
107 : : */
108 : : struct CCoinsCacheEntry
109 : : {
110 : : private:
111 : : /**
112 : : * These are used to create a doubly linked list of flagged entries.
113 : : * They are set in SetDirty, SetFresh, and unset in SetClean.
114 : : * A flagged entry is any entry that is either DIRTY, FRESH, or both.
115 : : *
116 : : * DIRTY entries are tracked so that only modified entries can be passed to
117 : : * the parent cache for batch writing. This is a performance optimization
118 : : * compared to giving all entries in the cache to the parent and having the
119 : : * parent scan for only modified entries.
120 : : */
121 : : CoinsCachePair* m_prev{nullptr};
122 : : CoinsCachePair* m_next{nullptr};
123 : : uint8_t m_flags{0};
124 : :
125 : : //! Adding a flag requires a reference to the sentinel of the flagged pair linked list.
126 : 556435 : static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
127 : : {
128 [ + + ]: 556435 : Assume(flags & (DIRTY | FRESH));
129 [ + + ]: 556435 : if (!pair.second.m_flags) {
130 : 412101 : Assume(!pair.second.m_prev && !pair.second.m_next);
131 : 412101 : pair.second.m_prev = sentinel.second.m_prev;
132 : 412101 : pair.second.m_next = &sentinel;
133 : 412101 : sentinel.second.m_prev = &pair;
134 : 412101 : pair.second.m_prev->second.m_next = &pair;
135 : : }
136 : 556435 : Assume(pair.second.m_prev && pair.second.m_next);
137 : 556435 : pair.second.m_flags |= flags;
138 : 556435 : }
139 : :
140 : : public:
141 : : Coin coin; // The actual cached data.
142 : :
143 : : enum Flags {
144 : : /**
145 : : * DIRTY means the CCoinsCacheEntry is potentially different from the
146 : : * version in the parent cache. Failure to mark a coin as DIRTY when
147 : : * it is potentially different from the parent cache will cause a
148 : : * consensus failure, since the coin's state won't get written to the
149 : : * parent when the cache is flushed.
150 : : */
151 : : DIRTY = (1 << 0),
152 : : /**
153 : : * FRESH means the parent cache does not have this coin or that it is a
154 : : * spent coin in the parent cache. If a FRESH coin in the cache is
155 : : * later spent, it can be deleted entirely and doesn't ever need to be
156 : : * flushed to the parent. This is a performance optimization. Marking a
157 : : * coin as FRESH when it exists unspent in the parent cache will cause a
158 : : * consensus failure, since it might not be deleted from the parent
159 : : * when this cache is flushed.
160 : : */
161 : : FRESH = (1 << 1),
162 : : };
163 : :
164 : 26816131 : CCoinsCacheEntry() noexcept = default;
165 : 1864 : explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
166 : 26818315 : ~CCoinsCacheEntry()
167 : : {
168 : 53636630 : SetClean();
169 : 26818315 : }
170 : :
171 : 424260 : static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
172 : 132175 : static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
173 : :
174 : 26845579 : void SetClean() noexcept
175 : : {
176 [ + + ][ + - : 26818321 : if (!m_flags) return;
- + + - -
- ]
177 : 569763 : m_next->second.m_prev = m_prev;
178 : 569763 : m_prev->second.m_next = m_next;
179 : 569763 : m_flags = 0;
180 : 569763 : m_prev = m_next = nullptr;
181 : : }
182 [ + - ][ + - : 1576790 : bool IsDirty() const noexcept { return m_flags & DIRTY; }
+ + + + -
+ + + +
+ ][ + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
183 [ + + + + : 430011 : bool IsFresh() const noexcept { return m_flags & FRESH; }
+ + + + +
+ ][ + + ]
184 : :
185 : : //! Only call Next when this entry is DIRTY, FRESH, or both
186 : 565590 : CoinsCachePair* Next() const noexcept
187 : : {
188 [ - + - + ]: 496708 : Assume(m_flags);
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - ]
189 [ - + ][ + - : 68949 : return m_next;
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
190 : : }
191 : :
192 : : //! Only call Prev when this entry is DIRTY, FRESH, or both
193 : 116536 : CoinsCachePair* Prev() const noexcept
194 : : {
195 [ - + ][ + - : 58288 : Assume(m_flags);
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - ]
196 [ - + - + ]: 58288 : return m_prev;
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- ]
197 : : }
198 : :
199 : : //! Only use this for initializing the linked list sentinel
200 : 157662 : void SelfRef(CoinsCachePair& pair) noexcept
201 : : {
202 [ + - + - : 157662 : Assume(&pair.second == this);
+ - ][ + - ]
203 : 157662 : m_prev = &pair;
204 : 157662 : m_next = &pair;
205 : : // Set sentinel to DIRTY so we can call Next on it
206 [ + - + - : 157662 : m_flags = DIRTY;
+ - ][ + - ]
207 : : }
208 : : };
209 : :
210 : : /**
211 : : * PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size
212 : : * of 4 pointers. We do not know the exact node size used in the std::unordered_node implementation
213 : : * because it is implementation defined. Most implementations have an overhead of 1 or 2 pointers,
214 : : * so nodes can be connected in a linked list, and in some cases the hash value is stored as well.
215 : : * Using an additional sizeof(void*)*4 for MAX_BLOCK_SIZE_BYTES should thus be sufficient so that
216 : : * all implementations can allocate the nodes from the PoolAllocator.
217 : : */
218 : : using CCoinsMap = std::unordered_map<COutPoint,
219 : : CCoinsCacheEntry,
220 : : SaltedOutpointHasher,
221 : : std::equal_to<COutPoint>,
222 : : PoolAllocator<CoinsCachePair,
223 : : sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
224 : :
225 : : using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
226 : :
227 : : /** Cursor for iterating over CoinsView state */
228 : : class CCoinsViewCursor
229 : : {
230 : : public:
231 : 79 : CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
232 : 79 : virtual ~CCoinsViewCursor() = default;
233 : :
234 : : virtual bool GetKey(COutPoint &key) const = 0;
235 : : virtual bool GetValue(Coin &coin) const = 0;
236 : :
237 : : virtual bool Valid() const = 0;
238 : : virtual void Next() = 0;
239 : :
240 : : //! Get best block at the time this cursor was created
241 : : const uint256 &GetBestBlock() const { return hashBlock; }
242 : : private:
243 : : uint256 hashBlock;
244 : : };
245 : :
246 : : /**
247 : : * Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
248 : : *
249 : : * This is a helper struct to encapsulate the diverging logic between a non-erasing
250 : : * CCoinsViewCache::Sync and an erasing CCoinsViewCache::Flush. This allows the receiver
251 : : * of CCoinsView::BatchWrite to iterate through the flagged entries without knowing
252 : : * the caller's intent.
253 : : *
254 : : * However, the receiver can still call CoinsViewCacheCursor::WillErase to see if the
255 : : * caller will erase the entry after BatchWrite returns. If so, the receiver can
256 : : * perform optimizations such as moving the coin out of the CCoinsCachEntry instead
257 : : * of copying it.
258 : : */
259 : : struct CoinsViewCacheCursor
260 : : {
261 : : //! If will_erase is not set, iterating through the cursor will erase spent coins from the map,
262 : : //! and other coins will be unflagged (removing them from the linked list).
263 : : //! If will_erase is set, the underlying map and linked list will not be modified,
264 : : //! as the caller is expected to wipe the entire map anyway.
265 : : //! This is an optimization compared to erasing all entries as the cursor iterates them when will_erase is set.
266 : : //! Calling CCoinsMap::clear() afterwards is faster because a CoinsCachePair cannot be coerced back into a
267 : : //! CCoinsMap::iterator to be erased, and must therefore be looked up again by key in the CCoinsMap before being erased.
268 : 10087 : CoinsViewCacheCursor(CoinsCachePair& sentinel LIFETIMEBOUND,
269 : : CCoinsMap& map LIFETIMEBOUND,
270 : : bool will_erase) noexcept
271 [ + + ]: 10087 : : m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
272 : :
273 : 10087 : inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
274 [ + + ]: 390231 : inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
[ + + - - ]
275 : :
276 : : //! Return the next entry after current, possibly erasing current
277 : 380144 : inline CoinsCachePair* NextAndMaybeErase(CoinsCachePair& current) noexcept
278 : : {
279 [ + + ]: 380144 : const auto next_entry{current.second.Next()};
280 : : // If we are not going to erase the cache, we must still erase spent entries.
281 : : // Otherwise, clear the state of the entry.
282 [ + + ]: 380144 : if (!m_will_erase) {
283 [ + + ]: 45280 : if (current.second.coin.IsSpent()) {
284 [ - + - - ]: 18021 : assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin
285 : 18021 : m_map.erase(current.first);
286 : : } else {
287 [ + - ]: 27259 : current.second.SetClean();
288 : : }
289 : : }
290 : 380144 : return next_entry;
291 : : }
292 : :
293 [ + + + + : 198947 : inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
+ + + + ]
294 : : private:
295 : : CoinsCachePair& m_sentinel;
296 : : CCoinsMap& m_map;
297 : : bool m_will_erase;
298 : : };
299 : :
300 : : /** Abstract view on the open txout dataset. */
301 [ + - + - : 158247 : class CCoinsView
+ - + - ]
302 : : {
303 : : public:
304 : : //! Retrieve the Coin (unspent transaction output) for a given outpoint.
305 : : virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const;
306 : :
307 : : //! Just check whether a given outpoint is unspent.
308 : : virtual bool HaveCoin(const COutPoint &outpoint) const;
309 : :
310 : : //! Retrieve the block hash whose state this CCoinsView currently represents
311 : : virtual uint256 GetBestBlock() const;
312 : :
313 : : //! Retrieve the range of blocks that may have been only partially written.
314 : : //! If the database is in a consistent state, the result is the empty vector.
315 : : //! Otherwise, a two-element vector is returned consisting of the new and
316 : : //! the old block hash, in that order.
317 : : virtual std::vector<uint256> GetHeadBlocks() const;
318 : :
319 : : //! Do a bulk modification (multiple Coin changes + BestBlock change).
320 : : //! The passed cursor is used to iterate through the coins.
321 : : virtual void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
322 : :
323 : : //! Get a cursor to iterate over the whole state
324 : : virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
325 : :
326 : : //! As we use CCoinsViews polymorphically, have a virtual destructor
327 : 138 : virtual ~CCoinsView() = default;
328 : :
329 : : //! Estimate database size (0 if not implemented)
330 : 0 : virtual size_t EstimateSize() const { return 0; }
331 : : };
332 : :
333 : :
334 : : /** CCoinsView backed by another CCoinsView */
335 : 0 : class CCoinsViewBacked : public CCoinsView
336 : : {
337 : : protected:
338 : : CCoinsView *base;
339 : :
340 : : public:
341 : : CCoinsViewBacked(CCoinsView *viewIn);
342 : : std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
343 : : bool HaveCoin(const COutPoint &outpoint) const override;
344 : : uint256 GetBestBlock() const override;
345 : : std::vector<uint256> GetHeadBlocks() const override;
346 : : void SetBackend(CCoinsView &viewIn);
347 : : void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock) override;
348 : : std::unique_ptr<CCoinsViewCursor> Cursor() const override;
349 : : size_t EstimateSize() const override;
350 : : };
351 : :
352 : :
353 : : /** CCoinsView that adds a memory cache for transactions to another CCoinsView */
354 : : class CCoinsViewCache : public CCoinsViewBacked
355 : : {
356 : : private:
357 : : const bool m_deterministic;
358 : :
359 : : protected:
360 : : /**
361 : : * Make mutable so that we can "fill the cache" even from Get-methods
362 : : * declared as "const".
363 : : */
364 : : mutable uint256 hashBlock;
365 : : mutable CCoinsMapMemoryResource m_cache_coins_memory_resource{};
366 : : /* The starting sentinel of the flagged entry circular doubly linked list. */
367 : : mutable CoinsCachePair m_sentinel;
368 : : mutable CCoinsMap cacheCoins;
369 : :
370 : : /* Cached dynamic memory usage for the inner Coin objects. */
371 : : mutable size_t cachedCoinsUsage{0};
372 : :
373 : : /**
374 : : * Discard all modifications made to this cache without flushing to the base view.
375 : : * This can be used to efficiently reuse a cache instance across multiple operations.
376 : : */
377 : : void Reset() noexcept;
378 : :
379 : : public:
380 : : CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
381 : :
382 : : /**
383 : : * By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache on top of a base cache.
384 : : */
385 : : CCoinsViewCache(const CCoinsViewCache &) = delete;
386 : :
387 : : // Standard CCoinsView methods
388 : : std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
389 : : bool HaveCoin(const COutPoint &outpoint) const override;
390 : : uint256 GetBestBlock() const override;
391 : : void SetBestBlock(const uint256 &hashBlock);
392 : : void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock) override;
393 : 0 : std::unique_ptr<CCoinsViewCursor> Cursor() const override {
394 [ # # ]: 0 : throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
395 : : }
396 : :
397 : : /**
398 : : * Check if we have the given utxo already loaded in this cache.
399 : : * The semantics are the same as HaveCoin(), but no calls to
400 : : * the backing CCoinsView are made.
401 : : */
402 : : bool HaveCoinInCache(const COutPoint &outpoint) const;
403 : :
404 : : /**
405 : : * Return a reference to Coin in the cache, or coinEmpty if not found. This is
406 : : * more efficient than GetCoin.
407 : : *
408 : : * Generally, do not hold the reference returned for more than a short scope.
409 : : * While the current implementation allows for modifications to the contents
410 : : * of the cache while holding the reference, this behavior should not be relied
411 : : * on! To be safe, best to not hold the returned reference through any other
412 : : * calls to this cache.
413 : : */
414 : : const Coin& AccessCoin(const COutPoint &output) const;
415 : :
416 : : /**
417 : : * Add a coin. Set possible_overwrite to true if an unspent version may
418 : : * already exist in the cache.
419 : : */
420 : : void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
421 : :
422 : : /**
423 : : * Emplace a coin into cacheCoins without performing any checks, marking
424 : : * the emplaced coin as dirty.
425 : : *
426 : : * NOT FOR GENERAL USE. Used only when loading coins from a UTXO snapshot.
427 : : * @sa ChainstateManager::PopulateAndValidateSnapshot()
428 : : */
429 : : void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
430 : :
431 : : /**
432 : : * Spend a coin. Pass moveto in order to get the deleted data.
433 : : * If no unspent output exists for the passed outpoint, this call
434 : : * has no effect.
435 : : */
436 : : bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
437 : :
438 : : /**
439 : : * Push the modifications applied to this cache to its base and wipe local state.
440 : : * Failure to call this method or Sync() before destruction will cause the changes
441 : : * to be forgotten.
442 : : * If reallocate_cache is false, the cache will retain the same memory footprint
443 : : * after flushing and should be destroyed to deallocate.
444 : : */
445 : : void Flush(bool reallocate_cache = true);
446 : :
447 : : /**
448 : : * Push the modifications applied to this cache to its base while retaining
449 : : * the contents of this cache (except for spent coins, which we erase).
450 : : * Failure to call this method or Flush() before destruction will cause the changes
451 : : * to be forgotten.
452 : : */
453 : : void Sync();
454 : :
455 : : /**
456 : : * Removes the UTXO with the given outpoint from the cache, if it is
457 : : * not modified.
458 : : */
459 : : void Uncache(const COutPoint &outpoint);
460 : :
461 : : //! Calculate the size of the cache (in number of transaction outputs)
462 : : unsigned int GetCacheSize() const;
463 : :
464 : : //! Calculate the size of the cache (in bytes)
465 : : size_t DynamicMemoryUsage() const;
466 : :
467 : : //! Check whether all prevouts of the transaction are present in the UTXO set represented by this view
468 : : bool HaveInputs(const CTransaction& tx) const;
469 : :
470 : : //! Force a reallocation of the cache map. This is required when downsizing
471 : : //! the cache because the map's allocator may be hanging onto a lot of
472 : : //! memory despite having called .clear().
473 : : //!
474 : : //! See: https://stackoverflow.com/questions/42114044/how-to-release-unordered-map-memory
475 : : void ReallocateCache();
476 : :
477 : : //! Run an internal sanity check on the cache data structure. */
478 : : void SanityCheck() const;
479 : :
480 : : class ResetGuard
481 : : {
482 : : private:
483 : : friend CCoinsViewCache;
484 : : CCoinsViewCache& m_cache;
485 : 8223 : explicit ResetGuard(CCoinsViewCache& cache LIFETIMEBOUND) noexcept : m_cache{cache} {}
486 : :
487 : : public:
488 : : ResetGuard(const ResetGuard&) = delete;
489 : : ResetGuard& operator=(const ResetGuard&) = delete;
490 : : ResetGuard(ResetGuard&&) = delete;
491 : : ResetGuard& operator=(ResetGuard&&) = delete;
492 : :
493 [ + - + - ]: 8223 : ~ResetGuard() { m_cache.Reset(); }
494 : : };
495 : :
496 : : //! Create a scoped guard that will call `Reset()` on this cache when it goes out of scope.
497 [ + - ]: 8223 : [[nodiscard]] ResetGuard CreateResetGuard() noexcept { return ResetGuard{*this}; }
498 : :
499 : : private:
500 : : /**
501 : : * @note this is marked const, but may actually append to `cacheCoins`, increasing
502 : : * memory usage.
503 : : */
504 : : CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
505 : : };
506 : :
507 : : //! Utility function to add all of a transaction's outputs to a cache.
508 : : //! When check is false, this assumes that overwrites are only possible for coinbase transactions.
509 : : //! When check is true, the underlying view may be queried to determine whether an addition is
510 : : //! an overwrite.
511 : : // TODO: pass in a boolean to limit these possible overwrites to known
512 : : // (pre-BIP34) cases.
513 : : void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
514 : :
515 : : //! Utility function to find any unspent output with a given txid.
516 : : //! This function can be quite expensive because in the event of a transaction
517 : : //! which is not found in the cache, it can cause up to MAX_OUTPUTS_PER_BLOCK
518 : : //! lookups to database, so it should be used with care.
519 : : const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
520 : :
521 : : /**
522 : : * This is a minimally invasive approach to shutdown on LevelDB read errors from the
523 : : * chainstate, while keeping user interface out of the common library, which is shared
524 : : * between bitcoind, and bitcoin-qt and non-server tools.
525 : : *
526 : : * Writes do not need similar protection, as failure to write is handled by the caller.
527 : : */
528 : : class CCoinsViewErrorCatcher final : public CCoinsViewBacked
529 : : {
530 : : public:
531 [ + - ]: 216 : explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
532 : :
533 : 1 : void AddReadErrCallback(std::function<void()> f) {
534 [ + - ]: 1 : m_err_callbacks.emplace_back(std::move(f));
535 : 1 : }
536 : :
537 : : std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
538 : : bool HaveCoin(const COutPoint &outpoint) const override;
539 : :
540 : : private:
541 : : /** A list of callbacks to execute upon leveldb read error. */
542 : : std::vector<std::function<void()>> m_err_callbacks;
543 : :
544 : : };
545 : :
546 : : #endif // BITCOIN_COINS_H
|