Bitcoin Core  24.99.0
P2P Digital Currency
coins.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2022 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, bool erase) { 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, bool erase) { return base->BatchWrite(mapCoins, hashBlock, erase); }
32 std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
33 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }
34 
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)it->second.coin.nHeight,
103  (int64_t)it->second.coin.out.nValue,
104  (bool)it->second.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, bool erase) {
180  for (CCoinsMap::iterator it = mapCoins.begin();
181  it != mapCoins.end();
182  it = erase ? mapCoins.erase(it) : std::next(it)) {
183  // Ignore non-dirty entries (optimization).
184  if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
185  continue;
186  }
187  CCoinsMap::iterator itUs = cacheCoins.find(it->first);
188  if (itUs == cacheCoins.end()) {
189  // The parent cache does not have an entry, while the child cache does.
190  // We can ignore it if it's both spent and FRESH in the child
191  if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
192  // Create the coin in the parent cache, move the data up
193  // and mark it as dirty.
194  CCoinsCacheEntry& entry = cacheCoins[it->first];
195  if (erase) {
196  // The `move` call here is purely an optimization; we rely on the
197  // `mapCoins.erase` call in the `for` expression to actually remove
198  // the entry from the child map.
199  entry.coin = std::move(it->second.coin);
200  } else {
201  entry.coin = it->second.coin;
202  }
205  // We can mark it FRESH in the parent if it was FRESH in the child
206  // Otherwise it might have just been flushed from the parent's cache
207  // and already exist in the grandparent
208  if (it->second.flags & CCoinsCacheEntry::FRESH) {
210  }
211  }
212  } else {
213  // Found the entry in the parent cache
214  if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
215  // The coin was marked FRESH in the child cache, but the coin
216  // exists in the parent cache. If this ever happens, it means
217  // the FRESH flag was misapplied and there is a logic error in
218  // the calling code.
219  throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
220  }
221 
222  if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
223  // The grandparent cache does not have an entry, and the coin
224  // has been spent. We can just delete it from the parent cache.
225  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
226  cacheCoins.erase(itUs);
227  } else {
228  // A normal modification.
229  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
230  if (erase) {
231  // The `move` call here is purely an optimization; we rely on the
232  // `mapCoins.erase` call in the `for` expression to actually remove
233  // the entry from the child map.
234  itUs->second.coin = std::move(it->second.coin);
235  } else {
236  itUs->second.coin = it->second.coin;
237  }
238  cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
239  itUs->second.flags |= CCoinsCacheEntry::DIRTY;
240  // NOTE: It isn't safe to mark the coin as FRESH in the parent
241  // cache. If it already existed and was spent in the parent
242  // cache then marking it FRESH would prevent that spentness
243  // from being flushed to the grandparent.
244  }
245  }
246  }
247  hashBlock = hashBlockIn;
248  return true;
249 }
250 
252  bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/true);
253  if (fOk && !cacheCoins.empty()) {
254  /* BatchWrite must erase all cacheCoins elements when erase=true. */
255  throw std::logic_error("Not all cached coins were erased");
256  }
257  cachedCoinsUsage = 0;
258  return fOk;
259 }
260 
262 {
263  bool fOk = base->BatchWrite(cacheCoins, hashBlock, /*erase=*/false);
264  // Instead of clearing `cacheCoins` as we would in Flush(), just clear the
265  // FRESH/DIRTY flags of any coin that isn't spent.
266  for (auto it = cacheCoins.begin(); it != cacheCoins.end(); ) {
267  if (it->second.coin.IsSpent()) {
268  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
269  it = cacheCoins.erase(it);
270  } else {
271  it->second.flags = 0;
272  ++it;
273  }
274  }
275  return fOk;
276 }
277 
279 {
280  CCoinsMap::iterator it = cacheCoins.find(hash);
281  if (it != cacheCoins.end() && it->second.flags == 0) {
282  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
283  TRACE5(utxocache, uncache,
284  hash.hash.data(),
285  (uint32_t)hash.n,
286  (uint32_t)it->second.coin.nHeight,
287  (int64_t)it->second.coin.out.nValue,
288  (bool)it->second.coin.IsCoinBase());
289  cacheCoins.erase(it);
290  }
291 }
292 
293 unsigned int CCoinsViewCache::GetCacheSize() const {
294  return cacheCoins.size();
295 }
296 
298 {
299  if (!tx.IsCoinBase()) {
300  for (unsigned int i = 0; i < tx.vin.size(); i++) {
301  if (!HaveCoin(tx.vin[i].prevout)) {
302  return false;
303  }
304  }
305  }
306  return true;
307 }
308 
310 {
311  // Cache should be empty when we're calling this.
312  assert(cacheCoins.size() == 0);
313  cacheCoins.~CCoinsMap();
314  ::new (&cacheCoins) CCoinsMap();
315 }
316 
319 
320 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
321 {
322  COutPoint iter(txid, 0);
323  while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
324  const Coin& alternate = view.AccessCoin(iter);
325  if (!alternate.IsSpent()) return alternate;
326  ++iter.n;
327  }
328  return coinEmpty;
329 }
330 
331 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
332  try {
333  return CCoinsViewBacked::GetCoin(outpoint, coin);
334  } catch(const std::runtime_error& e) {
335  for (const auto& f : m_err_callbacks) {
336  f();
337  }
338  LogPrintf("Error reading from database: %s\n", e.what());
339  // Starting the shutdown sequence and returning false to the caller would be
340  // interpreted as 'entry not found' (as opposed to unable to read data), and
341  // could lead to invalid interpretation. Just exit immediately, as we can't
342  // continue anyway, and all writes should be atomic.
343  std::abort();
344  }
345 }
int ret
CCoinsView backed by another CCoinsView.
Definition: coins.h:194
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:26
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:33
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:28
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:30
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:32
CCoinsView * base
Definition: coins.h:196
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:31
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:29
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:25
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:219
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:126
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:278
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:35
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:297
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:67
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:179
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:293
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:169
size_t cachedCoinsUsage
Definition: coins.h:223
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:175
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:41
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:58
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:164
bool Flush()
Push the modifications applied to this cache to its base and wipe local state.
Definition: coins.cpp:251
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:37
bool Sync()
Push the modifications applied to this cache to its base while retaining the contents of this cache (...
Definition: coins.cpp:261
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
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:159
CCoinsMap cacheCoins
Definition: coins.h:220
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:150
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:309
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:365
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:331
Abstract view on the open txout dataset.
Definition: coins.h:157
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:13
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:15
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:19
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:188
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:17
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock, bool erase=true)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:16
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:14
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
uint32_t n
Definition: transaction.h:39
uint256 hash
Definition: transaction.h:38
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
const std::vector< CTxOut > vout
Definition: transaction.h:306
const uint256 & GetHash() const
Definition: transaction.h:337
bool IsCoinBase() const
Definition: transaction.h:350
const std::vector< CTxIn > vin
Definition: transaction.h:305
An output of a transaction.
Definition: transaction.h:158
A UTXO entry.
Definition: coins.h:31
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
size_t DynamicMemoryUsage() const
Definition: coins.h:83
constexpr bool IsNull() const
Definition: uint256.h:41
constexpr const unsigned char * data() const
Definition: uint256.h:64
256-bit opaque blob.
Definition: uint256.h:105
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT
Definition: coins.cpp:317
static const Coin coinEmpty
Definition: coins.cpp:148
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:320
static const size_t MAX_OUTPUTS_PER_BLOCK
Definition: coins.cpp:318
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
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
#define LogPrintf(...)
Definition: logging.h:236
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:1109
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
@ 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
#define TRACE5(context, event, a, b, c, d, e)
Definition: trace.h:33
assert(!tx.IsCoinBase())
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12