Bitcoin Core  0.18.99
P2P Digital Currency
coins.cpp
Go to the documentation of this file.
1 // Copyright (c) 2012-2018 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("Adding new coin that replaces non-pruned entry");
81  }
82  fresh = !(it->second.flags & CCoinsCacheEntry::DIRTY);
83  }
84  it->second.coin = std::move(coin);
85  it->second.flags |= CCoinsCacheEntry::DIRTY | (fresh ? CCoinsCacheEntry::FRESH : 0);
86  cachedCoinsUsage += it->second.coin.DynamicMemoryUsage();
87 }
88 
89 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check) {
90  bool fCoinbase = tx.IsCoinBase();
91  const uint256& txid = tx.GetHash();
92  for (size_t i = 0; i < tx.vout.size(); ++i) {
93  bool overwrite = check ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
94  // Always set the possible_overwrite flag to AddCoin for coinbase txn, in order to correctly
95  // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
96  cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
97  }
98 }
99 
100 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
101  CCoinsMap::iterator it = FetchCoin(outpoint);
102  if (it == cacheCoins.end()) return false;
103  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
104  if (moveout) {
105  *moveout = std::move(it->second.coin);
106  }
107  if (it->second.flags & CCoinsCacheEntry::FRESH) {
108  cacheCoins.erase(it);
109  } else {
110  it->second.flags |= CCoinsCacheEntry::DIRTY;
111  it->second.coin.Clear();
112  }
113  return true;
114 }
115 
116 static const Coin coinEmpty;
117 
118 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
119  CCoinsMap::const_iterator it = FetchCoin(outpoint);
120  if (it == cacheCoins.end()) {
121  return coinEmpty;
122  } else {
123  return it->second.coin;
124  }
125 }
126 
127 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
128  CCoinsMap::const_iterator it = FetchCoin(outpoint);
129  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
130 }
131 
132 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
133  CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
134  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
135 }
136 
138  if (hashBlock.IsNull())
140  return hashBlock;
141 }
142 
143 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
144  hashBlock = hashBlockIn;
145 }
146 
147 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
148  for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
149  // Ignore non-dirty entries (optimization).
150  if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
151  continue;
152  }
153  CCoinsMap::iterator itUs = cacheCoins.find(it->first);
154  if (itUs == cacheCoins.end()) {
155  // The parent cache does not have an entry, while the child does
156  // We can ignore it if it's both FRESH and pruned in the child
157  if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
158  // Otherwise we will need to create it in the parent
159  // and move the data up and mark it as dirty
160  CCoinsCacheEntry& entry = cacheCoins[it->first];
161  entry.coin = std::move(it->second.coin);
164  // We can mark it FRESH in the parent if it was FRESH in the child
165  // Otherwise it might have just been flushed from the parent's cache
166  // and already exist in the grandparent
167  if (it->second.flags & CCoinsCacheEntry::FRESH) {
169  }
170  }
171  } else {
172  // Assert that the child cache entry was not marked FRESH if the
173  // parent cache entry has unspent outputs. If this ever happens,
174  // it means the FRESH flag was misapplied and there is a logic
175  // error in the calling code.
176  if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
177  throw std::logic_error("FRESH flag misapplied to cache entry for base transaction with spendable outputs");
178  }
179 
180  // Found the entry in the parent cache
181  if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
182  // The grandparent does not have an entry, and the child is
183  // modified and being pruned. This means we can just delete
184  // it from the parent.
185  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
186  cacheCoins.erase(itUs);
187  } else {
188  // A normal modification.
189  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
190  itUs->second.coin = std::move(it->second.coin);
191  cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
192  itUs->second.flags |= CCoinsCacheEntry::DIRTY;
193  // NOTE: It is possible the child has a FRESH flag here in
194  // the event the entry we found in the parent is pruned. But
195  // we must not copy that FRESH flag to the parent as that
196  // pruned state likely still needs to be communicated to the
197  // grandparent.
198  }
199  }
200  }
201  hashBlock = hashBlockIn;
202  return true;
203 }
204 
206  bool fOk = base->BatchWrite(cacheCoins, hashBlock);
207  cacheCoins.clear();
208  cachedCoinsUsage = 0;
209  return fOk;
210 }
211 
213 {
214  CCoinsMap::iterator it = cacheCoins.find(hash);
215  if (it != cacheCoins.end() && it->second.flags == 0) {
216  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
217  cacheCoins.erase(it);
218  }
219 }
220 
221 unsigned int CCoinsViewCache::GetCacheSize() const {
222  return cacheCoins.size();
223 }
224 
226 {
227  if (tx.IsCoinBase())
228  return 0;
229 
230  CAmount nResult = 0;
231  for (unsigned int i = 0; i < tx.vin.size(); i++)
232  nResult += AccessCoin(tx.vin[i].prevout).out.nValue;
233 
234  return nResult;
235 }
236 
238 {
239  if (!tx.IsCoinBase()) {
240  for (unsigned int i = 0; i < tx.vin.size(); i++) {
241  if (!HaveCoin(tx.vin[i].prevout)) {
242  return false;
243  }
244  }
245  }
246  return true;
247 }
248 
251 
252 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
253 {
254  COutPoint iter(txid, 0);
255  while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
256  const Coin& alternate = view.AccessCoin(iter);
257  if (!alternate.IsSpent()) return alternate;
258  ++iter.n;
259  }
260  return coinEmpty;
261 }
262 
263 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
264  try {
265  return CCoinsViewBacked::GetCoin(outpoint, coin);
266  } catch(const std::runtime_error& e) {
267  for (auto f : m_err_callbacks) {
268  f();
269  }
270  LogPrintf("Error reading from database: %s\n", e.what());
271  // Starting the shutdown sequence and returning false to the caller would be
272  // interpreted as 'entry not found' (as opposed to unable to read data), and
273  // could lead to invalid interpretation. Just exit immediately, as we can't
274  // continue anyway, and all writes should be atomic.
275  std::abort();
276  }
277 }
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:263
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:27
CAmount nValue
Definition: transaction.h:136
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:252
bool IsSpent() const
Definition: coins.h:76
uint64_t GetRand(uint64_t nMax) noexcept
Definition: random.cpp:665
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:68
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:36
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
Definition: coins.h:104
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 a pruned one if not found.
Definition: coins.cpp:118
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:205
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:27
unsigned int nHeight
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:38
CTxOut out
unspent transaction output
Definition: coins.h:34
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:132
void AddCoins(CCoinsViewCache &cache, const CTransaction &tx, int nHeight, bool check)
Utility function to add all of a transaction&#39;s outputs to a cache.
Definition: coins.cpp:89
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:144
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:16
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:116
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:237
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:147
bool IsNull() const
Definition: uint256.h:31
bool IsCoinBase() const
Definition: transaction.h:337
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:100
const std::vector< CTxIn > vin
Definition: transaction.h:287
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1005
Definition: coins.h:110
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:143
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:221
CCoinsMap cacheCoins
Definition: coins.h:210
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:146
CCoinsView * base
Definition: coins.h:186
const uint256 & GetHash() const
Definition: transaction.h:322
uint32_t n
Definition: transaction.h:22
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:123
const std::vector< CTxOut > vout
Definition: transaction.h:288
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:133
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:24
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:137
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:121
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:209
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:59
Definition: coins.h:111
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:178
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:212
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
CAmount GetValueIn(const CTransaction &tx) const
Amount of bitcoins coming in to a transaction Note that lightweight clients may not know anything bes...
Definition: coins.cpp:225
static const size_t MAX_OUTPUTS_PER_BLOCK
Definition: coins.cpp:250
size_t cachedCoinsUsage
Definition: coins.h:213
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:270
CCoinsView backed by another CCoinsView.
Definition: coins.h:183
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:202
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT
Definition: coins.cpp:249
auto it
Definition: validation.cpp:366
unsigned char flags
Definition: coins.h:107
Coin coin
Definition: coins.h:106
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:127
Cursor for iterating over CoinsView state.
Definition: coins.h:126