Bitcoin Core 22.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-2020 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>
14#include <uint256.h>
15#include <util/hasher.h>
16
17#include <assert.h>
18#include <stdint.h>
19
20#include <functional>
21#include <unordered_map>
22
30class Coin
31{
32public:
35
37 unsigned int fCoinBase : 1;
38
40 uint32_t nHeight : 31;
41
43 Coin(CTxOut&& outIn, int nHeightIn, bool fCoinBaseIn) : out(std::move(outIn)), fCoinBase(fCoinBaseIn), nHeight(nHeightIn) {}
44 Coin(const CTxOut& outIn, int nHeightIn, bool fCoinBaseIn) : out(outIn), fCoinBase(fCoinBaseIn),nHeight(nHeightIn) {}
45
46 void Clear() {
47 out.SetNull();
48 fCoinBase = false;
49 nHeight = 0;
50 }
51
53 Coin() : fCoinBase(false), nHeight(0) { }
54
55 bool IsCoinBase() const {
56 return fCoinBase;
57 }
58
59 template<typename Stream>
60 void Serialize(Stream &s) const {
61 assert(!IsSpent());
62 uint32_t code = nHeight * uint32_t{2} + fCoinBase;
63 ::Serialize(s, VARINT(code));
64 ::Serialize(s, Using<TxOutCompression>(out));
65 }
66
67 template<typename Stream>
68 void Unserialize(Stream &s) {
69 uint32_t code = 0;
70 ::Unserialize(s, VARINT(code));
71 nHeight = code >> 1;
72 fCoinBase = code & 1;
73 ::Unserialize(s, Using<TxOutCompression>(out));
74 }
75
79 bool IsSpent() const {
80 return out.IsNull();
81 }
82
83 size_t DynamicMemoryUsage() const {
85 }
86};
87
104{
105 Coin coin; // The actual cached data.
106 unsigned char flags;
107
108 enum Flags {
116 DIRTY = (1 << 0),
126 FRESH = (1 << 1),
127 };
128
130 explicit CCoinsCacheEntry(Coin&& coin_) : coin(std::move(coin_)), flags(0) {}
131 CCoinsCacheEntry(Coin&& coin_, unsigned char flag) : coin(std::move(coin_)), flags(flag) {}
132};
133
134typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;
135
138{
139public:
140 CCoinsViewCursor(const uint256 &hashBlockIn): hashBlock(hashBlockIn) {}
141 virtual ~CCoinsViewCursor() {}
142
143 virtual bool GetKey(COutPoint &key) const = 0;
144 virtual bool GetValue(Coin &coin) const = 0;
145 virtual unsigned int GetValueSize() const = 0;
146
147 virtual bool Valid() const = 0;
148 virtual void Next() = 0;
149
151 const uint256 &GetBestBlock() const { return hashBlock; }
152private:
154};
155
158{
159public:
164 virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
165
167 virtual bool HaveCoin(const COutPoint &outpoint) const;
168
170 virtual uint256 GetBestBlock() const;
171
176 virtual std::vector<uint256> GetHeadBlocks() const;
177
180 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
181
183 virtual std::unique_ptr<CCoinsViewCursor> Cursor() const;
184
186 virtual ~CCoinsView() {}
187
189 virtual size_t EstimateSize() const { return 0; }
190};
191
192
195{
196protected:
198
199public:
201 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
202 bool HaveCoin(const COutPoint &outpoint) const override;
203 uint256 GetBestBlock() const override;
204 std::vector<uint256> GetHeadBlocks() const override;
205 void SetBackend(CCoinsView &viewIn);
206 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
207 std::unique_ptr<CCoinsViewCursor> Cursor() const override;
208 size_t EstimateSize() const override;
209};
210
211
214{
215protected:
222
223 /* Cached dynamic memory usage for the inner Coin objects. */
224 mutable size_t cachedCoinsUsage;
225
226public:
228
233
234 // Standard CCoinsView methods
235 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
236 bool HaveCoin(const COutPoint &outpoint) const override;
237 uint256 GetBestBlock() const override;
238 void SetBestBlock(const uint256 &hashBlock);
239 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
240 std::unique_ptr<CCoinsViewCursor> Cursor() const override {
241 throw std::logic_error("CCoinsViewCache cursor iteration not supported.");
242 }
243
249 bool HaveCoinInCache(const COutPoint &outpoint) const;
250
261 const Coin& AccessCoin(const COutPoint &output) const;
262
267 void AddCoin(const COutPoint& outpoint, Coin&& coin, bool possible_overwrite);
268
276 void EmplaceCoinInternalDANGER(COutPoint&& outpoint, Coin&& coin);
277
283 bool SpendCoin(const COutPoint &outpoint, Coin* moveto = nullptr);
284
290 bool Flush();
291
296 void Uncache(const COutPoint &outpoint);
297
299 unsigned int GetCacheSize() const;
300
302 size_t DynamicMemoryUsage() const;
303
305 bool HaveInputs(const CTransaction& tx) const;
306
312 void ReallocateCache();
313
314private:
319 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
320};
321
326// TODO: pass in a boolean to limit these possible overwrites to known
327// (pre-BIP34) cases.
328void AddCoins(CCoinsViewCache& cache, const CTransaction& tx, int nHeight, bool check = false);
329
334const Coin& AccessByTxid(const CCoinsViewCache& cache, const uint256& txid);
335
344{
345public:
347
348 void AddReadErrCallback(std::function<void()> f) {
349 m_err_callbacks.emplace_back(std::move(f));
350 }
351
352 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
353
354private:
356 std::vector<std::function<void()>> m_err_callbacks;
357
358};
359
360#endif // BITCOIN_COINS_H
CCoinsView backed by another CCoinsView.
Definition: coins.h:195
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
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
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:30
CCoinsView * base
Definition: coins.h:197
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:214
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:166
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:220
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:240
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:119
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:229
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:34
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:242
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:66
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:238
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:156
size_t cachedCoinsUsage
Definition: coins.h:224
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:162
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:40
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:57
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:151
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:222
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:36
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:100
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:146
CCoinsMap cacheCoins
Definition: coins.h:221
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:137
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:254
Cursor for iterating over CoinsView state.
Definition: coins.h:138
const uint256 & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:151
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const uint256 &hashBlockIn)
Definition: coins.h:140
virtual unsigned int GetValueSize() const =0
uint256 hashBlock
Definition: coins.h:153
virtual ~CCoinsViewCursor()
Definition: coins.h:141
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:344
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:348
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:356
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:276
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:346
Abstract view on the open txout dataset.
Definition: coins.h:158
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()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:186
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:189
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:15
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:27
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:260
An output of a transaction.
Definition: transaction.h:129
CScript scriptPubKey
Definition: transaction.h:132
void SetNull()
Definition: transaction.h:143
bool IsNull() const
Definition: transaction.h:149
A UTXO entry.
Definition: coins.h:31
bool IsCoinBase() const
Definition: coins.h:55
void Clear()
Definition: coins.h:46
void Serialize(Stream &s) const
Definition: coins.h:60
Coin(CTxOut &&outIn, int nHeightIn, bool fCoinBaseIn)
construct a Coin from a CTxOut and height/coinbase information.
Definition: coins.h:43
Coin()
empty constructor
Definition: coins.h:53
CTxOut out
unspent transaction output
Definition: coins.h:34
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
Coin(const CTxOut &outIn, int nHeightIn, bool fCoinBaseIn)
Definition: coins.h:44
void Unserialize(Stream &s)
Definition: coins.h:68
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Definition: coins.h:40
size_t DynamicMemoryUsage() const
Definition: coins.h:83
unsigned int fCoinBase
whether containing transaction was a coinbase
Definition: coins.h:37
256-bit opaque blob.
Definition: uint256.h:124
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:108
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
const Coin & AccessByTxid(const CCoinsViewCache &cache, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:265
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:29
#define VARINT(obj)
Definition: serialize.h:443
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:104
unsigned char flags
Definition: coins.h:106
Coin coin
Definition: coins.h:105
Flags
Definition: coins.h:108
@ 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:126
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:116
CCoinsCacheEntry(Coin &&coin_, unsigned char flag)
Definition: coins.h:131
CCoinsCacheEntry()
Definition: coins.h:129
CCoinsCacheEntry(Coin &&coin_)
Definition: coins.h:130
assert(!tx.IsCoinBase())