Bitcoin ABC 0.32.4
P2P Digital Currency
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 const BlockHash &hashBlock) {
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}
42 return base->GetBestBlock();
43}
44std::vector<BlockHash> CCoinsViewBacked::GetHeadBlocks() const {
45 return base->GetHeadBlocks();
46}
48 base = &viewIn;
49}
51 const BlockHash &hashBlock) {
52 return base->BatchWrite(cursor, hashBlock);
53}
55 return base->Cursor();
56}
58 return base->EstimateSize();
59}
60
61CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn, bool deterministic)
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 m_sentinel.second.SelfRef(m_sentinel);
67}
68
71}
72
73CCoinsMap::iterator
74CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
75 const auto [ret, inserted] = cacheCoins.try_emplace(outpoint);
76 if (inserted) {
77 if (!base->GetCoin(outpoint, ret->second.coin)) {
78 cacheCoins.erase(ret);
79 return cacheCoins.end();
80 }
81 if (ret->second.coin.IsSpent()) {
82 // The parent only has an empty entry for this outpoint; we can
83 // consider our version as fresh.
85 }
86 cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
87 }
88 return ret;
89}
90
91bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
92 CCoinsMap::const_iterator it = FetchCoin(outpoint);
93 if (it == cacheCoins.end()) {
94 return false;
95 }
96 coin = it->second.coin;
97 return !coin.IsSpent();
98}
99
100void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin coin,
101 bool possible_overwrite) {
102 assert(!coin.IsSpent());
103 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
104 return;
105 }
106 CCoinsMap::iterator it;
107 bool inserted;
108 std::tie(it, inserted) =
109 cacheCoins.emplace(std::piecewise_construct,
110 std::forward_as_tuple(outpoint), std::tuple<>());
111 bool fresh = false;
112 if (!inserted) {
113 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
114 }
115 if (!possible_overwrite) {
116 if (!it->second.coin.IsSpent()) {
117 throw std::logic_error("Attempted to overwrite an unspent coin "
118 "(when possible_overwrite is false)");
119 }
120 // If the coin exists in this cache as a spent coin and is DIRTY, then
121 // its spentness hasn't been flushed to the parent cache. We're
122 // re-adding the coin to this cache now but we can't mark it as FRESH.
123 // If we mark it FRESH and then spend it before the cache is flushed
124 // we would remove it from this cache and would never flush spentness
125 // to the parent cache.
126 //
127 // Re-adding a spent coin can happen in the case of a re-org (the coin
128 // is 'spent' when the block adding it is disconnected and then
129 // re-added when it is also added in a newly connected block).
130 //
131 // If the coin doesn't exist in the current cache, or is spent but not
132 // DIRTY, then it can be marked FRESH.
133 fresh = !it->second.IsDirty();
134 }
135 it->second.coin = std::move(coin);
137 if (fresh) {
139 }
140 cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
141 TRACE5(utxocache, add, outpoint.GetTxId().data(), outpoint.GetN(),
142 coin.GetHeight(), coin.GetTxOut().nValue.ToString().c_str(),
143 coin.IsCoinBase());
144}
145
147 Coin &&coin) {
148 cachedCoinsUsage += coin.DynamicMemoryUsage();
149 auto [it, inserted] =
150 cacheCoins.try_emplace(std::move(outpoint), std::move(coin));
151 if (inserted) {
153 }
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.IsFresh()) {
186 cacheCoins.erase(it);
187 } else {
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
221void CCoinsViewCache::SetBestBlock(const BlockHash &hashBlockIn) {
222 hashBlock = hashBlockIn;
223}
224
226 const BlockHash &hashBlockIn) {
227 for (auto it{cursor.Begin()}; it != cursor.End();
228 it = cursor.NextAndMaybeErase(*it)) {
229 // Ignore non-dirty entries (optimization).
230 if (!it->second.IsDirty()) {
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.IsFresh() && it->second.coin.IsSpent())) {
238 // Create the coin in the parent cache, move the data up
239 // and mark it as dirty.
240 itUs = cacheCoins.try_emplace(it->first).first;
241 CCoinsCacheEntry &entry{itUs->second};
242
243 if (cursor.WillErase(*it)) {
244 // Since this entry will be erased,
245 // we can move the coin into us instead of copying it
246 entry.coin = std::move(it->second.coin);
247 } else {
248 entry.coin = it->second.coin;
249 }
250 cachedCoinsUsage += entry.coin.DynamicMemoryUsage();
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.IsFresh()) {
257 }
258 }
259 } else {
260 // Found the entry in the parent cache
261 if (it->second.IsFresh() && !itUs->second.coin.IsSpent()) {
262 // The coin was marked FRESH in the child cache, but the coin
263 // exists in the parent cache. If this ever happens, it means
264 // the FRESH flag was misapplied and there is a logic error in
265 // the calling code.
266 throw std::logic_error("FRESH flag misapplied to coin that "
267 "exists in parent cache");
268 }
269
270 if (itUs->second.IsFresh() && it->second.coin.IsSpent()) {
271 // The grandparent cache does not have an entry, and the coin
272 // has been spent. We can just delete it from the parent cache.
273 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
274 cacheCoins.erase(itUs);
275 } else {
276 // A normal modification.
277 cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
278 if (cursor.WillErase(*it)) {
279 // Since this entry will be erased,
280 // we can move the coin into us instead of copying it
281 itUs->second.coin = std::move(it->second.coin);
282 } else {
283 itUs->second.coin = it->second.coin;
284 }
285 cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
287 // NOTE: It isn't safe to mark the coin as FRESH in the parent
288 // cache. If it already existed and was spent in the parent
289 // cache then marking it FRESH would prevent that spentness
290 // from being flushed to the grandparent.
291 }
292 }
293 }
294 hashBlock = hashBlockIn;
295 return true;
296}
297
300 /*will_erase=*/true)};
301 bool fOk = base->BatchWrite(cursor, hashBlock);
302 if (fOk) {
303 cacheCoins.clear();
305 }
307 return fOk;
308}
309
312 /*will_erase=*/false)};
313 bool fOk = base->BatchWrite(cursor, hashBlock);
314 if (fOk) {
315 if (m_sentinel.second.Next() != &m_sentinel) {
316 /* BatchWrite must clear flags of all entries */
317 throw std::logic_error(
318 "Not all unspent flagged entries were cleared");
319 }
320 }
321 return fOk;
322}
323
324void CCoinsViewCache::Uncache(const COutPoint &outpoint) {
325 CCoinsMap::iterator it = cacheCoins.find(outpoint);
326 if (it != cacheCoins.end() && !it->second.IsDirty() &&
327 !it->second.IsFresh()) {
328 cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
329 TRACE5(utxocache, uncache, outpoint.GetTxId().data(), outpoint.GetN(),
330 it->second.coin.GetHeight(),
331 it->second.coin.GetTxOut().nValue.ToString().c_str(),
332 it->second.coin.IsCoinBase());
333 cacheCoins.erase(it);
334 }
335}
336
337unsigned int CCoinsViewCache::GetCacheSize() const {
338 return cacheCoins.size();
339}
340
341bool CCoinsViewCache::HaveInputs(const CTransaction &tx) const {
342 if (tx.IsCoinBase()) {
343 return true;
344 }
345
346 for (size_t i = 0; i < tx.vin.size(); i++) {
347 if (!HaveCoin(tx.vin[i].prevout)) {
348 return false;
349 }
350 }
351
352 return true;
353}
354
356 // Cache should be empty when we're calling this.
357 assert(cacheCoins.size() == 0);
358 cacheCoins.~CCoinsMap();
359 m_cache_coins_memory_resource.~CCoinsMapMemoryResource();
361 ::new (&cacheCoins)
362 CCoinsMap{0, SaltedOutpointHasher{/*deterministic=*/m_deterministic},
363 CCoinsMap::key_equal{}, &m_cache_coins_memory_resource};
364}
365
367 size_t recomputed_usage = 0;
368 size_t count_flagged = 0;
369 for (const auto &[_, entry] : cacheCoins) {
370 unsigned attr = 0;
371 if (entry.IsDirty()) {
372 attr |= 1;
373 }
374 if (entry.IsFresh()) {
375 attr |= 2;
376 }
377 if (entry.coin.IsSpent()) {
378 attr |= 4;
379 }
380 // Only 5 combinations are possible.
381 assert(attr != 2 && attr != 4 && attr != 7);
382
383 // Recompute cachedCoinsUsage.
384 recomputed_usage += entry.coin.DynamicMemoryUsage();
385
386 // Count the number of entries we expect in the linked list.
387 if (entry.IsDirty() || entry.IsFresh()) {
388 ++count_flagged;
389 }
390 }
391 // Iterate over the linked list of flagged entries.
392 size_t count_linked = 0;
393 for (auto it = m_sentinel.second.Next(); it != &m_sentinel;
394 it = it->second.Next()) {
395 // Verify linked list integrity.
396 assert(it->second.Next()->second.Prev() == it);
397 assert(it->second.Prev()->second.Next() == it);
398 // Verify they are actually flagged.
399 assert(it->second.IsDirty() || it->second.IsFresh());
400 // Count the number of entries actually in the list.
401 ++count_linked;
402 }
403 assert(count_linked == count_flagged);
404 assert(recomputed_usage == cachedCoinsUsage);
405}
406
407// TODO: merge with similar definition in undo.h.
408static const size_t MAX_OUTPUTS_PER_TX =
410
411const Coin &AccessByTxid(const CCoinsViewCache &view, const TxId &txid) {
412 for (uint32_t n = 0; n < MAX_OUTPUTS_PER_TX; n++) {
413 const Coin &alternate = view.AccessCoin(COutPoint(txid, n));
414 if (!alternate.IsSpent()) {
415 return alternate;
416 }
417 }
418
419 return coinEmpty;
420}
421
422bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint,
423 Coin &coin) const {
424 try {
425 return CCoinsViewBacked::GetCoin(outpoint, coin);
426 } catch (const std::runtime_error &e) {
427 for (const auto &f : m_err_callbacks) {
428 f();
429 }
430 LogPrintf("Error reading from database: %s\n", e.what());
431 // Starting the shutdown sequence and returning false to the caller
432 // would be interpreted as 'entry not found' (as opposed to unable to
433 // read data), and could lead to invalid interpretation. Just exit
434 // immediately, as we can't continue anyway, and all writes should be
435 // atomic.
436 std::abort();
437 }
438}
CCoinsView backed by another CCoinsView.
Definition: coins.h:343
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
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:47
CCoinsView * base
Definition: coins.h:345
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:44
bool BatchWrite(CoinsViewCacheCursor &cursor, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:50
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:34
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:363
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:100
const bool m_deterministic
Definition: coins.h:365
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:373
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:324
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:341
bool BatchWrite(CoinsViewCacheCursor &cursor, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:225
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:372
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:337
size_t cachedCoinsUsage
Definition: coins.h:381
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:74
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:91
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:298
CoinsCachePair m_sentinel
The starting sentinel of the flagged entry circular doubly linked list.
Definition: coins.h:377
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:69
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:310
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:146
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:366
CCoinsMap cacheCoins
Definition: coins.h:378
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:355
Cursor for iterating over CoinsView state.
Definition: coins.h:222
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:535
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:422
Abstract view on the open txout dataset.
Definition: coins.h:305
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 size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:339
virtual bool BatchWrite(CoinsViewCacheCursor &cursor, const BlockHash &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:22
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
A UTXO entry.
Definition: coins.h:29
uint32_t GetHeight() const
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:47
CTxOut & GetTxOut()
Definition: coins.h:50
bool IsSpent() const
Definition: coins.h:48
bool IsNull() const
Definition: uint256.h:32
static const size_t MAX_OUTPUTS_PER_TX
Definition: coins.cpp:408
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:411
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< 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:217
CCoinsMap::allocator_type::ResourceType CCoinsMapMemoryResource
Definition: coins.h:219
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:424
unsigned int nHeight
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:28
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1207
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:95
Coin coin
Definition: coins.h:135
static void SetFresh(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:166
static void SetDirty(CoinsCachePair &pair, CoinsCachePair &sentinel) noexcept
Definition: coins.h:162
Cursor for iterating over the linked list of flagged entries in CCoinsViewCache.
Definition: coins.h:255
CoinsCachePair * NextAndMaybeErase(CoinsCachePair &current) noexcept
Return the next entry after current, possibly erasing current.
Definition: coins.h:278
bool WillErase(CoinsCachePair &current) const noexcept
Definition: coins.h:293
CoinsCachePair * Begin() const noexcept
Definition: coins.h:272
CoinsCachePair * End() const noexcept
Definition: coins.h:275
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