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