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