Bitcoin Core 28.0.0
P2P Digital Currency
Loading...
Searching...
No Matches
coins.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2022 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 <compressor.h>
10#include <core_memusage.h>
11#include <memusage.h>
13#include <serialize.h>
15#include <uint256.h>
16#include <util/check.h>
17#include <util/hasher.h>
18
19#include <assert.h>
20#include <stdint.h>
21
22#include <functional>
23#include <unordered_map>
24
32class Coin
33{
34public:
37
39 unsigned int fCoinBase : 1;
40
42 uint32_t nHeight : 31;
43
45 Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
46 Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
47
48 void Clear() {
49 out.SetNull();
50 fCoinBase = false;
51 nHeight = 0;
52 }
53
55 Coin() : fCoinBase(false), nHeight(0) { }
56
57 bool IsCoinBase() const {
58 return fCoinBase;
59 }
60
61 template<typename Stream>
62 void Serialize(Stream &s) const {
63 assert(!IsSpent());
64 uint32_t code = nHeight * uint32_t{2} + fCoinBase;
65 ::Serialize(s, VARINT(code));
67 }
68
69 template<typename Stream>
70 void Unserialize(Stream &s) {
71 uint32_t code = 0;
72 ::Unserialize(s, VARINT(code));
73 nHeight = code >> 1;
74 fCoinBase = code & 1;
76 }
77
81 bool IsSpent() const {
82 return out.IsNull();
83 }
84
85 size_t DynamicMemoryUsage() const {
87 }
88};
89
90struct CCoinsCacheEntry;
91using CoinsCachePair = std::pair<const COutPoint, CCoinsCacheEntry>;
92
109{
110private:
129 uint8_t m_flags{0};
130
131public:
132 Coin coin; // The actual cached data.
133
134 enum Flags {
142 DIRTY = (1 << 0),
152 FRESH = (1 << 1),
153 };
154
155 CCoinsCacheEntry() noexcept = default;
156 explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
158 {
159 ClearFlags();
160 }
161
165 inline void AddFlags(uint8_t flags, CoinsCachePair& self, CoinsCachePair& sentinel) noexcept
166 {
167 Assume(&self.second == this);
168 if (!m_flags && flags) {
169 m_prev = sentinel.second.m_prev;
170 m_next = &sentinel;
171 sentinel.second.m_prev = &self;
172 m_prev->second.m_next = &self;
173 }
174 m_flags |= flags;
175 }
176 inline void ClearFlags() noexcept
177 {
178 if (!m_flags) return;
179 m_next->second.m_prev = m_prev;
180 m_prev->second.m_next = m_next;
181 m_flags = 0;
182 }
183 inline uint8_t GetFlags() const noexcept { return m_flags; }
184 inline bool IsDirty() const noexcept { return m_flags & DIRTY; }
185 inline bool IsFresh() const noexcept { return m_flags & FRESH; }
186
188 inline CoinsCachePair* Next() const noexcept {
190 return m_next;
191 }
192
194 inline CoinsCachePair* Prev() const noexcept {
196 return m_prev;
197 }
198
200 inline void SelfRef(CoinsCachePair& self) noexcept
201 {
202 Assume(&self.second == this);
203 m_prev = &self;
204 m_next = &self;
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{
271 bool will_erase) noexcept
272 : m_usage(usage), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
273
274 inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
275 inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
276
279 {
280 const auto next_entry{current.second.Next()};
281 // If we are not going to erase the cache, we must still erase spent entries.
282 // Otherwise clear the flags on the entry.
283 if (!m_will_erase) {
284 if (current.second.coin.IsSpent()) {
285 m_usage -= current.second.coin.DynamicMemoryUsage();
286 m_map.erase(current.first);
287 } else {
288 current.second.ClearFlags();
289 }
290 }
291 return next_entry;
292 }
293
294 inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
295private:
296 size_t& m_usage;
300};
301
304{
305public:
310 virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
311
313 virtual bool HaveCoin(const COutPoint &outpoint) const;
314
316 virtual uint256 GetBestBlock() const;
317
322 virtual std::vector<uint256> GetHeadBlocks() const;
323
326 virtual bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
327
329 virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
330
332 virtual ~CCoinsView() = default;
333
335 virtual size_t EstimateSize() const { return 0; }
336};
337
338
341{
342protected:
344
345public:
347 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
348 bool HaveCoin(const COutPoint &outpoint) const override;
349 uint256 GetBestBlock() const override;
350 std::vector<uint256> GetHeadBlocks() const override;
351 void SetBackend(CCoinsView &viewIn);
352 bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
353 std::unique_ptr<CCoinsViewCursor> Cursor() const override;
354 size_t EstimateSize() const override;
355};
356
357
360{
361private:
362 const bool m_deterministic;
363
364protected:
371 /* The starting sentinel of the flagged entry circular doubly linked list. */
374
375 /* Cached dynamic memory usage for the inner Coin objects. */
376 mutable size_t cachedCoinsUsage{0};
377
378public:
379 CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
380
385
386 // Standard CCoinsView methods
387 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
388 bool HaveCoin(const COutPoint &outpoint) const override;
389 uint256 GetBestBlock() const override;
390 void SetBestBlock(const uint256 &hashBlock);
391 bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
392 std::unique_ptr<CCoinsViewCursor> Cursor() const override {
393 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
394 }
395
401 bool HaveCoinInCache(const COutPoint &outpoint) const;
402
413 const Coin& AccessCoin(const COutPoint &output) const;
414
419 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
420
428 void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
429
435 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
436
443 bool Flush();
444
452 bool Sync();
453
458 void Uncache(const COutPoint &outpoint);
459
461 unsigned int GetCacheSize() const;
462
464 size_t DynamicMemoryUsage() const;
465
467 bool HaveInputs(const CTransaction& tx) const;
468
474 void ReallocateCache();
475
477 void SanityCheck() const;
478
479private:
484 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
485};
486
491// TODO: pass in a boolean to limit these possible overwrites to known
492// (pre-BIP34) cases.
493void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
494
499const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
500
509{
510public:
512
513 void AddReadErrCallback(std::function<void()> f) {
514 m_err_callbacks.emplace_back(std::move(f));
515 }
516
517 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
518 bool HaveCoin(const COutPoint &outpoint) const override;
519
520private:
522 std::vector<std::function<void()>> m_err_callbacks;
523
524};
525
526#endif // BITCOIN_COINS_H
#define LIFETIMEBOUND
Definition attributes.h:16
int flags
#define Assume(val)
Assume is the identity function.
Definition check.h:89
CCoinsView backed by another CCoinsView.
Definition coins.h:341
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition coins.cpp:26
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition coins.cpp:25
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition coins.cpp:32
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition coins.cpp:27
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition coins.cpp:30
void SetBackend(CCoinsView &viewIn)
Definition coins.cpp:29
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition coins.cpp:31
CCoinsView * base
Definition coins.h:343
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition coins.cpp:28
CCoinsViewBacked(CCoinsView *viewIn)
Definition coins.cpp:24
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition coins.h:360
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition coins.cpp:34
const bool m_deterministic
Definition coins.h:362
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition coins.h:369
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition coins.h:392
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition coins.h:370
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition coins.cpp:132
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition coins.cpp:278
CCoinsViewCache(const CCoinsViewCache &)=delete
By deleting the copy constructor, we prevent accidentally using it when one intends to create a cache...
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:297
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition coins.cpp:70
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition coins.cpp:185
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition coins.cpp:293
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition coins.cpp:175
size_t cachedCoinsUsage
Definition coins.h:376
void SetBestBlock(const uint256 &hashBlock)
Definition coins.cpp:181
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition coins.cpp:45
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition coins.cpp:61
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition coins.cpp:170
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition coins.cpp:254
CoinsCachePair m_sentinel
Definition coins.h:372
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition coins.cpp:41
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition coins.cpp:265
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition coins.cpp:110
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition coins.cpp:165
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition coins.cpp:319
CCoinsMap cacheCoins
Definition coins.h:373
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition coins.cpp:156
void ReallocateCache()
Force a reallocation of the cache map.
Definition coins.cpp:309
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:509
void AddReadErrCallback(std::function< void()> f)
Definition coins.h:513
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition coins.h:522
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition coins.cpp:384
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition coins.cpp:388
CCoinsViewErrorCatcher(CCoinsView *view)
Definition coins.h:511
Abstract view on the open txout dataset.
Definition coins.h:304
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition coins.cpp:12
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition coins.cpp:14
virtual ~CCoinsView()=default
As we use CCoinsViews polymorphically, have a virtual destructor.
virtual bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition coins.cpp:15
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition coins.cpp:18
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition coins.h:335
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition coins.cpp:16
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition coins.cpp:13
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.
An output of a transaction.
CScript scriptPubKey
void SetNull()
bool IsNull() const
A UTXO entry.
Definition coins.h:33
bool IsCoinBase() const
Definition coins.h:57
void Clear()
Definition coins.h:48
void Serialize(Stream &s) const
Definition coins.h:62
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition coins.h:45
Coin()
empty constructor
Definition coins.h:55
CTxOut out
unspent transaction output
Definition coins.h:36
bool IsSpent() const
Either this coin never existed (see e.g.
Definition coins.h:81
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition coins.h:46
void Unserialize(Stream &s)
Definition coins.h:70
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition coins.h:42
size_t DynamicMemoryUsage() const
Definition coins.h:85
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition coins.h:39
Forwards all allocations/deallocations to the PoolResource.
Definition pool.h:277
256-bit opaque blob.
Definition uint256.h:178
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:121
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition coins.h:91
const Coin & AccessByTxid(const CCoinsViewCache &cache, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition coins.cpp:355
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:218
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition coins.h:225
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition memusage.h:30
#define VARINT(obj)
Definition serialize.h:498
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition serialize.h:495
A Coin in one level of the coins database caching hierarchy.
Definition coins.h:109
Coin coin
Definition coins.h:132
CCoinsCacheEntry() noexcept=default
Flags
Definition coins.h:134
@ 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:152
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition coins.h:142
uint8_t m_flags
Definition coins.h:129
CoinsCachePair * m_next
Definition coins.h:128
bool IsFresh() const noexcept
Definition coins.h:185
~CCoinsCacheEntry()
Definition coins.h:157
uint8_t GetFlags() const noexcept
Definition coins.h:183
bool IsDirty() const noexcept
Definition coins.h:184
void AddFlags(uint8_t flags, CoinsCachePair &self, CoinsCachePair &sentinel) noexcept
Adding a flag also requires a self reference to the pair that contains this entry in the CCoinsCache ...
Definition coins.h:165
CoinsCachePair * m_prev
These are used to create a doubly linked list of flagged entries.
Definition coins.h:127
CoinsCachePair * Next() const noexcept
Only call Next when this entry is DIRTY, FRESH, or both.
Definition coins.h:188
CoinsCachePair * Prev() const noexcept
Only call Prev when this entry is DIRTY, FRESH, or both.
Definition coins.h:194
void ClearFlags() noexcept
Definition coins.h:176
void SelfRef(CoinsCachePair &self) noexcept
Only use this for initializing the linked list sentinel.
Definition coins.h:200
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition coins.h:260
CoinsCachePair & m_sentinel
Definition coins.h:297
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition coins.h:278
CoinsViewCacheCursor(size_t &usage 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:268
bool WillErase(CoinsCachePair &current) const noexcept
Definition coins.h:294
CCoinsMap & m_map
Definition coins.h:298
CoinsCachePair * Begin() const noexcept
Definition coins.h:274
size_t & m_usage
Definition coins.h:296
CoinsCachePair * End() const noexcept
Definition coins.h:275
assert(!tx.IsCoinBase())