Bitcoin Core 30.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>
14#include <serialize.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
33class Coin
34{
35public:
38
40 unsigned int fCoinBase : 1;
41
43 uint32_t nHeight : 31;
44
46 Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
47 Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
48
49 void Clear() {
50 out.SetNull();
51 fCoinBase = false;
52 nHeight = 0;
53 }
54
56 Coin() : fCoinBase(false), nHeight(0) { }
57
58 bool IsCoinBase() const {
59 return fCoinBase;
60 }
61
62 template<typename Stream>
63 void Serialize(Stream &s) const {
64 assert(!IsSpent());
65 uint32_t code = nHeight * uint32_t{2} + fCoinBase;
66 ::Serialize(s, VARINT(code));
67 ::Serialize(s, Using<TxOutCompression>(out));
68 }
69
70 template<typename Stream>
71 void Unserialize(Stream &s) {
72 uint32_t code = 0;
73 ::Unserialize(s, VARINT(code));
74 nHeight = code >> 1;
75 fCoinBase = code & 1;
76 ::Unserialize(s, Using<TxOutCompression>(out));
77 }
78
82 bool IsSpent() const {
83 return out.IsNull();
84 }
85
86 size_t DynamicMemoryUsage() const {
88 }
89};
90
91struct CCoinsCacheEntry;
92using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
93
109{
110private:
123 uint8_t m_flags{0};
124
126 static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
127 {
128 Assume(flags & (DIRTY | FRESH));
129 if (!pair.second.m_flags) {
130 Assume(!pair.second.m_prev && !pair.second.m_next);
131 pair.second.m_prev = sentinel.second.m_prev;
132 pair.second.m_next = &sentinel;
133 sentinel.second.m_prev = &pair;
134 pair.second.m_prev->second.m_next = &pair;
135 }
136 Assume(pair.second.m_prev && pair.second.m_next);
137 pair.second.m_flags |= flags;
138 }
139
140public:
141 Coin coin; // The actual cached data.
142
143 enum Flags {
151 DIRTY = (1 << 0),
161 FRESH = (1 << 1),
162 };
163
164 CCoinsCacheEntry() noexcept = default;
165 explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
167 {
168 SetClean();
169 }
170
171 static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
172 static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
173
174 void SetClean() noexcept
175 {
176 if (!m_flags) return;
177 m_next->second.m_prev = m_prev;
178 m_prev->second.m_next = m_next;
179 m_flags = 0;
180 m_prev = m_next = nullptr;
181 }
182 bool IsDirty() const noexcept { return m_flags & DIRTY; }
183 bool IsFresh() const noexcept { return m_flags & FRESH; }
184
186 CoinsCachePair* Next() const noexcept
187 {
189 return m_next;
190 }
191
193 CoinsCachePair* Prev() const noexcept
194 {
196 return m_prev;
197 }
198
200 void SelfRef(CoinsCachePair& pair) noexcept
201 {
202 Assume(&pair.second == this);
203 m_prev = &pair;
204 m_next = &pair;
205 // Set sentinel to DIRTY so we can call Next on it
206 m_flags = DIRTY;
207 }
208};
209
218using CCoinsMap = std::unordered_map<COutPoint,
221 std::equal_to<COutPoint>,
223 sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
224
225using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
226
229{
230public:
231 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
232 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
241 const uint256 &GetBestBlock() const { return hashBlock; }
242private:
244};
245
260{
270 bool will_erase) noexcept
271 : m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
272
273 inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
274 inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
275
278 {
279 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 if (!m_will_erase) {
283 if (current.second.coin.IsSpent()) {
284 assert(current.second.coin.DynamicMemoryUsage() == 0); // scriptPubKey was already cleared in SpendCoin
285 m_map.erase(current.first);
286 } else {
287 current.second.SetClean();
288 }
289 }
290 return next_entry;
291 }
292
293 inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
294private:
298};
299
302{
303public:
305 virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const;
306
308 virtual bool HaveCoin(const COutPoint &outpoint) const;
309
311 virtual uint256 GetBestBlock() const;
312
317 virtual std::vector<uint256> GetHeadBlocks() const;
318
321 virtual void BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
322
324 virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
325
327 virtual ~CCoinsView() = default;
328
330 virtual size_t EstimateSize() const { return 0; }
331};
332
333
336{
337protected:
339
340public:
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
355{
356private:
357 const bool m_deterministic;
358
359protected:
366 /* The starting sentinel of the flagged entry circular doubly linked list. */
369
370 /* Cached dynamic memory usage for the inner Coin objects. */
371 mutable size_t cachedCoinsUsage{0};
372
377 void Reset() noexcept;
378
379public:
380 CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
381
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 std::unique_ptr<CCoinsViewCursor> Cursor() const override {
394 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
395 }
396
402 bool HaveCoinInCache(const COutPoint &outpoint) const;
403
414 const Coin& AccessCoin(const COutPoint &output) const;
415
420 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
421
429 void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
430
436 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
437
445 void Flush(bool reallocate_cache = true);
446
453 void Sync();
454
459 void Uncache(const COutPoint &outpoint);
460
462 unsigned int GetCacheSize() const;
463
465 size_t DynamicMemoryUsage() const;
466
468 bool HaveInputs(const CTransaction& tx) const;
469
475 void ReallocateCache();
476
478 void SanityCheck() const;
479
481 {
482 private:
485 explicit ResetGuard(CCoinsViewCache& cache LIFETIMEBOUND) noexcept : m_cache{cache} {}
486
487 public:
488 ResetGuard(const ResetGuard&) = delete;
489 ResetGuard& operator=(const ResetGuard&) = delete;
492
494 };
495
497 [[nodiscard]] ResetGuard CreateResetGuard() noexcept { return ResetGuard{*this}; }
498
499private:
504 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
505};
506
511// TODO: pass in a boolean to limit these possible overwrites to known
512// (pre-BIP34) cases.
513void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
514
519const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
520
529{
530public:
532
533 void AddReadErrCallback(std::function<void()> f) {
534 m_err_callbacks.emplace_back(std::move(f));
535 }
536
537 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
538 bool HaveCoin(const COutPoint &outpoint) const override;
539
540private:
542 std::vector<std::function<void()>> m_err_callbacks;
543
544};
545
546#endif // BITCOIN_COINS_H
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:529
#define Assume(val)
Assume is the identity function.
Definition: check.h:125
CCoinsView backed by another CCoinsView.
Definition: coins.h:336
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:38
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:34
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:40
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:35
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:33
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:37
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:39
CCoinsView * base
Definition: coins.h:338
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:36
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:32
CCoinsViewCache & m_cache
Definition: coins.h:484
ResetGuard(const ResetGuard &)=delete
ResetGuard & operator=(ResetGuard &&)=delete
ResetGuard(ResetGuard &&)=delete
ResetGuard & operator=(const ResetGuard &)=delete
ResetGuard(CCoinsViewCache &cache LIFETIMEBOUND) noexcept
Definition: coins.h:485
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:355
void Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:265
const bool m_deterministic
Definition: coins.h:357
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:364
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:393
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:365
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:135
ResetGuard CreateResetGuard() noexcept
Create a scoped guard that will call Reset() on this cache when it goes out of scope.
Definition: coins.h:497
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:282
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:301
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:74
void Flush(bool reallocate_cache=true)
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:254
void Reset() noexcept
Discard all modifications made to this cache without flushing to the base view.
Definition: coins.cpp:275
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:297
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:178
size_t cachedCoinsUsage
Definition: coins.h:371
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:184
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:53
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:173
CoinsCachePair m_sentinel
Definition: coins.h:367
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:49
void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:188
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:115
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:168
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition: coins.cpp:323
CCoinsMap cacheCoins
Definition: coins.h:368
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:68
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:159
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:313
Cursor for iterating over CoinsView state.
Definition: coins.h:229
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:241
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:231
uint256 hashBlock
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:529
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:533
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:387
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:542
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:392
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:531
Abstract view on the open txout dataset.
Definition: coins.h:302
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:17
virtual void BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:20
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:19
virtual ~CCoinsView()=default
As we use CCoinsViews polymorphically, have a virtual destructor.
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:330
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:25
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:18
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:34
bool IsCoinBase() const
Definition: coins.h:58
void Clear()
Definition: coins.h:49
void Serialize(Stream &s) const
Definition: coins.h:63
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:46
Coin()
empty constructor
Definition: coins.h:56
CTxOut out
unspent transaction output
Definition: coins.h:37
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:82
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:47
void Unserialize(Stream &s)
Definition: coins.h:71
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:43
size_t DynamicMemoryUsage() const
Definition: coins.h:86
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:40
Forwards all allocations/deallocations to the PoolResource.
Definition: pool.h:290
256-bit opaque blob.
Definition: uint256.h:195
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:124
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:92
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:223
const Coin & AccessByTxid(const CCoinsViewCache &cache, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:358
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:225
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
#define VARINT(obj)
Definition: serialize.h:491
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:109
Coin coin
Definition: coins.h:141
CCoinsCacheEntry() noexcept=default
Flags
Definition: coins.h:143
@ 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:161
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:151
void SetClean() noexcept
Definition: coins.h:174
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:172
uint8_t m_flags
Definition: coins.h:123
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:126
CoinsCachePair * m_next
Definition: coins.h:122
bool IsFresh() const noexcept
Definition: coins.h:183
~CCoinsCacheEntry()
Definition: coins.h:166
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:171
void SelfRef(CoinsCachePair &pair) noexcept
Only use this for initializing the linked list sentinel.
Definition: coins.h:200
bool IsDirty() const noexcept
Definition: coins.h:182
CoinsCachePair * m_prev
These are used to create a doubly linked list of flagged entries.
Definition: coins.h:121
CoinsCachePair * Next() const noexcept
Only call Next when this entry is DIRTY, FRESH, or both.
Definition: coins.h:186
CoinsCachePair * Prev() const noexcept
Only call Prev when this entry is DIRTY, FRESH, or both.
Definition: coins.h:193
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:260
CoinsCachePair & m_sentinel
Definition: coins.h:295
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:277
CoinsViewCacheCursor(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:268
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:293
CCoinsMap & m_map
Definition: coins.h:296
CoinsCachePair * Begin() const noexcept
Definition: coins.h:273
CoinsCachePair * End() const noexcept
Definition: coins.h:274
assert(!tx.IsCoinBase())