Bitcoin Core 31.99.0
P2P Digital Currency
coins.h
Go to the documentation of this file.
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>
15#include <serialize.h>
17#include <uint256.h>
18#include <util/check.h>
19#include <util/log.h>
20#include <util/overflow.h>
21#include <util/hasher.h>
22
23#include <cassert>
24#include <cstdint>
25
26#include <atomic>
27#include <functional>
28#include <future>
29#include <memory>
30#include <optional>
31#include <unordered_map>
32#include <utility>
33#include <vector>
34
35class CBlock;
36class ThreadPool;
37
45class Coin
46{
47public:
50
52 bool fCoinBase : 1;
53
55 uint32_t nHeight : 31;
56
58 Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
59 Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
60
61 void Clear() {
62 out.SetNull();
63 fCoinBase = false;
64 nHeight = 0;
65 }
66
68 Coin() : fCoinBase(false), nHeight(0) { }
69
70 bool IsCoinBase() const {
71 return fCoinBase;
72 }
73
74 template<typename Stream>
75 void Serialize(Stream &s) const {
76 assert(!IsSpent());
77 uint32_t code{(uint32_t{nHeight} << 1) | uint32_t{fCoinBase}};
78 ::Serialize(s, VARINT(code));
79 ::Serialize(s, Using<TxOutCompression>(out));
80 }
81
82 template<typename Stream>
83 void Unserialize(Stream &s) {
84 uint32_t code = 0;
85 ::Unserialize(s, VARINT(code));
86 nHeight = code >> 1;
87 fCoinBase = code & 1;
88 ::Unserialize(s, Using<TxOutCompression>(out));
89 }
90
94 bool IsSpent() const {
95 return out.IsNull();
96 }
97
98 size_t DynamicMemoryUsage() const {
100 }
101};
102
103struct CCoinsCacheEntry;
104using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
105
121{
122private:
135 uint8_t m_flags{0};
136
138 static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
139 {
140 Assume(flags & (DIRTY | FRESH));
141 if (!pair.second.m_flags) {
142 Assume(!pair.second.m_prev && !pair.second.m_next);
143 pair.second.m_prev = sentinel.second.m_prev;
144 pair.second.m_next = &sentinel;
145 sentinel.second.m_prev = &pair;
146 pair.second.m_prev->second.m_next = &pair;
147 }
148 Assume(pair.second.m_prev && pair.second.m_next);
149 pair.second.m_flags |= flags;
150 }
151
152public:
153 Coin coin; // The actual cached data.
154
155 enum Flags {
163 DIRTY = (1 << 0),
173 FRESH = (1 << 1),
174 };
175
176 CCoinsCacheEntry() noexcept = default;
177 explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
179 {
180 SetClean();
181 }
182
183 static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
184 static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
185
186 void SetClean() noexcept
187 {
188 if (!m_flags) return;
189 m_next->second.m_prev = m_prev;
190 m_prev->second.m_next = m_next;
191 m_flags = 0;
192 m_prev = m_next = nullptr;
193 }
194 bool IsDirty() const noexcept { return m_flags & DIRTY; }
195 bool IsFresh() const noexcept { return m_flags & FRESH; }
196
198 CoinsCachePair* Next() const noexcept
199 {
201 return m_next;
202 }
203
205 CoinsCachePair* Prev() const noexcept
206 {
208 return m_prev;
209 }
210
212 void SelfRef(CoinsCachePair& pair) noexcept
213 {
214 Assume(&pair.second == this);
215 m_prev = &pair;
216 m_next = &pair;
217 // Set sentinel to DIRTY so we can call Next on it
218 m_flags = DIRTY;
219 }
220};
221
230using CCoinsMap = std::unordered_map<COutPoint,
233 std::equal_to<COutPoint>,
235 sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
236
237using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
238
241{
242public:
243 CCoinsViewCursor(const uint256& in_block_hash) : block_hash(in_block_hash) {}
244 virtual ~CCoinsViewCursor() = default;
245
246 virtual bool GetKey(COutPoint &key) const = 0;
247 virtual bool GetValue(Coin &coin) const = 0;
248
249 virtual bool Valid() const = 0;
250 virtual void Next() = 0;
251
253 const uint256& GetBestBlock() const { return block_hash; }
254private:
256};
257
272{
283 bool will_erase) noexcept
284 : m_dirty_count(dirty_count), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
285
286 inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
287 inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
288
291 {
292 const auto next_entry{current.second.Next()};
293 Assume(TrySub(m_dirty_count, current.second.IsDirty()));
294 // If we are not going to erase the cache, we must still erase spent entries.
295 // Otherwise, clear the state of the entry.
296 if (!m_will_erase) {
297 if (current.second.coin.IsSpent()) {
298 assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin
299 m_map.erase(current.first);
300 } else {
301 current.second.SetClean();
302 }
303 }
304 return next_entry;
305 }
306
307 inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
308 size_t GetDirtyCount() const noexcept { return m_dirty_count; }
309 size_t GetTotalCount() const noexcept { return m_map.size(); }
310private:
315};
316
319{
320public:
322 virtual ~CCoinsView() = default;
323
326 virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const = 0;
327
330 virtual std::optional<Coin> PeekCoin(const COutPoint& outpoint) const = 0;
331
334 virtual bool HaveCoin(const COutPoint& outpoint) const = 0;
335
337 virtual uint256 GetBestBlock() const = 0;
338
343 virtual std::vector<uint256> GetHeadBlocks() const = 0;
344
347 virtual void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) = 0;
348
350 virtual std::unique_ptr<CCoinsViewCursor> Cursor() const = 0;
351
353 virtual size_t EstimateSize() const = 0;
354};
355
358{
359protected:
360 CoinsViewEmpty() = default;
361
362public:
363 static CoinsViewEmpty& Get();
364
367
368 std::optional<Coin> GetCoin(const COutPoint&) const override { return {}; }
369 std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override { return GetCoin(outpoint); }
370 bool HaveCoin(const COutPoint& outpoint) const override { return !!GetCoin(outpoint); }
371 uint256 GetBestBlock() const override { return {}; }
372 std::vector<uint256> GetHeadBlocks() const override { return {}; }
373 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256&) override
374 {
375 for (auto it{cursor.Begin()}; it != cursor.End(); it = cursor.NextAndMaybeErase(*it)) { }
376 }
377 std::unique_ptr<CCoinsViewCursor> Cursor() const override { return {}; }
378 size_t EstimateSize() const override { return 0; }
379};
380
383{
384protected:
386
387public:
388 explicit CCoinsViewBacked(CCoinsView* in_view) : base{Assert(in_view)} {}
389
390 void SetBackend(CCoinsView& in_view) { base = &in_view; }
391
392 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override { return base->GetCoin(outpoint); }
393 std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override { return base->PeekCoin(outpoint); }
394 bool HaveCoin(const COutPoint& outpoint) const override { return base->HaveCoin(outpoint); }
395 uint256 GetBestBlock() const override { return base->GetBestBlock(); }
396 std::vector<uint256> GetHeadBlocks() const override { return base->GetHeadBlocks(); }
397 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override { base->BatchWrite(cursor, block_hash); }
398 std::unique_ptr<CCoinsViewCursor> Cursor() const override { return base->Cursor(); }
399 size_t EstimateSize() const override { return base->EstimateSize(); }
400};
401
402
405{
406private:
407 const bool m_deterministic;
408
409protected:
416 /* The starting sentinel of the flagged entry circular doubly linked list. */
419
420 /* Cached dynamic memory usage for the inner Coin objects. */
421 mutable size_t cachedCoinsUsage{0};
422 /* Running count of dirty Coin cache entries. */
423 mutable size_t m_dirty_count{0};
424
429 virtual void Reset() noexcept;
430
431 /* Fetch the coin from base. Used for cache misses in FetchCoin. */
432 virtual std::optional<Coin> FetchCoinFromBase(const COutPoint& outpoint) const;
433
434public:
435 CCoinsViewCache(CCoinsView* in_base, bool deterministic = false);
436
441
442 // Standard CCoinsView methods
443 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
444 std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override;
445 bool HaveCoin(const COutPoint& outpoint) const override;
446 uint256 GetBestBlock() const override;
447 void SetBestBlock(const uint256& block_hash);
448 void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& block_hash) override;
449 std::unique_ptr<CCoinsViewCursor> Cursor() const override {
450 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
451 }
452
458 bool HaveCoinInCache(const COutPoint &outpoint) const;
459
470 const Coin& AccessCoin(const COutPoint &output) const;
471
476 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
477
485 void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
486
492 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
493
501 virtual void Flush(bool reallocate_cache = true);
502
509 void Sync();
510
515 void Uncache(const COutPoint &outpoint);
516
518 unsigned int GetCacheSize() const;
519
521 size_t GetDirtyCount() const noexcept { return m_dirty_count; }
522
524 size_t DynamicMemoryUsage() const;
525
527 bool HaveInputs(const CTransaction& tx) const;
528
534 void ReallocateCache();
535
537 void SanityCheck() const;
538
540 {
541 private:
544 explicit ResetGuard(CCoinsViewCache& cache LIFETIMEBOUND) noexcept : m_cache{cache} {}
545
546 public:
547 ResetGuard(const ResetGuard&) = delete;
548 ResetGuard& operator=(const ResetGuard&) = delete;
551
553 };
554
556 [[nodiscard]] ResetGuard CreateResetGuard() noexcept { return ResetGuard{*this}; }
557
558private:
563 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
564};
565
625{
626private:
628 std::atomic_uint32_t m_input_head{0};
630 mutable uint32_t m_input_tail{0};
631
635 std::atomic_flag ready{};
640 mutable std::optional<Coin> coin{std::nullopt};
641
642 explicit InputToFetch(const COutPoint& o LIFETIMEBOUND) noexcept : outpoint{o} {}
643
646 InputToFetch(InputToFetch&& other) noexcept : outpoint{other.outpoint}
647 {
648 Assert(!other.coin);
649 Assert(!other.ready.test(std::memory_order_relaxed));
650 }
651 };
653 std::vector<InputToFetch> m_inputs{};
654
661 bool ProcessInput() noexcept
662 {
663 const auto i{m_input_head.fetch_add(1, std::memory_order_relaxed)};
664 if (i >= m_inputs.size()) return false;
665
666 auto& input{m_inputs[i]};
667 input.coin = base->PeekCoin(input.outpoint);
668 // Use release so writing coin above happens before the main thread acquires.
669 Assert(!input.ready.test_and_set(std::memory_order_release));
670 input.ready.notify_one();
671 return true;
672 }
673
676 void StopFetching() noexcept
677 {
678 if (m_futures.empty()) {
679 Assert(m_inputs.empty());
680 Assert(m_input_head.load(std::memory_order_relaxed) == 0);
681 Assert(m_input_tail == 0);
682 return;
683 }
684 // Skip fetching the rest of the inputs by moving the head to the end.
685 m_input_head.store(m_inputs.size(), std::memory_order_relaxed);
686 // Wait for all threads to stop.
687 for (auto& future : m_futures) future.wait();
688 m_futures.clear();
689 m_inputs.clear();
690 m_input_head.store(0, std::memory_order_relaxed);
691 m_input_tail = 0;
692 }
693
694 std::optional<Coin> FetchCoinFromBase(const COutPoint& outpoint) const override
695 {
696 // This assumes ConnectBlock accesses all inputs in the same order as
697 // they are added to m_inputs in StartFetching.
698 if (m_input_tail < m_inputs.size() && m_inputs[m_input_tail].outpoint == outpoint) {
699 // We advance the tail since the input is cached and not accessed through this method again.
700 auto& input{m_inputs[m_input_tail++]};
701 // Wait until the coin is ready to be read. We need acquire so we match the worker thread's release.
702 input.ready.wait(/*old=*/false, std::memory_order_acquire);
703 // We can move the coin since we won't access this input again.
704 return std::move(input.coin);
705 }
706
707 // We will only get here for BIP30 checks, an invalid block, or if the threadpool has not been started.
708 return base->PeekCoin(outpoint);
709 }
710
712 std::shared_ptr<ThreadPool> m_thread_pool;
713 std::vector<std::future<void>> m_futures{};
714
715protected:
716 void Reset() noexcept override
717 {
718 StopFetching();
720 }
721
722public:
723 explicit CoinsViewOverlay(CCoinsView* in_base, std::shared_ptr<ThreadPool> thread_pool,
724 bool deterministic = false) noexcept
725 : CCoinsViewCache{in_base, deterministic}, m_thread_pool{std::move(thread_pool)}
726 {
728 }
729
730 ~CoinsViewOverlay() noexcept override { StopFetching(); }
731
733 [[nodiscard]] ResetGuard StartFetching(const CBlock& block LIFETIMEBOUND) noexcept;
734
735 void Flush(bool reallocate_cache = true) override
736 {
737 if (!Assume(AllInputsConsumed())) {
738 LogWarning("Block %s input prevout prefetch queue was not fully consumed; inputs were accessed out of order, so prefetching degraded to serial lookups for this block.", GetBestBlock().ToString());
739 }
740 StopFetching();
741 CCoinsViewCache::Flush(reallocate_cache);
742 }
743
745 bool AllInputsConsumed() const noexcept { return m_input_tail == m_inputs.size(); }
746};
747
752// TODO: pass in a boolean to limit these possible overwrites to known
753// (pre-BIP34) cases.
754void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
755
760const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
761
770{
771public:
773
774 void AddReadErrCallback(std::function<void()> f) {
775 m_err_callbacks.emplace_back(std::move(f));
776 }
777
778 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
779 bool HaveCoin(const COutPoint& outpoint) const override;
780 std::optional<Coin> PeekCoin(const COutPoint& outpoint) const override;
781
782private:
784 std::vector<std::function<void()>> m_err_callbacks;
785
786};
787
788#endif // BITCOIN_COINS_H
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:530
#define Assert(val)
Identity function.
Definition: check.h:116
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
Definition: block.h:74
CCoinsView backed by another CCoinsView.
Definition: coins.h:383
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.h:394
size_t EstimateSize() const override
Estimate database size.
Definition: coins.h:399
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.h:395
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
Definition: coins.h:393
CCoinsViewBacked(CCoinsView *in_view)
Definition: coins.h:388
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.h:392
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state. Implementations may return nullptr.
Definition: coins.h:398
CCoinsView * base
Definition: coins.h:385
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.h:397
void SetBackend(CCoinsView &in_view)
Definition: coins.h:390
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.h:396
CCoinsViewCache & m_cache
Definition: coins.h:543
ResetGuard(const ResetGuard &)=delete
ResetGuard & operator=(ResetGuard &&)=delete
ResetGuard(ResetGuard &&)=delete
ResetGuard & operator=(const ResetGuard &)=delete
ResetGuard(CCoinsViewCache &cache LIFETIMEBOUND) noexcept
Definition: coins.h:544
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:405
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:277
const bool m_deterministic
Definition: coins.h:407
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state. Implementations may return nullptr.
Definition: coins.h:449
size_t GetDirtyCount() const noexcept
Number of dirty cache entries (transaction outputs)
Definition: coins.h:521
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:415
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:137
uint256 m_block_hash
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:414
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
Definition: coins.h:556
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:296
bool HaveInputs(const CTransaction &tx) const
Check whether all prevouts of the transaction are present in the UTXO set represented by this view.
Definition: coins.cpp:315
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:73
virtual std::optional< Coin > FetchCoinFromBase(const COutPoint &outpoint) const
Definition: coins.cpp:47
size_t m_dirty_count
Definition: coins.h:423
virtual void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:265
void SetBestBlock(const uint256 &block_hash)
Definition: coins.cpp:189
virtual void Reset() noexcept
Discard all modifications made to this cache without flushing to the base view.
Definition: coins.cpp:288
unsigned int GetCacheSize() const
Size of the cache (in number of transaction outputs)
Definition: coins.cpp:311
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:183
size_t cachedCoinsUsage
Definition: coins.h:421
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:52
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:178
CoinsCachePair m_sentinel
Definition: coins.h:417
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:43
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:194
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
Definition: coins.cpp:28
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:116
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:172
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition: coins.cpp:337
CCoinsMap cacheCoins
Definition: coins.h:418
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:67
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:163
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:327
Cursor for iterating over CoinsView state.
Definition: coins.h:241
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:253
virtual void Next()=0
virtual bool Valid() const =0
uint256 block_hash
Definition: coins.h:255
CCoinsViewCursor(const uint256 &in_block_hash)
Definition: coins.h:243
virtual ~CCoinsViewCursor()=default
virtual bool GetKey(COutPoint &key) const =0
virtual bool GetValue(Coin &coin) const =0
This is a minimally invasive approach to shutdown on LevelDB read errors from the chainstate,...
Definition: coins.h:770
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:774
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:439
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:784
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:444
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:772
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
Definition: coins.cpp:449
Pure abstract view on the open txout dataset.
Definition: coins.h:319
virtual size_t EstimateSize() const =0
Estimate database size.
virtual std::vector< uint256 > GetHeadBlocks() const =0
Retrieve the range of blocks that may have been only partially written.
virtual std::optional< Coin > PeekCoin(const COutPoint &outpoint) const =0
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const =0
Retrieve the Coin (unspent transaction output) for a given outpoint.
virtual ~CCoinsView()=default
As we use CCoinsViews polymorphically, have a virtual destructor.
virtual void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &block_hash)=0
Do a bulk modification (multiple Coin changes + BestBlock change).
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const =0
Get a cursor to iterate over the whole state. Implementations may return nullptr.
virtual bool HaveCoin(const COutPoint &outpoint) const =0
Just check whether a given outpoint is unspent.
virtual uint256 GetBestBlock() const =0
Retrieve the block hash whose state this CCoinsView currently represents.
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:281
An output of a transaction.
Definition: transaction.h:140
CScript scriptPubKey
Definition: transaction.h:143
void SetNull()
Definition: transaction.h:154
bool IsNull() const
Definition: transaction.h:160
A UTXO entry.
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:70
void Clear()
Definition: coins.h:61
void Serialize(Stream &s) const
Definition: coins.h:75
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:58
Coin()
empty constructor
Definition: coins.h:68
CTxOut out
unspent transaction output
Definition: coins.h:49
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:94
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:59
bool fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:52
void Unserialize(Stream &s)
Definition: coins.h:83
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:55
size_t DynamicMemoryUsage() const
Definition: coins.h:98
Noop coins view.
Definition: coins.h:358
CoinsViewEmpty & operator=(const CoinsViewEmpty &)=delete
size_t EstimateSize() const override
Estimate database size.
Definition: coins.h:378
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.h:373
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.h:370
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.h:371
CoinsViewEmpty()=default
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state. Implementations may return nullptr.
Definition: coins.h:377
std::optional< Coin > PeekCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint, without caching results.
Definition: coins.h:369
std::optional< Coin > GetCoin(const COutPoint &) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.h:368
CoinsViewEmpty(const CoinsViewEmpty &)=delete
static CoinsViewEmpty & Get()
Definition: coins.cpp:22
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.h:372
CCoinsViewCache subclass that asynchronously fetches most block input prevouts in parallel during Con...
Definition: coins.h:625
uint32_t m_input_tail
The latest input not yet accessed by a consumer. Only the main thread increments this.
Definition: coins.h:630
void StopFetching() noexcept
Stop all worker threads and clear fetching data.
Definition: coins.h:676
std::vector< std::future< void > > m_futures
Definition: coins.h:713
std::atomic_uint32_t m_input_head
The latest input not yet being fetched. Workers atomically increment this when fetching.
Definition: coins.h:628
CoinsViewOverlay(CCoinsView *in_base, std::shared_ptr< ThreadPool > thread_pool, bool deterministic=false) noexcept
Definition: coins.h:723
std::shared_ptr< ThreadPool > m_thread_pool
Non-null. May have zero workers when input fetching is disabled.
Definition: coins.h:712
bool ProcessInput() noexcept
Claim and fetch the next input in the queue.
Definition: coins.h:661
~CoinsViewOverlay() noexcept override
Definition: coins.h:730
ResetGuard StartFetching(const CBlock &block LIFETIMEBOUND) noexcept
Start fetching inputs from block.
Definition: coins.cpp:369
bool AllInputsConsumed() const noexcept
Verify that all parallel fetched input prevouts have been consumed.
Definition: coins.h:745
std::optional< Coin > FetchCoinFromBase(const COutPoint &outpoint) const override
Definition: coins.h:694
void Reset() noexcept override
Discard all modifications made to this cache without flushing to the base view.
Definition: coins.h:716
void Flush(bool reallocate_cache=true) override
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.h:735
std::vector< InputToFetch > m_inputs
Must only be mutated when m_futures is empty. Elements may be mutated when m_futures is not empty.
Definition: coins.h:653
Forwards all allocations/deallocations to the PoolResource.
Definition: pool.h:291
Fixed-size thread pool for running arbitrary tasks concurrently.
Definition: threadpool.h:48
256-bit opaque blob.
Definition: uint256.h:196
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check=false)
Utility function to add all of a transaction's outputs to a cache.
Definition: coins.cpp:126
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:104
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< CoinsCachePair, sizeof(CoinsCachePair)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
Definition: coins.h:235
const Coin & AccessByTxid(const CCoinsViewCache &cache, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:410
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:237
#define LogWarning(...)
Definition: log.h:126
unsigned int nHeight
T check(T ptr)
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:31
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:249
constexpr bool TrySub(T &i, const U j) noexcept
Definition: overflow.h:36
#define VARINT(obj)
Definition: serialize.h:494
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:121
Coin coin
Definition: coins.h:153
CCoinsCacheEntry() noexcept=default
Flags
Definition: coins.h:155
@ FRESH
FRESH means the parent cache does not have this coin or that it is a spent coin in the parent cache.
Definition: coins.h:173
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:163
void SetClean() noexcept
Definition: coins.h:186
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:184
uint8_t m_flags
Definition: coins.h:135
static void AddFlags(uint8_t flags, CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Adding a flag requires a reference to the sentinel of the flagged pair linked list.
Definition: coins.h:138
CoinsCachePair * m_next
Definition: coins.h:134
bool IsFresh() const noexcept
Definition: coins.h:195
~CCoinsCacheEntry()
Definition: coins.h:178
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:183
void SelfRef(CoinsCachePair &pair) noexcept
Only use this for initializing the linked list sentinel.
Definition: coins.h:212
bool IsDirty() const noexcept
Definition: coins.h:194
CoinsCachePair * m_prev
These are used to create a doubly linked list of flagged entries.
Definition: coins.h:133
CoinsCachePair * Next() const noexcept
Only call Next when this entry is DIRTY, FRESH, or both.
Definition: coins.h:198
CoinsCachePair * Prev() const noexcept
Only call Prev when this entry is DIRTY, FRESH, or both.
Definition: coins.h:205
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:272
CoinsCachePair & m_sentinel
Definition: coins.h:312
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:290
size_t & m_dirty_count
Definition: coins.h:311
size_t GetTotalCount() const noexcept
Definition: coins.h:309
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:307
size_t GetDirtyCount() const noexcept
Definition: coins.h:308
CCoinsMap & m_map
Definition: coins.h:313
CoinsCachePair * Begin() const noexcept
Definition: coins.h:286
CoinsViewCacheCursor(size_t &dirty_count LIFETIMEBOUND, CoinsCachePair &sentinel LIFETIMEBOUND, CCoinsMap &map LIFETIMEBOUND, bool will_erase) noexcept
If will_erase is not set, iterating through the cursor will erase spent coins from the map,...
Definition: coins.h:280
CoinsCachePair * End() const noexcept
Definition: coins.h:287
The inputs of the block which is being fetched.
Definition: coins.h:633
InputToFetch(InputToFetch &&other) noexcept
Move ctor is required for resizing m_inputs in StartFetching.
Definition: coins.h:646
std::atomic_flag ready
Workers set this after setting the coin. The main thread tests this before reading the coin.
Definition: coins.h:635
InputToFetch(const COutPoint &o LIFETIMEBOUND) noexcept
Definition: coins.h:642
std::optional< Coin > coin
The coin that workers will fetch and main thread will insert into cache.
Definition: coins.h:640
const COutPoint & outpoint
The outpoint of the input to fetch.
Definition: coins.h:637
assert(!tx.IsCoinBase())