Bitcoin Core  22.99.0
P2P Digital Currency
coins.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2021 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 
7 #include <consensus/consensus.h>
8 #include <logging.h>
9 #include <random.h>
10 #include <util/trace.h>
11 #include <version.h>
12 
13 bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
15 std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
16 bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
17 std::unique_ptr<CCoinsViewCursor> CCoinsView::Cursor() const { return nullptr; }
18 
19 bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
20 {
21  Coin coin;
22  return GetCoin(outpoint, coin);
23 }
24 
26 bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
27 bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
29 std::vector<uint256> CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
30 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
31 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
32 std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
33 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
34 
35 CCoinsViewCache::CCoinsViewCache(CCoinsView *baseIn) : CCoinsViewBacked(baseIn), cachedCoinsUsage(0) {}
36 
39 }
40 
41 CCoinsMap::iterator CCoinsViewCache::FetchCoin(const COutPoint &outpoint) const {
42  CCoinsMap::iterator it = cacheCoins.find(outpoint);
43  if (it != cacheCoins.end())
44  return it;
45  Coin tmp;
46  if (!base->GetCoin(outpoint, tmp))
47  return cacheCoins.end();
48  CCoinsMap::iterator ret = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::forward_as_tuple(std::move(tmp))).first;
49  if (ret->second.coin.IsSpent()) {
50  // The parent only has an empty entry for this outpoint; we can consider our
51  // version as fresh.
52  ret->second.flags = CCoinsCacheEntry::FRESH;
53  }
54  cachedCoinsUsage += ret->second.coin.DynamicMemoryUsage();
55  return ret;
56 }
57 
58 bool CCoinsViewCache::GetCoin(const COutPoint &outpoint, Coin &coin) const {
59  CCoinsMap::const_iterator it = FetchCoin(outpoint);
60  if (it != cacheCoins.end()) {
61  coin = it->second.coin;
62  return !coin.IsSpent();
63  }
64  return false;
65 }
66 
67 void CCoinsViewCache::AddCoin(const COutPoint &outpoint, Coin&& coin, bool possible_overwrite) {
68  assert(!coin.IsSpent());
69  if (coin.out.scriptPubKey.IsUnspendable()) return;
70  CCoinsMap::iterator it;
71  bool inserted;
72  std::tie(it, inserted) = cacheCoins.emplace(std::piecewise_construct, std::forward_as_tuple(outpoint), std::tuple<>());
73  bool fresh = false;
74  if (!inserted) {
75  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
76  }
77  if (!possible_overwrite) {
78  if (!it->second.coin.IsSpent()) {
79  throw std::logic_error("Attempted to overwrite an unspent coin (when possible_overwrite is false)");
80  }
81  // If the coin exists in this cache as a spent coin and is DIRTY, then
82  // its spentness hasn't been flushed to the parent cache. We're
83  // re-adding the coin to this cache now but we can't mark it as FRESH.
84  // If we mark it FRESH and then spend it before the cache is flushed
85  // we would remove it from this cache and would never flush spentness
86  // to the parent cache.
87  //
88  // Re-adding a spent coin can happen in the case of a re-org (the coin
89  // is 'spent' when the block adding it is disconnected and then
90  // re-added when it is also added in a newly connected block).
91  //
92  // If the coin doesn't exist in the current cache, or is spent but not
93  // DIRTY, then it can be marked FRESH.
94  fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
95  }
96  it->second.coin = std::move(coin);
97  it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
98  cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
99  TRACE5(utxocache, add,
100  outpoint.hash.data(),
101  (uint32_t)outpoint.n,
102  (uint32_t)coin.nHeight,
103  (int64_t)coin.out.nValue,
104  (bool)coin.IsCoinBase());
105 }
106 
108  cachedCoinsUsage += coin.DynamicMemoryUsage();
109  cacheCoins.emplace(
110  std::piecewise_construct,
111  std::forward_as_tuple(std::move(outpoint)),
112  std::forward_as_tuple(std::move(coin), CCoinsCacheEntry::DIRTY));
113 }
114 
115 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
116  bool fCoinbase = tx.IsCoinBase();
117  const uint256& txid = tx.GetHash();
118  for (size_t i = 0; i < tx.vout.size(); ++i) {
119  bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
120  // Coinbase transactions can always be overwritten, in order to correctly
121  // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
122  cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
123  }
124 }
125 
126 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
127  CCoinsMap::iterator it = FetchCoin(outpoint);
128  if (it == cacheCoins.end()) return false;
129  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
130  TRACE5(utxocache, spent,
131  outpoint.hash.data(),
132  (uint32_t)outpoint.n,
133  (uint32_t)it->second.coin.nHeight,
134  (int64_t)it->second.coin.out.nValue,
135  (bool)it->second.coin.IsCoinBase());
136  if (moveout) {
137  *moveout = std::move(it->second.coin);
138  }
139  if (it->second.flags & CCoinsCacheEntry::FRESH) {
140  cacheCoins.erase(it);
141  } else {
142  it->second.flags |= CCoinsCacheEntry::DIRTY;
143  it->second.coin.Clear();
144  }
145  return true;
146 }
147 
148 static const Coin coinEmpty;
149 
150 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
151  CCoinsMap::const_iterator it = FetchCoin(outpoint);
152  if (it == cacheCoins.end()) {
153  return coinEmpty;
154  } else {
155  return it->second.coin;
156  }
157 }
158 
159 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
160  CCoinsMap::const_iterator it = FetchCoin(outpoint);
161  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
162 }
163 
164 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
165  CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
166  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
167 }
168 
170  if (hashBlock.IsNull())
172  return hashBlock;
173 }
174 
175 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
176  hashBlock = hashBlockIn;
177 }
178 
179 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
180  for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
181  // Ignore non-dirty entries (optimization).
182  if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
183  continue;
184  }
185  CCoinsMap::iterator itUs = cacheCoins.find(it->first);
186  if (itUs == cacheCoins.end()) {
187  // The parent cache does not have an entry, while the child cache does.
188  // We can ignore it if it's both spent and FRESH in the child
189  if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
190  // Create the coin in the parent cache, move the data up
191  // and mark it as dirty.
192  CCoinsCacheEntry& entry = cacheCoins[it->first];
193  entry.coin = std::move(it->second.coin);
196  // We can mark it FRESH in the parent if it was FRESH in the child
197  // Otherwise it might have just been flushed from the parent's cache
198  // and already exist in the grandparent
199  if (it->second.flags & CCoinsCacheEntry::FRESH) {
201  }
202  }
203  } else {
204  // Found the entry in the parent cache
205  if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
206  // The coin was marked FRESH in the child cache, but the coin
207  // exists in the parent cache. If this ever happens, it means
208  // the FRESH flag was misapplied and there is a logic error in
209  // the calling code.
210  throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
211  }
212 
213  if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
214  // The grandparent cache does not have an entry, and the coin
215  // has been spent. We can just delete it from the parent cache.
216  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
217  cacheCoins.erase(itUs);
218  } else {
219  // A normal modification.
220  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
221  itUs->second.coin = std::move(it->second.coin);
222  cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
223  itUs->second.flags |= CCoinsCacheEntry::DIRTY;
224  // NOTE: It isn't safe to mark the coin as FRESH in the parent
225  // cache. If it already existed and was spent in the parent
226  // cache then marking it FRESH would prevent that spentness
227  // from being flushed to the grandparent.
228  }
229  }
230  }
231  hashBlock = hashBlockIn;
232  return true;
233 }
234 
236  bool fOk = base->BatchWrite(cacheCoins, hashBlock);
237  cacheCoins.clear();
238  cachedCoinsUsage = 0;
239  return fOk;
240 }
241 
243 {
244  CCoinsMap::iterator it = cacheCoins.find(hash);
245  if (it != cacheCoins.end() && it->second.flags == 0) {
246  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
247  TRACE5(utxocache, uncache,
248  hash.hash.data(),
249  (uint32_t)hash.n,
250  (uint32_t)it->second.coin.nHeight,
251  (int64_t)it->second.coin.out.nValue,
252  (bool)it->second.coin.IsCoinBase());
253  cacheCoins.erase(it);
254  }
255 }
256 
257 unsigned int CCoinsViewCache::GetCacheSize() const {
258  return cacheCoins.size();
259 }
260 
262 {
263  if (!tx.IsCoinBase()) {
264  for (unsigned int i = 0; i < tx.vin.size(); i++) {
265  if (!HaveCoin(tx.vin[i].prevout)) {
266  return false;
267  }
268  }
269  }
270  return true;
271 }
272 
274 {
275  // Cache should be empty when we're calling this.
276  assert(cacheCoins.size() == 0);
277  cacheCoins.~CCoinsMap();
278  ::new (&cacheCoins) CCoinsMap();
279 }
280 
283 
284 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
285 {
286  COutPoint iter(txid, 0);
287  while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
288  const Coin& alternate = view.AccessCoin(iter);
289  if (!alternate.IsSpent()) return alternate;
290  ++iter.n;
291  }
292  return coinEmpty;
293 }
294 
295 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
296  try {
297  return CCoinsViewBacked::GetCoin(outpoint, coin);
298  } catch(const std::runtime_error& e) {
299  for (auto f : m_err_callbacks) {
300  f();
301  }
302  LogPrintf("Error reading from database: %s\n", e.what());
303  // Starting the shutdown sequence and returning false to the caller would be
304  // interpreted as 'entry not found' (as opposed to unable to read data), and
305  // could lead to invalid interpretation. Just exit immediately, as we can't
306  // continue anyway, and all writes should be atomic.
307  std::abort();
308  }
309 }
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:30
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1093
TRACE5
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:33
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
assert
assert(!tx.IsCoinBase())
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:257
CCoinsViewBacked::EstimateSize
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:33
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
CCoinsViewCache::CCoinsViewCache
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:35
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:159
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:67
COutPoint::hash
uint256 hash
Definition: transaction.h:29
base_blob::data
const unsigned char * data() const
Definition: uint256.h:55
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:221
CCoinsViewBacked::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
CCoinsViewCache::EmplaceCoinInternalDANGER
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:107
trace.h
CCoinsViewCache::AccessCoin
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:150
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:29
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:105
CCoinsViewCache::ReallocateCache
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:273
version.h
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
CCoinsView::HaveCoin
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:19
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:197
CCoinsView::GetCoin
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:157
AddCoins
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:115
CCoinsView::BatchWrite
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:16
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:315
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:58
CCoinsViewCache::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:179
random.h
CCoinsViewCache::SpendCoin
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:126
CTxOut
An output of a transaction.
Definition: transaction.h:128
Coin
A UTXO entry.
Definition: coins.h:30
coinEmpty
static const Coin coinEmpty
Definition: coins.cpp:148
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:37
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:271
CCoinsViewErrorCatcher::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:295
consensus.h
LogPrintf
#define LogPrintf(...)
Definition: logging.h:187
CCoinsView::GetHeadBlocks
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:15
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:164
CCoinsCacheEntry::flags
unsigned char flags
Definition: coins.h:106
CCoinsViewCache::hashBlock
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:220
uint256
256-bit opaque blob.
Definition: uint256.h:124
CCoinsViewBacked::Cursor
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:32
CCoinsView::EstimateSize
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:189
coins.h
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:25
CCoinsView::Cursor
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:17
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:224
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CCoinsViewCache::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:169
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:194
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:175
COutPoint::n
uint32_t n
Definition: transaction.h:30
CCoinsViewBacked::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:31
MAX_BLOCK_WEIGHT
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
CCoinsViewBacked::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:26
logging.h
CCoinsViewCache::HaveInputs
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:261
CCoinsMap
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
CCoinsViewBacked::GetHeadBlocks
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:29
CCoinsViewCache::Uncache
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:242
Coin::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: coins.h:83
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
CCoinsViewErrorCatcher::m_err_callbacks
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:356
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
AccessByTxid
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:284
MAX_OUTPUTS_PER_BLOCK
static const size_t MAX_OUTPUTS_PER_BLOCK
Definition: coins.cpp:282
CCoinsViewBacked::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:28
Coin::IsSpent
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
CCoinsCacheEntry::FRESH
@ 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
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:116
CCoinsViewCache::FetchCoin
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:41
CCoinsView::GetBestBlock
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:14
WITNESS_SCALE_FACTOR
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:103
MIN_TRANSACTION_OUTPUT_WEIGHT
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT
Definition: coins.cpp:281
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:235
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12