Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
coins.cpp
Go to the documentation of this file.
1// Copyright (c) 2012-2016 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <coins.h>
6
8#include <logging.h>
9#include <random.h>
10#include <util/trace.h>
11#include <version.h>
12
13bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const {
14 return false;
15}
17 return BlockHash();
18}
19std::vector<BlockHash> CCoinsView::GetHeadBlocks() const {
20 return std::vector<BlockHash>();
21}
23 bool erase) {
24 return false;
25}
27 return nullptr;
28}
29bool CCoinsView::HaveCoin(const COutPoint &outpoint) const {
30 Coin coin;
31 return GetCoin(outpoint, coin);
32}
33
35bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const {
36 return base->GetCoin(outpoint, coin);
37}
38bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const {
39 return base->HaveCoin(outpoint);
40}
44std::vector<BlockHash> CCoinsViewBacked::GetHeadBlocks() const {
45 return base->GetHeadBlocks();
46}
51 const BlockHash &hashBlock, bool erase) {
52 return base->BatchWrite(mapCoins, hashBlock, erase);
53}
58 return base->EstimateSize();
59}
60
62 : CCoinsViewBacked(baseIn), m_deterministic(deterministic),
63 cacheCoins(0, SaltedOutpointHasher(/*deterministic=*/deterministic),
64 CCoinsMap::key_equal{}, &m_cache_coins_memory_resource),
65 cachedCoinsUsage(0) {}
66
70
71CCoinsMap::iterator
72CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
73 CCoinsMap::iterator it = cacheCoins.find(outpoint);
74 if (it != cacheCoins.end()) {
75 return it;
76 }
77 Coin tmp;
78 if (!base->GetCoin(outpoint, tmp)) {
79 return cacheCoins.end();
80 }
81 CCoinsMap::iterator ret =
83 .emplace(std::piecewise_construct, std::forward_as_tuple(outpoint),
84 std::forward_as_tuple(std::move(tmp)))
85 .first;
86 if (ret->second.coin.IsSpent()) {
87 // The parent only has an empty entry for this outpoint; we can consider
88 // our version as fresh.
89 ret->second.flags = CCoinsCacheEntry::FRESH;
90 }
91 cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
92 return ret;
93}
94
95bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
96 CCoinsMap::const_iterator it = FetchCoin(outpoint);
97 if (it == cacheCoins.end()) {
98 return false;
99 }
100 coin = it->second.coin;
101 return !coin.IsSpent();
102}
103
104void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin coin,
105 bool possible_overwrite) {
106 assert(!coin.IsSpent());
107 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
108 return;
109 }
110 CCoinsMap::iterator it;
111 bool inserted;
112 std::tie(it, inserted) =
113 cacheCoins.emplace(std::piecewise_construct,
114 std::forward_as_tuple(outpoint), std::tuple<>());
115 bool fresh = false;
116 if (!inserted) {
117 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
118 }
119 if (!possible_overwrite) {
120 if (!it->second.coin.IsSpent()) {
121 throw std::logic_error("Attempted to overwrite an unspent coin "
122 "(when possible_overwrite is false)");
123 }
124 // If the coin exists in this cache as a spent coin and is DIRTY, then
125 // its spentness hasn't been flushed to the parent cache. We're
126 // re-adding the coin to this cache now but we can't mark it as FRESH.
127 // If we mark it FRESH and then spend it before the cache is flushed
128 // we would remove it from this cache and would never flush spentness
129 // to the parent cache.
130 //
131 // Re-adding a spent coin can happen in the case of a re-org (the coin
132 // is 'spent' when the block adding it is disconnected and then
133 // re-added when it is also added in a newly connected block).
134 //
135 // If the coin doesn't exist in the current cache, or is spent but not
136 // DIRTY, then it can be marked FRESH.
137 fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
138 }
139 it->second.coin = std::move(coin);
140 it->second.flags |=
142 cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
143 TRACE5(utxocache, add, outpoint.GetTxId().data(), outpoint.GetN(),
144 coin.GetHeight(), coin.GetTxOut().nValue.ToString().c_str(),
145 coin.IsCoinBase());
146}
147
149 Coin &&coin) {
150 cachedCoinsUsage += coin.DynamicMemoryUsage();
151 cacheCoins.emplace(
152 std::piecewise_construct, std::forward_as_tuple(std::move(outpoint)),
153 std::forward_as_tuple(std::move(coin), CCoinsCacheEntry::DIRTY));
154}
155
156void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight,
157 bool check_for_overwrite) {
158 bool fCoinbase = tx.IsCoinBase();
159 const TxId txid = tx.GetId();
160 for (size_t i = 0; i < tx.vout.size(); ++i) {
161 const COutPoint outpoint(txid, i);
162 bool overwrite =
163 check_for_overwrite ? cache.HaveCoin(outpoint) : fCoinbase;
164 // Coinbase transactions can always be overwritten,
165 // in order to correctly deal with the pre-BIP30 occurrences of
166 // duplicate coinbase transactions.
167 cache.AddCoin(outpoint, Coin(tx.vout[i], nHeight, fCoinbase),
168 overwrite);
169 }
170}
171
172bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin *moveout) {
173 CCoinsMap::iterator it = FetchCoin(outpoint);
174 if (it == cacheCoins.end()) {
175 return false;
176 }
177 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
178 TRACE5(utxocache, spent, outpoint.GetTxId().data(), outpoint.GetN(),
179 it->second.coin.GetHeight(),
180 it->second.coin.GetTxOut().nValue.ToString().c_str(),
181 it->second.coin.IsCoinBase());
182 if (moveout) {
183 *moveout = std::move(it->second.coin);
184 }
185 if (it->second.flags & CCoinsCacheEntry::FRESH) {
186 cacheCoins.erase(it);
187 } else {
188 it->second.flags |= CCoinsCacheEntry::DIRTY;
189 it->second.coin.Clear();
190 }
191 return true;
192}
193
194static const Coin coinEmpty;
195
196const Coin &CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
197 CCoinsMap::const_iterator it = FetchCoin(outpoint);
198 if (it == cacheCoins.end()) {
199 return coinEmpty;
200 }
201 return it->second.coin;
202}
203
204bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
205 CCoinsMap::const_iterator it = FetchCoin(outpoint);
206 return it != cacheCoins.end() && !it->second.coin.IsSpent();
207}
208
209bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
210 CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
211 return (it != cacheCoins.end() && !it->second.coin.IsSpent());
212}
213
215 if (hashBlock.IsNull()) {
217 }
218 return hashBlock;
219}
220
224
226 const BlockHash &hashBlockIn, bool erase) {
227 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();
228 it = erase ? mapCoins.erase(it) : std::next(it)) {
229 // Ignore non-dirty entries (optimization).
230 if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
231 continue;
232 }
233 CCoinsMap::iterator itUs = cacheCoins.find(it->first);
234 if (itUs == cacheCoins.end()) {
235 // The parent cache does not have an entry, while the child cache
236 // does. We can ignore it if it's both spent and FRESH in the child
237 if (!(it->second.flags & CCoinsCacheEntry::FRESH &&
238 it->second.coin.IsSpent())) {
239 // Create the coin in the parent cache, move the data up
240 // and mark it as dirty.
241 CCoinsCacheEntry &entry = cacheCoins[it->first];
242 if (erase) {
243 // The `move` call here is purely an optimization; we rely
244 // on the `mapCoins.erase` call in the `for` expression to
245 // actually remove the entry from the child map.
246 entry.coin = std::move(it->second.coin);
247 } else {
248 entry.coin = it->second.coin;
249 }
252 // We can mark it FRESH in the parent if it was FRESH in the
253 // child. Otherwise it might have just been flushed from the
254 // parent's cache and already exist in the grandparent
255 if (it->second.flags & CCoinsCacheEntry::FRESH) {
257 }
258 }
259 } else {
260 // Found the entry in the parent cache
261 if ((it->second.flags & CCoinsCacheEntry::FRESH) &&
262 !itUs->second.coin.IsSpent()) {
263 // The coin was marked FRESH in the child cache, but the coin
264 // exists in the parent cache. If this ever happens, it means
265 // the FRESH flag was misapplied and there is a logic error in
266 // the calling code.
267 throw std::logic_error("FRESH flag misapplied to coin that "
268 "exists in parent cache");
269 }
270
271 if ((itUs->second.flags & CCoinsCacheEntry::FRESH) &&
272 it->second.coin.IsSpent()) {
273 // The grandparent cache does not have an entry, and the coin
274 // has been spent. We can just delete it from the parent cache.
275 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
276 cacheCoins.erase(itUs);
277 } else {
278 // A normal modification.
279 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
280 if (erase) {
281 // The `move` call here is purely an optimization; we rely
282 // on the `mapCoins.erase` call in the `for` expression to
283 // actually remove the entry from the child map.
284 itUs->second.coin = std::move(it->second.coin);
285 } else {
286 itUs->second.coin = it->second.coin;
287 }
288 cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
289 itUs->second.flags |= CCoinsCacheEntry::DIRTY;
290 // NOTE: It isn't safe to mark the coin as FRESH in the parent
291 // cache. If it already existed and was spent in the parent
292 // cache then marking it FRESH would prevent that spentness
293 // from being flushed to the grandparent.
294 }
295 }
296 }
298 return true;
299}
300
302 bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/true);
303 if (fOk) {
304 if (!cacheCoins.empty()) {
305 /* BatchWrite must erase all cacheCoins elements when erase=true. */
306 throw std::logic_error("Not all cached coins were erased");
307 }
309 }
311 return fOk;
312}
313
315 bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/false);
316 // Instead of clearing `cacheCoins` as we would in Flush(), just clear the
317 // FRESH/DIRTY flags of any coin that isn't spent.
318 for (auto it = cacheCoins.begin(); it != cacheCoins.end();) {
319 if (it->second.coin.IsSpent()) {
320 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
321 it = cacheCoins.erase(it);
322 } else {
323 it->second.flags = 0;
324 ++it;
325 }
326 }
327 return fOk;
328}
329
330void CCoinsViewCache::Uncache(const COutPoint &outpoint) {
331 CCoinsMap::iterator it = cacheCoins.find(outpoint);
332 if (it != cacheCoins.end() && it->second.flags == 0) {
333 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
334 TRACE5(utxocache, uncache, outpoint.GetTxId().data(), outpoint.GetN(),
335 it->second.coin.GetHeight(),
336 it->second.coin.GetTxOut().nValue.ToString().c_str(),
337 it->second.coin.IsCoinBase());
338 cacheCoins.erase(it);
339 }
340}
341
342unsigned int CCoinsViewCache::GetCacheSize() const {
343 return cacheCoins.size();
344}
345
346bool CCoinsViewCache::HaveInputs(const CTransaction &tx) const {
347 if (tx.IsCoinBase()) {
348 return true;
349 }
350
351 for (size_t i = 0; i < tx.vin.size(); i++) {
352 if (!HaveCoin(tx.vin[i].prevout)) {
353 return false;
354 }
355 }
356
357 return true;
358}
359
361 // Cache should be empty when we're calling this.
362 assert(cacheCoins.size() == 0);
363 cacheCoins.~CCoinsMap();
364 m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
367 CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic},
368 CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
369}
370
372 size_t recomputed_usage = 0;
373 for (const auto &[_, entry] : cacheCoins) {
374 unsigned attr = 0;
375 if (entry.flags & CCoinsCacheEntry::DIRTY) {
376 attr |= 1;
377 }
378 if (entry.flags & CCoinsCacheEntry::FRESH) {
379 attr |= 2;
380 }
381 if (entry.coin.IsSpent()) {
382 attr |= 4;
383 }
384 // Only 5 combinations are possible.
385 assert(attr != 2 && attr != 4 && attr != 7);
386
387 // Recompute cachedCoinsUsage.
388 recomputed_usage += entry.coin.DynamicMemoryUsage();
389 }
391}
392
393// TODO: merge with similar definition in undo.h.
394static const size_t MAX_OUTPUTS_PER_TX =
396
397const Coin &AccessByTxid(const CCoinsViewCache &view, const TxId &txid) {
398 for (uint32_t n = 0; n < MAX_OUTPUTS_PER_TX; n++) {
399 const Coin &alternate = view.AccessCoin(COutPoint(txid, n));
400 if (!alternate.IsSpent()) {
401 return alternate;
402 }
403 }
404
405 return coinEmpty;
406}
407
408bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint,
409 Coin &coin) const {
410 try {
411 return CCoinsViewBacked::GetCoin(outpoint, coin);
412 } catch (const std::runtime_error &e) {
413 for (auto f : m_err_callbacks) {
414 f();
415 }
416 LogPrintf("Error reading from database: %s\n", e.what());
417 // Starting the shutdown sequence and returning false to the caller
418 // would be interpreted as 'entry not found' (as opposed to unable to
419 // read data), and could lead to invalid interpretation. Just exit
420 // immediately, as we can't continue anyway, and all writes should be
421 // atomic.
422 std::abort();
423 }
424}
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
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
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
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 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.
const std::vector< CTxOut > vout
bool IsCoinBase() const
const TxId GetId() const
An output of a transaction.
CScript scriptPubKey
Amount nValue
A UTXO entry.
Definition coins.h:28
uint32_t GetHeight() const
Definition coins.h:45
bool IsCoinBase() const
Definition coins.h:46
CTxOut & GetTxOut()
Definition coins.h:49
bool IsSpent() const
Definition coins.h:47
size_t DynamicMemoryUsage() const
Definition coins.h:68
bool IsNull() const
Definition uint256.h:32
static const size_t MAX_OUTPUTS_PER_TX
Definition coins.cpp:394
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition coins.cpp:397
static const Coin coinEmpty
Definition coins.cpp:194
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check_for_overwrite)
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
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
Definition consensus.h:14
#define LogPrintf(...)
Definition logging.h:227
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition memusage.h:27
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition serialize.h:1258
std::string ToString() const
Definition amount.cpp:22
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
@ 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
A TxId is the identifier of a transaction.
Definition txid.h:14
#define TRACE5(context, event, a, b, c, d, e)
Definition trace.h:44
bilingual_str _(const char *psz)
Translation function.
Definition translation.h:68
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition version.h:11