Bitcoin Core  22.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 std::unique_ptr<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); }
31 std::unique_ptr<CCoinsViewCursor> CCoinsViewBacked::Cursor() const { return base->Cursor(); }
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 
101  cachedCoinsUsage += coin.DynamicMemoryUsage();
102  cacheCoins.emplace(
103  std::piecewise_construct,
104  std::forward_as_tuple(std::move(outpoint)),
105  std::forward_as_tuple(std::move(coin), CCoinsCacheEntry::DIRTY));
106 }
107 
108 void AddCoins(CCoinsViewCache& cache, const CTransaction &tx, int nHeight, bool check_for_overwrite) {
109  bool fCoinbase = tx.IsCoinBase();
110  const uint256& txid = tx.GetHash();
111  for (size_t i = 0; i < tx.vout.size(); ++i) {
112  bool overwrite = check_for_overwrite ? cache.HaveCoin(COutPoint(txid, i)) : fCoinbase;
113  // Coinbase transactions can always be overwritten, in order to correctly
114  // deal with the pre-BIP30 occurrences of duplicate coinbase transactions.
115  cache.AddCoin(COutPoint(txid, i), Coin(tx.vout[i], nHeight, fCoinbase), overwrite);
116  }
117 }
118 
119 bool CCoinsViewCache::SpendCoin(const COutPoint &outpoint, Coin* moveout) {
120  CCoinsMap::iterator it = FetchCoin(outpoint);
121  if (it == cacheCoins.end()) return false;
122  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
123  if (moveout) {
124  *moveout = std::move(it->second.coin);
125  }
126  if (it->second.flags & CCoinsCacheEntry::FRESH) {
127  cacheCoins.erase(it);
128  } else {
129  it->second.flags |= CCoinsCacheEntry::DIRTY;
130  it->second.coin.Clear();
131  }
132  return true;
133 }
134 
135 static const Coin coinEmpty;
136 
137 const Coin& CCoinsViewCache::AccessCoin(const COutPoint &outpoint) const {
138  CCoinsMap::const_iterator it = FetchCoin(outpoint);
139  if (it == cacheCoins.end()) {
140  return coinEmpty;
141  } else {
142  return it->second.coin;
143  }
144 }
145 
146 bool CCoinsViewCache::HaveCoin(const COutPoint &outpoint) const {
147  CCoinsMap::const_iterator it = FetchCoin(outpoint);
148  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
149 }
150 
151 bool CCoinsViewCache::HaveCoinInCache(const COutPoint &outpoint) const {
152  CCoinsMap::const_iterator it = cacheCoins.find(outpoint);
153  return (it != cacheCoins.end() && !it->second.coin.IsSpent());
154 }
155 
157  if (hashBlock.IsNull())
159  return hashBlock;
160 }
161 
162 void CCoinsViewCache::SetBestBlock(const uint256 &hashBlockIn) {
163  hashBlock = hashBlockIn;
164 }
165 
166 bool CCoinsViewCache::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlockIn) {
167  for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); it = mapCoins.erase(it)) {
168  // Ignore non-dirty entries (optimization).
169  if (!(it->second.flags & CCoinsCacheEntry::DIRTY)) {
170  continue;
171  }
172  CCoinsMap::iterator itUs = cacheCoins.find(it->first);
173  if (itUs == cacheCoins.end()) {
174  // The parent cache does not have an entry, while the child cache does.
175  // We can ignore it if it's both spent and FRESH in the child
176  if (!(it->second.flags & CCoinsCacheEntry::FRESH && it->second.coin.IsSpent())) {
177  // Create the coin in the parent cache, move the data up
178  // and mark it as dirty.
179  CCoinsCacheEntry& entry = cacheCoins[it->first];
180  entry.coin = std::move(it->second.coin);
183  // We can mark it FRESH in the parent if it was FRESH in the child
184  // Otherwise it might have just been flushed from the parent's cache
185  // and already exist in the grandparent
186  if (it->second.flags & CCoinsCacheEntry::FRESH) {
188  }
189  }
190  } else {
191  // Found the entry in the parent cache
192  if ((it->second.flags & CCoinsCacheEntry::FRESH) && !itUs->second.coin.IsSpent()) {
193  // The coin was marked FRESH in the child cache, but the coin
194  // exists in the parent cache. If this ever happens, it means
195  // the FRESH flag was misapplied and there is a logic error in
196  // the calling code.
197  throw std::logic_error("FRESH flag misapplied to coin that exists in parent cache");
198  }
199 
200  if ((itUs->second.flags & CCoinsCacheEntry::FRESH) && it->second.coin.IsSpent()) {
201  // The grandparent cache does not have an entry, and the coin
202  // has been spent. We can just delete it from the parent cache.
203  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
204  cacheCoins.erase(itUs);
205  } else {
206  // A normal modification.
207  cachedCoinsUsage -= itUs->second.coin.DynamicMemoryUsage();
208  itUs->second.coin = std::move(it->second.coin);
209  cachedCoinsUsage += itUs->second.coin.DynamicMemoryUsage();
210  itUs->second.flags |= CCoinsCacheEntry::DIRTY;
211  // NOTE: It isn't safe to mark the coin as FRESH in the parent
212  // cache. If it already existed and was spent in the parent
213  // cache then marking it FRESH would prevent that spentness
214  // from being flushed to the grandparent.
215  }
216  }
217  }
218  hashBlock = hashBlockIn;
219  return true;
220 }
221 
223  bool fOk = base->BatchWrite(cacheCoins, hashBlock);
224  cacheCoins.clear();
225  cachedCoinsUsage = 0;
226  return fOk;
227 }
228 
230 {
231  CCoinsMap::iterator it = cacheCoins.find(hash);
232  if (it != cacheCoins.end() && it->second.flags == 0) {
233  cachedCoinsUsage -= it->second.coin.DynamicMemoryUsage();
234  cacheCoins.erase(it);
235  }
236 }
237 
238 unsigned int CCoinsViewCache::GetCacheSize() const {
239  return cacheCoins.size();
240 }
241 
243 {
244  if (!tx.IsCoinBase()) {
245  for (unsigned int i = 0; i < tx.vin.size(); i++) {
246  if (!HaveCoin(tx.vin[i].prevout)) {
247  return false;
248  }
249  }
250  }
251  return true;
252 }
253 
255 {
256  // Cache should be empty when we're calling this.
257  assert(cacheCoins.size() == 0);
258  cacheCoins.~CCoinsMap();
259  ::new (&cacheCoins) CCoinsMap();
260 }
261 
264 
265 const Coin& AccessByTxid(const CCoinsViewCache& view, const uint256& txid)
266 {
267  COutPoint iter(txid, 0);
268  while (iter.n < MAX_OUTPUTS_PER_BLOCK) {
269  const Coin& alternate = view.AccessCoin(iter);
270  if (!alternate.IsSpent()) return alternate;
271  ++iter.n;
272  }
273  return coinEmpty;
274 }
275 
276 bool CCoinsViewErrorCatcher::GetCoin(const COutPoint &outpoint, Coin &coin) const {
277  try {
278  return CCoinsViewBacked::GetCoin(outpoint, coin);
279  } catch(const std::runtime_error& e) {
280  for (auto f : m_err_callbacks) {
281  f();
282  }
283  LogPrintf("Error reading from database: %s\n", e.what());
284  // Starting the shutdown sequence and returning false to the caller would be
285  // interpreted as 'entry not found' (as opposed to unable to read data), and
286  // could lead to invalid interpretation. Just exit immediately, as we can't
287  // continue anyway, and all writes should be atomic.
288  std::abort();
289  }
290 }
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:29
GetSerializeSize
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
CCoinsViewCache::GetCacheSize
unsigned int GetCacheSize() const
Calculate the size of the cache (in number of transaction outputs)
Definition: coins.cpp:238
CCoinsViewBacked::EstimateSize
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Definition: coins.cpp:32
nHeight
unsigned int nHeight
Definition: mempool_eviction.cpp:14
CCoinsViewCache::CCoinsViewCache
CCoinsViewCache(CCoinsView *baseIn)
Definition: coins.cpp:34
CCoinsViewCache::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:146
CCoinsViewCache::AddCoin
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
Definition: coins.cpp:66
CCoinsViewCache::cacheCoins
CCoinsMap cacheCoins
Definition: coins.h:221
CCoinsViewBacked::HaveCoin
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
Definition: coins.cpp:26
CCoinsViewCache::EmplaceCoinInternalDANGER
void EmplaceCoinInternalDANGER(COutPoint &&outpoint, Coin &&coin)
Emplace a coin into cacheCoins without performing any checks, marking the emplaced coin as dirty.
Definition: coins.cpp:100
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:137
memusage::DynamicUsage
static size_t DynamicUsage(const int8_t &v)
Dynamic memory usage for built-in types is zero.
Definition: memusage.h:29
CCoinsCacheEntry::coin
Coin coin
Definition: coins.h:105
CCoinsViewCache::ReallocateCache
void ReallocateCache()
Force a reallocation of the cache map.
Definition: coins.cpp:254
version.h
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
CCoinsView::HaveCoin
virtual bool HaveCoin(const COutPoint &outpoint) const
Just check whether a given outpoint is unspent.
Definition: coins.cpp:18
CCoinsViewBacked::base
CCoinsView * base
Definition: coins.h:197
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:157
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:108
CCoinsView::BatchWrite
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock)
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:15
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:315
CCoinsViewCache::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:57
CCoinsViewCache::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:166
random.h
CCoinsViewCache::SpendCoin
bool SpendCoin(const COutPoint &outpoint, Coin *moveto=nullptr)
Spend a coin.
Definition: coins.cpp:119
CTxOut
An output of a transaction.
Definition: transaction.h:128
Coin
A UTXO entry.
Definition: coins.h:30
coinEmpty
static const Coin coinEmpty
Definition: coins.cpp:135
CCoinsViewCache::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Calculate the size of the cache (in bytes)
Definition: coins.cpp:36
CTransaction::vout
const std::vector< CTxOut > vout
Definition: transaction.h:271
CCoinsViewErrorCatcher::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:276
consensus.h
LogPrintf
#define LogPrintf(...)
Definition: logging.h:184
CCoinsView::GetHeadBlocks
virtual std::vector< uint256 > GetHeadBlocks() const
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:14
CCoinsViewCache::HaveCoinInCache
bool HaveCoinInCache(const COutPoint &outpoint) const
Check if we have the given utxo already loaded in this cache.
Definition: coins.cpp:151
CCoinsCacheEntry::flags
unsigned char flags
Definition: coins.h:106
CCoinsViewCache::hashBlock
uint256 hashBlock
Make mutable so that we can "fill the cache" even from Get-methods declared as "const".
Definition: coins.h:220
uint256
256-bit opaque blob.
Definition: uint256.h:124
CCoinsViewBacked::Cursor
std::unique_ptr< CCoinsViewCursor > Cursor() const override
Get a cursor to iterate over the whole state.
Definition: coins.cpp:31
CCoinsView::EstimateSize
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:189
coins.h
CCoinsViewBacked::CCoinsViewBacked
CCoinsViewBacked(CCoinsView *viewIn)
Definition: coins.cpp:24
CCoinsView::Cursor
virtual std::unique_ptr< CCoinsViewCursor > Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:16
CCoinsViewCache::cachedCoinsUsage
size_t cachedCoinsUsage
Definition: coins.h:224
base_blob::IsNull
bool IsNull() const
Definition: uint256.h:31
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:213
CCoinsViewCache::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:156
CCoinsViewBacked
CCoinsView backed by another CCoinsView.
Definition: coins.h:194
CCoinsViewCache::SetBestBlock
void SetBestBlock(const uint256 &hashBlock)
Definition: coins.cpp:162
COutPoint::n
uint32_t n
Definition: transaction.h:30
CCoinsViewBacked::BatchWrite
bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override
Do a bulk modification (multiple Coin changes + BestBlock change).
Definition: coins.cpp:30
MAX_BLOCK_WEIGHT
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
Definition: consensus.h:15
CCoinsViewBacked::GetCoin
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
Definition: coins.cpp:25
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:242
CCoinsMap
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher > CCoinsMap
Definition: coins.h:134
CCoinsViewBacked::GetHeadBlocks
std::vector< uint256 > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
Definition: coins.cpp:28
assert
assert(s1.IsAddrV1Compatible())
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:229
Coin::DynamicMemoryUsage
size_t DynamicMemoryUsage() const
Definition: coins.h:83
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:302
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:356
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
AccessByTxid
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:265
MAX_OUTPUTS_PER_BLOCK
static const size_t MAX_OUTPUTS_PER_BLOCK
Definition: coins.cpp:263
CCoinsViewBacked::GetBestBlock
uint256 GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:27
Coin::IsSpent
bool IsSpent() const
Either this coin never existed (see e.g.
Definition: coins.h:79
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:126
CCoinsCacheEntry::DIRTY
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
Definition: coins.h:116
CCoinsViewCache::FetchCoin
CCoinsMap::iterator FetchCoin(const COutPoint &outpoint) const
Definition: coins.cpp:40
CCoinsView::GetBestBlock
virtual uint256 GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:13
WITNESS_SCALE_FACTOR
static const int WITNESS_SCALE_FACTOR
Definition: consensus.h:21
CCoinsCacheEntry
A Coin in one level of the coins database caching hierarchy.
Definition: coins.h:103
MIN_TRANSACTION_OUTPUT_WEIGHT
static const size_t MIN_TRANSACTION_OUTPUT_WEIGHT
Definition: coins.cpp:262
CCoinsViewCache::Flush
bool Flush()
Push the modifications applied to this cache to its base.
Definition: coins.cpp:222
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12