Bitcoin ABC  0.24.11
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 
305  // Cache should be empty when we're calling this.
306  assert(cacheCoins.size() == 0);
307  cacheCoins.~CCoinsMap();
308  ::new (&cacheCoins) CCoinsMap();
309 }
310 
311 // TODO: merge with similar definition in undo.h.
312 static const size_t MAX_OUTPUTS_PER_TX =
314 
315 const Coin &AccessByTxid(const CCoinsViewCache &view, const TxId &txid) {
316  for (uint32_t n = 0; n < MAX_OUTPUTS_PER_TX; n++) {
317  const Coin &alternate = view.AccessCoin(COutPoint(txid, n));
318  if (!alternate.IsSpent()) {
319  return alternate;
320  }
321  }
322 
323  return coinEmpty;
324 }
325 
327  Coin &coin) const {
328  try {
329  return CCoinsViewBacked::GetCoin(outpoint, coin);
330  } catch (const std::runtime_error &e) {
331  for (auto f : m_err_callbacks) {
332  f();
333  }
334  LogPrintf("Error reading from database: %s\n", e.what());
335  // Starting the shutdown sequence and returning false to the caller
336  // would be interpreted as 'entry not found' (as opposed to unable to
337  // read data), and could lead to invalid interpretation. Just exit
338  // immediately, as we can't continue anyway, and all writes should be
339  // atomic.
340  std::abort();
341  }
342 }
CCoinsViewCache::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:209
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:45
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1182
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:210
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:286
CCoinsViewBacked::EstimateSize
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:55
k1
static const uint8_t k1[32]
Definition: chacha_poly_aead.cpp:20
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:13
CCoinsViewCache::CCoinsViewCache
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:63
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:188
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:103
MAX_OUTPUTS_PER_TX
static const size_t MAX_OUTPUTS_PER_TX
Definition: coins.cpp:312
CCoinsViewBacked::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:48
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:238
CCoinsViewBacked::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:36
CCoinsViewCache::hashBlock
BlockHash hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:237
CCoinsViewCache::AccessCoin
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Definition: coins.cpp:180
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:26
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:122
CCoinsViewCache::ReallocateCache
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:304
version.h
GetRand
uint64_t GetRand(uint64_t nMax) noexcept
Generate a uniform random integer in the range [0..range).
Definition: random.cpp:650
SaltedOutpointHasher::SaltedOutpointHasher
SaltedOutpointHasher()
Definition: coins.cpp:59
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:194
CCoinsView::HaveCoin
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:27
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:214
CCoinsView::GetCoin
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:12
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:175
AddCoins
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:144
CCoinsViewCursor
Cursor for iterating over CoinsView state.
Definition: coins.h:155
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:256
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:94
random.h
CCoinsViewCache::SpendCoin
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:160
MAX_TX_SIZE
static const uint64_t MAX_TX_SIZE
The maximum allowed size for a transaction, in bytes.
Definition: consensus.h:14
CCoinsViewBacked::Cursor
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:52
CTxOut
An output of a transaction.
Definition: transaction.h:130
CTransaction::GetId
const TxId GetId() const
Definition: transaction.h:244
Coin
A UTXO entry.
Definition: coins.h:27
coinEmpty
static const Coin coinEmpty
Definition: coins.cpp:178
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:66
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:211
CCoinsViewErrorCatcher::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:326
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:133
CCoinsViewBacked::GetHeadBlocks
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:42
consensus.h
CCoinsView::GetHeadBlocks
virtual std::vector< BlockHash > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:18
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:193
TxId
A TxId is the identifier of a transaction.
Definition: txid.h:14
CCoinsView::Cursor
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:24
CCoinsCacheEntry::flags
uint8_t flags
Definition: coins.h:123
CCoinsView::BatchWrite
virtual bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:21
CCoinsView::EstimateSize
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:208
coins.h
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:32
BlockHash
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:241
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:30
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:231
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:212
CCoinsViewCache::GetBestBlock
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:198
CCoinsViewBacked::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:33
logging.h
CCoinsViewCache::HaveInputs
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
CCoinsMap
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:152
CCoinsViewCache::Uncache
void Uncache(const COutPoint &outpoint)
Removes the UTXO with the given outpoint from the cache, if it is not modified.
Definition: coins.cpp:278
Coin::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: coins.h:67
CCoinsViewErrorCatcher::m_err_callbacks
std::vector< std::function< void()> > m_err_callbacks
A list of callbacks to execute upon leveldb read error.
Definition: coins.h:373
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
CScript::IsUnspendable
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack.
Definition: script.h:548
Coin::IsSpent
bool IsSpent() const
Definition: coins.h:46
CCoinsCacheEntry::FRESH
@ 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:143
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:133
CCoinsViewCache::SetBestBlock
void SetBestBlock(const BlockHash &hashBlock)
Definition: coins.cpp:205
CCoinsViewCache::FetchCoin
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:71
Coin::GetTxOut
CTxOut & GetTxOut()
Definition: coins.h:48
AccessByTxid
const Coin & AccessByTxid(const CCoinsViewCache &view, const TxId &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:315
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
CCoinsView::GetBestBlock
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:15
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:120
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:271
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:11
CCoinsViewBacked::GetBestBlock
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:39