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