Bitcoin ABC 0.30.7
P2P Digital Currency
coins.h
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2016 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 <memusage.h>
12#include <serialize.h>
14#include <util/hasher.h>
15
16#include <cassert>
17#include <cstdint>
18#include <functional>
19#include <unordered_map>
20
28class Coin {
31
35
36public:
39
41 Coin(CTxOut outIn, uint32_t nHeightIn, bool IsCoinbase)
42 : out(std::move(outIn)),
43 nHeightAndIsCoinBase((nHeightIn << 1) | IsCoinbase) {}
44
45 uint32_t GetHeight() const { return nHeightAndIsCoinBase >> 1; }
46 bool IsCoinBase() const { return nHeightAndIsCoinBase & 0x01; }
47 bool IsSpent() const { return out.IsNull(); }
48
49 CTxOut &GetTxOut() { return out; }
50 const CTxOut &GetTxOut() const { return out; }
51
52 void Clear() {
53 out.SetNull();
55 }
56
57 template <typename Stream> void Serialize(Stream &s) const {
58 assert(!IsSpent());
60 ::Serialize(s, Using<TxOutCompression>(out));
61 }
62
63 template <typename Stream> void Unserialize(Stream &s) {
65 ::Unserialize(s, Using<TxOutCompression>(out));
66 }
67
68 size_t DynamicMemoryUsage() const {
70 }
71};
72
92 // The actual cached data.
94 uint8_t flags;
95
96 enum Flags {
104 DIRTY = (1 << 0),
114 FRESH = (1 << 1),
115 };
116
118 explicit CCoinsCacheEntry(Coin coinIn)
119 : coin(std::move(coinIn)), flags(0) {}
120 CCoinsCacheEntry(Coin &&coin_, uint8_t flag)
121 : coin(std::move(coin_)), flags(flag) {}
122};
123
134using CCoinsMap = std::unordered_map<
135 COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to<COutPoint>,
137 sizeof(std::pair<const COutPoint, CCoinsCacheEntry>) +
138 sizeof(void *) * 4>>;
139
140using CCoinsMapMemoryResource = CCoinsMap::allocator_type::ResourceType;
141
144public:
145 CCoinsViewCursor(const BlockHash &hashBlockIn) : hashBlock(hashBlockIn) {}
146 virtual ~CCoinsViewCursor() {}
147
148 virtual bool GetKey(COutPoint &key) const = 0;
149 virtual bool GetValue(Coin &coin) const = 0;
150 virtual unsigned int GetValueSize() const = 0;
151
152 virtual bool Valid() const = 0;
153 virtual void Next() = 0;
154
156 const BlockHash &GetBestBlock() const { return hashBlock; }
157
158private:
160};
161
164public:
170 virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
171
173 virtual bool HaveCoin(const COutPoint &outpoint) const;
174
176 virtual BlockHash GetBestBlock() const;
177
183 virtual std::vector<BlockHash> GetHeadBlocks() const;
184
187 virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock,
188 bool erase = true);
189
191 virtual CCoinsViewCursor *Cursor() const;
192
194 virtual ~CCoinsView() {}
195
197 virtual size_t EstimateSize() const { return 0; }
198};
199
202protected:
204
205public:
207 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
208 bool HaveCoin(const COutPoint &outpoint) const override;
209 BlockHash GetBestBlock() const override;
210 std::vector<BlockHash> GetHeadBlocks() const override;
211 void SetBackend(CCoinsView &viewIn);
212 bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock,
213 bool erase = true) override;
214 CCoinsViewCursor *Cursor() const override;
215 size_t EstimateSize() const override;
216};
217
222private:
223 const bool m_deterministic;
224
225protected:
233
234 /* Cached dynamic memory usage for the inner Coin objects. */
235 mutable size_t cachedCoinsUsage;
236
237public:
238 CCoinsViewCache(CCoinsView *baseIn, bool deterministic = false);
239
245
246 // Standard CCoinsView methods
247 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
248 bool HaveCoin(const COutPoint &outpoint) const override;
249 BlockHash GetBestBlock() const override;
250 void SetBestBlock(const BlockHash &hashBlock);
251 bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock,
252 bool erase = true) override;
253 CCoinsViewCursor *Cursor() const override {
254 throw std::logic_error(
255 "CCoinsViewCache cursor iteration not supported.");
256 }
257
263 bool HaveCoinInCache(const COutPoint &outpoint) const;
264
275 const Coin &AccessCoin(const COutPoint &output) const;
276
281 void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite);
282
290 void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin);
291
297 bool SpendCoin(const COutPoint &outpoint, Coin *moveto = nullptr);
298
305 bool Flush();
306
314 bool Sync();
315
320 void Uncache(const COutPoint &outpoint);
321
323 unsigned int GetCacheSize() const;
324
326 size_t DynamicMemoryUsage() const;
327
330 bool HaveInputs(const CTransaction &tx) const;
331
338 void ReallocateCache();
339
341 void SanityCheck() const;
342
343private:
348 CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const;
349};
350
355// TODO: pass in a boolean to limit these possible overwrites to known
356// (pre-BIP34) cases.
357void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight,
358 bool check = false);
359
364const Coin &AccessByTxid(const CCoinsViewCache &cache, const TxId &txid);
365
375public:
377 : CCoinsViewBacked(view) {}
378
379 void AddReadErrCallback(std::function<void()> f) {
380 m_err_callbacks.emplace_back(std::move(f));
381 }
382
383 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
384
385private:
389 std::vector<std::function<void()>> m_err_callbacks;
390};
391
392#endif // BITCOIN_COINS_H
CCoinsView backed by another CCoinsView.
Definition: coins.h:201
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:38
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:41
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:54
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:35
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:57
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:50
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:47
CCoinsView * base
Definition: coins.h:203
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:44
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:34
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:221
CCoinsViewCache(CCoinsView *baseIn, bool deterministic=false)
Definition: coins.cpp:61
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:104
const bool m_deterministic
Definition: coins.h:223
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:214
CCoinsMapMemoryResource m_cache_coins_memory_resource
Definition: coins.h:231
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:172
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:330
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.h:253
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:346
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:221
BlockHash hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:230
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:342
size_t cachedCoinsUsage
Definition: coins.h:235
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:225
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:72
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:95
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:209
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:301
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:67
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:314
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:148
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:204
void SanityCheck() const
Run an internal sanity check on the cache data structure.
Definition: coins.cpp:371
CCoinsMap cacheCoins
Definition: coins.h:232
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:196
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:360
Cursor for iterating over CoinsView state.
Definition: coins.h:143
virtual void Next()=0
virtual bool Valid() const =0
CCoinsViewCursor(const BlockHash &hashBlockIn)
Definition: coins.h:145
virtual unsigned int GetValueSize() const =0
BlockHash hashBlock
Definition: coins.h:159
virtual ~CCoinsViewCursor()
Definition: coins.h:146
virtual bool GetKey(COutPoint &key) const =0
const BlockHash & GetBestBlock() const
Get best block at the time this cursor was created.
Definition: coins.h:156
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:374
void AddReadErrCallback(std::function< void()> f)
Definition: coins.h:379
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:389
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:408
CCoinsViewErrorCatcher(CCoinsView *view)
Definition: coins.h:376
Abstract view on the open txout dataset.
Definition: coins.h:163
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:26
virtual std::vector< BlockHash > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:19
virtual ~CCoinsView()
As we use CCoinsViews polymorphically, have a virtual destructor.
Definition: coins.h:194
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:16
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:29
virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock, bool erase=true)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:22
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:197
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
void SetNull()
Definition: transaction.h:140
bool IsNull() const
Definition: transaction.h:145
A UTXO entry.
Definition: coins.h:28
uint32_t GetHeight() const
Definition: coins.h:45
bool IsCoinBase() const
Definition: coins.h:46
void Clear()
Definition: coins.h:52
Coin(CTxOut outIn, uint32_t nHeightIn, bool IsCoinbase)
Constructor from a CTxOut and height/coinbase information.
Definition: coins.h:41
void Serialize(Stream &s) const
Definition: coins.h:57
CTxOut & GetTxOut()
Definition: coins.h:49
uint32_t nHeightAndIsCoinBase
Whether containing transaction was a coinbase and height at which the transaction was included into a...
Definition: coins.h:34
Coin()
Empty constructor.
Definition: coins.h:38
CTxOut out
Unspent transaction output.
Definition: coins.h:30
const CTxOut & GetTxOut() const
Definition: coins.h:50
bool IsSpent() const
Definition: coins.h:47
void Unserialize(Stream &s)
Definition: coins.h:63
size_t DynamicMemoryUsage() const
Definition: coins.h:68
Forwards all allocations/deallocations to the PoolResource.
Definition: pool.h:299
const Coin & AccessByTxid(const CCoinsViewCache &cache, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:397
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:156
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< std::pair< const COutPoint, CCoinsCacheEntry >, sizeof(std::pair< const COutPoint, CCoinsCacheEntry >)+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:138
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:140
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:27
Implement std::hash so RCUPtr can be used as a key for maps or sets.
Definition: rcu.h:259
#define VARINT(obj)
Definition: serialize.h:579
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:91
Coin coin
Definition: coins.h:93
Flags
Definition: coins.h:96
@ 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:114
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:104
uint8_t flags
Definition: coins.h:94
CCoinsCacheEntry(Coin &&coin_, uint8_t flag)
Definition: coins.h:120
CCoinsCacheEntry()
Definition: coins.h:117
CCoinsCacheEntry(Coin coinIn)
Definition: coins.h:118
A TxId is the identifier of a transaction.
Definition: txid.h:14
assert(!tx.IsCoinBase())