Bitcoin Core 28.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-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));
66 ::Serialize(s, Using<TxOutCompression>(out));
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;
75 ::Unserialize(s, Using<TxOutCompression>(out));
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
132 static void AddFlags(uint8_t flags, CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept
133 {
134 Assume(flags & (DIRTY | FRESH));
135 if (!pair.second.m_flags) {
136 Assume(!pair.second.m_prev && !pair.second.m_next);
137 pair.second.m_prev = sentinel.second.m_prev;
138 pair.second.m_next = &sentinel;
139 sentinel.second.m_prev = &pair;
140 pair.second.m_prev->second.m_next = &pair;
141 }
142 Assume(pair.second.m_prev && pair.second.m_next);
143 pair.second.m_flags |= flags;
144 }
145
146public:
147 Coin coin; // The actual cached data.
148
149 enum Flags {
157 DIRTY = (1 << 0),
167 FRESH = (1 << 1),
168 };
169
170 CCoinsCacheEntry() noexcept = default;
171 explicit CCoinsCacheEntry(Coin&& coin_) noexcept : coin(std::move(coin_)) {}
173 {
174 SetClean();
175 }
176
177 static void SetDirty(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(DIRTY, pair, sentinel); }
178 static void SetFresh(CoinsCachePair& pair, CoinsCachePair& sentinel) noexcept { AddFlags(FRESH, pair, sentinel); }
179
180 void SetClean() noexcept
181 {
182 if (!m_flags) return;
183 m_next->second.m_prev = m_prev;
184 m_prev->second.m_next = m_next;
185 m_flags = 0;
186 m_prev = m_next = nullptr;
187 }
188 bool IsDirty() const noexcept { return m_flags & DIRTY; }
189 bool IsFresh() const noexcept { return m_flags & FRESH; }
190
192 CoinsCachePair* Next() const noexcept
193 {
195 return m_next;
196 }
197
199 CoinsCachePair* Prev() const noexcept
200 {
202 return m_prev;
203 }
204
206 void SelfRef(CoinsCachePair& pair) noexcept
207 {
208 Assume(&pair.second == this);
209 m_prev = &pair;
210 m_next = &pair;
211 // Set sentinel to DIRTY so we can call Next on it
212 m_flags = DIRTY;
213 }
214};
215
224using CCoinsMap = std::unordered_map<COutPoint,
227 std::equal_to<COutPoint>,
229 sizeof(CoinsCachePair) + sizeof(void*) * 4>>;
230
231using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
232
235{
236public:
237 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
238 virtual ~CCoinsViewCursor() = default;
239
240 virtual bool GetKey(COutPoint &key) const = 0;
241 virtual bool GetValue(Coin &coin) const = 0;
242
243 virtual bool Valid() const = 0;
244 virtual void Next() = 0;
245
247 const uint256 &GetBestBlock() const { return hashBlock; }
248private:
250};
251
266{
277 bool will_erase) noexcept
278 : m_usage(usage), m_sentinel(sentinel), m_map(map), m_will_erase(will_erase) {}
279
280 inline CoinsCachePair* Begin() const noexcept { return m_sentinel.second.Next(); }
281 inline CoinsCachePair* End() const noexcept { return &m_sentinel; }
282
285 {
286 const auto next_entry{current.second.Next()};
287 // If we are not going to erase the cache, we must still erase spent entries.
288 // Otherwise, clear the state of the entry.
289 if (!m_will_erase) {
290 if (current.second.coin.IsSpent()) {
291 m_usage -= current.second.coin.DynamicMemoryUsage();
292 m_map.erase(current.first);
293 } else {
294 current.second.SetClean();
295 }
296 }
297 return next_entry;
298 }
299
300 inline bool WillErase(CoinsCachePair& current) const noexcept { return m_will_erase || current.second.coin.IsSpent(); }
301private:
302 size_t& m_usage;
306};
307
310{
311public:
313 virtual std::optional<Coin> GetCoin(const COutPoint& outpoint) const;
314
316 virtual bool HaveCoin(const COutPoint &outpoint) const;
317
319 virtual uint256 GetBestBlock() const;
320
325 virtual std::vector<uint256> GetHeadBlocks() const;
326
329 virtual bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256& hashBlock);
330
332 virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
333
335 virtual ~CCoinsView() = default;
336
338 virtual size_t EstimateSize() const { return 0; }
339};
340
341
344{
345protected:
347
348public:
350 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
351 bool HaveCoin(const COutPoint &outpoint) const override;
352 uint256 GetBestBlock() const override;
353 std::vector<uint256> GetHeadBlocks() const override;
354 void SetBackend(CCoinsView &viewIn);
355 bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
356 std::unique_ptr<CCoinsViewCursor> Cursor() const override;
357 size_t EstimateSize() const override;
358};
359
360
363{
364private:
365 const bool m_deterministic;
366
367protected:
374 /* The starting sentinel of the flagged entry circular doubly linked list. */
377
378 /* Cached dynamic memory usage for the inner Coin objects. */
379 mutable size_t cachedCoinsUsage{0};
380
381public:
382 CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
383
388
389 // Standard CCoinsView methods
390 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
391 bool HaveCoin(const COutPoint &outpoint) const override;
392 uint256 GetBestBlock() const override;
393 void SetBestBlock(const uint256 &hashBlock);
394 bool BatchWrite(CoinsViewCacheCursor& cursor, const uint256 &hashBlock) override;
395 std::unique_ptr<CCoinsViewCursor> Cursor() const override {
396 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
397 }
398
404 bool HaveCoinInCache(const COutPoint &outpoint) const;
405
416 const Coin& AccessCoin(const COutPoint &output) const;
417
422 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
423
431 void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
432
438 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
439
446 bool Flush();
447
455 bool Sync();
456
461 void Uncache(const COutPoint &outpoint);
462
464 unsigned int GetCacheSize() const;
465
467 size_t DynamicMemoryUsage() const;
468
470 bool HaveInputs(const CTransaction& tx) const;
471
477 void ReallocateCache();
478
480 void SanityCheck() const;
481
482private:
487 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
488};
489
494// TODO: pass in a boolean to limit these possible overwrites to known
495// (pre-BIP34) cases.
496void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
497
502const Coin& AccessByTxid(const CCoinsViewCache& cache, const Txid& txid);
503
512{
513public:
515
516 void AddReadErrCallback(std::function<void()> f) {
517 m_err_callbacks.emplace_back(std::move(f));
518 }
519
520 std::optional<Coin> GetCoin(const COutPoint& outpoint) const override;
521 bool HaveCoin(const COutPoint &outpoint) const override;
522
523private:
525 std::vector<std::function<void()>> m_err_callbacks;
526
527};
528
529#endif // BITCOIN_COINS_H
#define LIFETIMEBOUND
Definition: attributes.h:16
int flags
Definition: bitcoin-tx.cpp:536
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
CCoinsView backed by another CCoinsView.
Definition: coins.h:344
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:29
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:35
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:30
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:28
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:33
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:32
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:34
CCoinsView * base
Definition: coins.h:346
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:31
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:27
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:363
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition: coins.cpp:37
const bool m_deterministic
Definition: coins.h:365
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:372
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:395
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:373
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:130
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:274
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:293
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:72
bool BatchWrite(CoinsViewCacheCursor &cursor, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:183
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:289
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:173
size_t cachedCoinsUsage
Definition: coins.h:379
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:179
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:48
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:168
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:250
CoinsCachePair m_sentinel
Definition: coins.h:375
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:44
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:261
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:113
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:163
void SanityCheck() const
Run an internal sanity check on the cache data structure. *‍/.
Definition: coins.cpp:315
CCoinsMap cacheCoins
Definition: coins.h:376
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:66
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:154
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:305
Cursor for iterating over CoinsView state.
Definition: coins.h:235
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:247
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:237
uint256 hashBlock
Definition: coins.h:249
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:512
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:516
std::optional< Coin > GetCoin(const COutPoint &outpoint) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:380
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:525
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:385
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:514
Abstract view on the open txout dataset.
Definition: coins.h:310
virtual std::optional< Coin > GetCoin(const COutPoint &outpoint) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:16
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:18
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:19
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:22
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:338
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:20
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:17
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:296
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
void SetNull()
Definition: transaction.h:164
bool IsNull() const
Definition: transaction.h:170
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:190
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:119
std::pair< const COutPoint, CCoinsCacheEntry > CoinsCachePair
Definition: coins.h:91
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:229
const Coin & AccessByTxid(const CCoinsViewCache &cache, const Txid &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:351
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:231
unsigned int nHeight
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:498
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:109
Coin coin
Definition: coins.h:147
CCoinsCacheEntry() noexcept=default
Flags
Definition: coins.h:149
@ 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:167
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:157
void SetClean() noexcept
Definition: coins.h:180
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:178
uint8_t m_flags
Definition: coins.h:129
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:132
CoinsCachePair * m_next
Definition: coins.h:128
bool IsFresh() const noexcept
Definition: coins.h:189
~CCoinsCacheEntry()
Definition: coins.h:172
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:177
void SelfRef(CoinsCachePair &pair) noexcept
Only use this for initializing the linked list sentinel.
Definition: coins.h:206
bool IsDirty() const noexcept
Definition: coins.h:188
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:192
CoinsCachePair * Prev() const noexcept
Only call Prev when this entry is DIRTY, FRESH, or both.
Definition: coins.h:199
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:266
CoinsCachePair & m_sentinel
Definition: coins.h:303
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:284
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:274
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:300
CCoinsMap & m_map
Definition: coins.h:304
CoinsCachePair * Begin() const noexcept
Definition: coins.h:280
size_t & m_usage
Definition: coins.h:302
CoinsCachePair * End() const noexcept
Definition: coins.h:281
assert(!tx.IsCoinBase())