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