Branch data Line data Source code
1 : : // Copyright (c) 2020-present 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 <index/coinstatsindex.h>
6 : :
7 : : #include <arith_uint256.h>
8 : : #include <chain.h>
9 : : #include <chainparams.h>
10 : : #include <coins.h>
11 : : #include <common/args.h>
12 : : #include <consensus/amount.h>
13 : : #include <crypto/muhash.h>
14 : : #include <dbwrapper.h>
15 : : #include <index/base.h>
16 : : #include <index/db_key.h>
17 : : #include <interfaces/chain.h>
18 : : #include <interfaces/types.h>
19 : : #include <kernel/coinstats.h>
20 : : #include <primitives/block.h>
21 : : #include <primitives/transaction.h>
22 : : #include <script/script.h>
23 : : #include <serialize.h>
24 : : #include <uint256.h>
25 : : #include <undo.h>
26 : : #include <util/check.h>
27 : : #include <util/fs.h>
28 : : #include <util/log.h>
29 : : #include <validation.h>
30 : :
31 : : #include <compare>
32 : : #include <limits>
33 : : #include <string>
34 : : #include <utility>
35 : : #include <vector>
36 : :
37 : : using kernel::ApplyCoinHash;
38 : : using kernel::CCoinsStats;
39 : : using kernel::GetBogoSize;
40 : : using kernel::RemoveCoinHash;
41 : :
42 : : static constexpr uint8_t DB_MUHASH{'M'};
43 : :
44 : : namespace {
45 : :
46 : : struct DBVal {
47 : : uint256 muhash{uint256::ZERO};
48 : : uint64_t transaction_output_count{0};
49 : : uint64_t bogo_size{0};
50 : : CAmount total_amount{0};
51 : : CAmount total_subsidy{0};
52 : : arith_uint256 total_prevout_spent_amount{0};
53 : : arith_uint256 total_new_outputs_ex_coinbase_amount{0};
54 : : arith_uint256 total_coinbase_amount{0};
55 : : CAmount total_unspendables_genesis_block{0};
56 : : CAmount total_unspendables_bip30{0};
57 : : CAmount total_unspendables_scripts{0};
58 : : CAmount total_unspendables_unclaimed_rewards{0};
59 : :
60 : 25538 : SERIALIZE_METHODS(DBVal, obj)
61 : : {
62 : 12769 : uint256 prevout_spent, new_outputs, coinbase;
63 : 12769 : SER_WRITE(obj, prevout_spent = ArithToUint256(obj.total_prevout_spent_amount));
64 : 12769 : SER_WRITE(obj, new_outputs = ArithToUint256(obj.total_new_outputs_ex_coinbase_amount));
65 : 12769 : SER_WRITE(obj, coinbase = ArithToUint256(obj.total_coinbase_amount));
66 : :
67 : 12769 : READWRITE(obj.muhash);
68 : 12769 : READWRITE(obj.transaction_output_count);
69 : 12769 : READWRITE(obj.bogo_size);
70 : 12769 : READWRITE(obj.total_amount);
71 : 12769 : READWRITE(obj.total_subsidy);
72 : 12769 : READWRITE(prevout_spent);
73 : 12769 : READWRITE(new_outputs);
74 : 12769 : READWRITE(coinbase);
75 : 12769 : READWRITE(obj.total_unspendables_genesis_block);
76 : 12769 : READWRITE(obj.total_unspendables_bip30);
77 : 12769 : READWRITE(obj.total_unspendables_scripts);
78 : 12769 : READWRITE(obj.total_unspendables_unclaimed_rewards);
79 : :
80 : 12769 : SER_READ(obj, obj.total_prevout_spent_amount = UintToArith256(prevout_spent));
81 : 12769 : SER_READ(obj, obj.total_new_outputs_ex_coinbase_amount = UintToArith256(new_outputs));
82 : 12769 : SER_READ(obj, obj.total_coinbase_amount = UintToArith256(coinbase));
83 : 12769 : }
84 : : };
85 : : }; // namespace
86 : :
87 : 56 : CoinStatsIndex::CoinStatsIndex(std::unique_ptr<interfaces::Chain> chain, size_t n_cache_size, bool f_memory, bool f_wipe)
88 [ + - + - ]: 56 : : BaseIndex(std::move(chain), "coinstatsindex", "coinstatsidx")
89 : : {
90 : : // An earlier version of the index used "indexes/coinstats" but it contained
91 : : // a bug and is superseded by a fixed version at "indexes/coinstatsindex".
92 : : // The original index is kept around until the next release in case users
93 : : // decide to downgrade their node.
94 [ + - + - ]: 224 : auto old_path = gArgs.GetDataDirNet() / "indexes" / "coinstats";
95 [ + - + + ]: 56 : if (fs::exists(old_path)) {
96 : : // TODO: Change this to deleting the old index with v31.
97 [ - + + - ]: 2 : LogWarning("Old version of coinstatsindex found at %s. This folder can be safely deleted unless you " \
98 : : "plan to downgrade your node to version 29 or lower.", fs::PathToString(old_path));
99 : : }
100 [ + - + - ]: 224 : fs::path path{gArgs.GetDataDirNet() / "indexes" / "coinstatsindex"};
101 [ + - ]: 56 : fs::create_directories(path);
102 : :
103 [ + - + - : 224 : m_db = std::make_unique<CoinStatsIndex::DB>(path / "db", n_cache_size, f_memory, f_wipe);
+ + ]
104 : 113 : }
105 : :
106 : 12161 : bool CoinStatsIndex::CustomAppend(const interfaces::BlockInfo& block)
107 : : {
108 : 12161 : const CAmount block_subsidy{GetBlockSubsidy(block.height, Params().GetConsensus())};
109 : 12161 : m_total_subsidy += block_subsidy;
110 : :
111 : : // Ignore genesis block
112 [ + + ]: 12161 : if (block.height > 0) {
113 : 12139 : uint256 expected_block_hash{*Assert(block.prev_hash)};
114 [ - + ]: 12139 : if (m_current_block_hash != expected_block_hash) {
115 [ # # # # ]: 0 : LogError("previous block header belongs to unexpected block %s; expected %s",
116 : : m_current_block_hash.ToString(), expected_block_hash.ToString());
117 : 0 : return false;
118 : : }
119 : :
120 : : // Add the new utxos created from the block
121 [ - + ]: 12139 : assert(block.data);
122 [ - + + + ]: 24635 : for (size_t i = 0; i < block.data->vtx.size(); ++i) {
123 : 12496 : const auto& tx{block.data->vtx.at(i)};
124 [ + + ]: 12496 : const bool is_coinbase{tx->IsCoinBase()};
125 : :
126 : : // Skip duplicate txid coinbase transactions (BIP30).
127 [ + + - + ]: 12496 : if (is_coinbase && IsBIP30Unspendable(block.hash, block.height)) {
128 : 0 : m_total_unspendables_bip30 += block_subsidy;
129 : 0 : continue;
130 : : }
131 : :
132 [ - + + + ]: 37244 : for (uint32_t j = 0; j < tx->vout.size(); ++j) {
133 : 24748 : const CTxOut& out{tx->vout[j]};
134 : 24748 : const Coin coin{out, block.height, is_coinbase};
135 [ + + ]: 24748 : const COutPoint outpoint{tx->GetHash(), j};
136 : :
137 : : // Skip unspendable coins
138 [ + + ]: 24748 : if (coin.out.scriptPubKey.IsUnspendable()) {
139 : 12139 : m_total_unspendables_scripts += coin.out.nValue;
140 : 12139 : continue;
141 : : }
142 : :
143 [ + - ]: 12609 : ApplyCoinHash(m_muhash, outpoint, coin);
144 : :
145 [ + + ]: 12609 : if (is_coinbase) {
146 : 12142 : m_total_coinbase_amount += coin.out.nValue;
147 : : } else {
148 : 467 : m_total_new_outputs_ex_coinbase_amount += coin.out.nValue;
149 : : }
150 : :
151 : 12609 : ++m_transaction_output_count;
152 : 12609 : m_total_amount += coin.out.nValue;
153 [ + - ]: 12609 : m_bogo_size += GetBogoSize(coin.out.scriptPubKey);
154 : 24748 : }
155 : :
156 : : // The coinbase tx has no undo data since no former output is spent
157 [ + + ]: 12496 : if (!is_coinbase) {
158 : 357 : const auto& tx_undo{Assert(block.undo_data)->vtxundo.at(i - 1)};
159 : :
160 [ - + + + ]: 714 : for (size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
161 : 357 : const Coin& coin{tx_undo.vprevout[j]};
162 : 357 : const COutPoint outpoint{tx->vin[j].prevout.hash, tx->vin[j].prevout.n};
163 : :
164 : 357 : RemoveCoinHash(m_muhash, outpoint, coin);
165 : :
166 : 357 : m_total_prevout_spent_amount += coin.out.nValue;
167 : :
168 : 357 : --m_transaction_output_count;
169 : 357 : m_total_amount -= coin.out.nValue;
170 : 357 : m_bogo_size -= GetBogoSize(coin.out.scriptPubKey);
171 : : }
172 : : }
173 : : }
174 : : } else {
175 : : // genesis block
176 : 22 : m_total_unspendables_genesis_block += block_subsidy;
177 : : }
178 : :
179 : : // If spent prevouts + block subsidy are still a higher amount than
180 : : // new outputs + coinbase + current unspendable amount this means
181 : : // the miner did not claim the full block reward. Unclaimed block
182 : : // rewards are also unspendable.
183 : 12161 : const CAmount temp_total_unspendable_amount{m_total_unspendables_genesis_block + m_total_unspendables_bip30 + m_total_unspendables_scripts + m_total_unspendables_unclaimed_rewards};
184 : 36483 : const arith_uint256 unclaimed_rewards{(m_total_prevout_spent_amount + m_total_subsidy) - (m_total_new_outputs_ex_coinbase_amount + m_total_coinbase_amount + temp_total_unspendable_amount)};
185 [ - + ]: 12161 : assert(unclaimed_rewards <= arith_uint256(std::numeric_limits<CAmount>::max()));
186 : 12161 : m_total_unspendables_unclaimed_rewards += static_cast<CAmount>(unclaimed_rewards.GetLow64());
187 : :
188 : 12161 : std::pair<uint256, DBVal> value;
189 : 12161 : value.first = block.hash;
190 : 12161 : value.second.transaction_output_count = m_transaction_output_count;
191 : 12161 : value.second.bogo_size = m_bogo_size;
192 : 12161 : value.second.total_amount = m_total_amount;
193 : 12161 : value.second.total_subsidy = m_total_subsidy;
194 : 12161 : value.second.total_prevout_spent_amount = m_total_prevout_spent_amount;
195 : 12161 : value.second.total_new_outputs_ex_coinbase_amount = m_total_new_outputs_ex_coinbase_amount;
196 : 12161 : value.second.total_coinbase_amount = m_total_coinbase_amount;
197 : 12161 : value.second.total_unspendables_genesis_block = m_total_unspendables_genesis_block;
198 : 12161 : value.second.total_unspendables_bip30 = m_total_unspendables_bip30;
199 : 12161 : value.second.total_unspendables_scripts = m_total_unspendables_scripts;
200 : 12161 : value.second.total_unspendables_unclaimed_rewards = m_total_unspendables_unclaimed_rewards;
201 : :
202 : 12161 : uint256 out;
203 : 12161 : m_muhash.Finalize(out);
204 : 12161 : value.second.muhash = out;
205 : :
206 : 12161 : m_current_block_hash = block.hash;
207 : :
208 : : // Intentionally do not update DB_MUHASH here so it stays in sync with
209 : : // DB_BEST_BLOCK, and the index is not corrupted if there is an unclean shutdown.
210 : 12161 : m_db->Write(index_util::DBHeightKey(block.height), value);
211 : 12161 : return true;
212 : : }
213 : :
214 : 163 : bool CoinStatsIndex::CustomRemove(const interfaces::BlockInfo& block)
215 : : {
216 : 163 : CDBBatch batch(*m_db);
217 [ + - + - ]: 163 : std::unique_ptr<CDBIterator> db_it(m_db->NewIterator());
218 : :
219 : : // During a reorg, copy the block's hash digest from the height index to the hash index,
220 : : // ensuring it's still accessible after the height index entry is overwritten.
221 [ + - + - ]: 163 : if (!index_util::CopyHeightIndexToHashIndex<DBVal>(*db_it, batch, m_name, block.height)) {
222 : : return false;
223 : : }
224 : :
225 [ + - ]: 163 : m_db->WriteBatch(batch);
226 : :
227 [ + - - + ]: 163 : if (!RevertBlock(block)) {
228 : 0 : return false; // failure cause logged internally
229 : : }
230 : :
231 : : return true;
232 : 163 : }
233 : :
234 : 82 : std::optional<CCoinsStats> CoinStatsIndex::LookUpStats(const CBlockIndex& block_index) const
235 : : {
236 : 82 : CCoinsStats stats{block_index.nHeight, block_index.GetBlockHash()};
237 : 82 : stats.index_used = true;
238 : :
239 : 82 : DBVal entry;
240 [ + + ]: 82 : if (!index_util::LookUpOne(*m_db, {block_index.GetBlockHash(), block_index.nHeight}, entry)) {
241 : 1 : return std::nullopt;
242 : : }
243 : :
244 : 81 : stats.hashSerialized = entry.muhash;
245 : 81 : stats.nTransactionOutputs = entry.transaction_output_count;
246 : 81 : stats.nBogoSize = entry.bogo_size;
247 : 81 : stats.total_amount = entry.total_amount;
248 : 81 : stats.total_subsidy = entry.total_subsidy;
249 : 81 : stats.total_prevout_spent_amount = entry.total_prevout_spent_amount;
250 : 81 : stats.total_new_outputs_ex_coinbase_amount = entry.total_new_outputs_ex_coinbase_amount;
251 : 81 : stats.total_coinbase_amount = entry.total_coinbase_amount;
252 : 81 : stats.total_unspendables_genesis_block = entry.total_unspendables_genesis_block;
253 : 81 : stats.total_unspendables_bip30 = entry.total_unspendables_bip30;
254 : 81 : stats.total_unspendables_scripts = entry.total_unspendables_scripts;
255 : 81 : stats.total_unspendables_unclaimed_rewards = entry.total_unspendables_unclaimed_rewards;
256 : :
257 : 81 : return stats;
258 : : }
259 : :
260 : 61 : bool CoinStatsIndex::CustomInit(const std::optional<interfaces::BlockRef>& block)
261 : : {
262 [ + + ]: 61 : if (!m_db->Read(DB_MUHASH, m_muhash)) {
263 : : // Check that the cause of the read failure is that the key does not
264 : : // exist. Any other errors indicate database corruption or a disk
265 : : // failure, and starting the index would cause further corruption.
266 [ - + ]: 25 : if (m_db->Exists(DB_MUHASH)) {
267 : 0 : LogError("Cannot read current %s state; index may be corrupted",
268 : : GetName());
269 : 0 : return false;
270 : : }
271 : : }
272 : :
273 [ + + ]: 61 : if (block) {
274 : 36 : DBVal entry;
275 [ - + ]: 36 : if (!index_util::LookUpOne(*m_db, *block, entry)) {
276 : 0 : LogError("Cannot read current %s state; index may be corrupted",
277 : : GetName());
278 : 0 : return false;
279 : : }
280 : :
281 : 36 : uint256 out;
282 : 36 : m_muhash.Finalize(out);
283 [ + - ]: 36 : if (entry.muhash != out) {
284 : 0 : LogError("Cannot read current %s state; index may be corrupted",
285 : : GetName());
286 : 0 : return false;
287 : : }
288 : :
289 : 36 : m_transaction_output_count = entry.transaction_output_count;
290 : 36 : m_bogo_size = entry.bogo_size;
291 : 36 : m_total_amount = entry.total_amount;
292 : 36 : m_total_subsidy = entry.total_subsidy;
293 : 36 : m_total_prevout_spent_amount = entry.total_prevout_spent_amount;
294 : 36 : m_total_new_outputs_ex_coinbase_amount = entry.total_new_outputs_ex_coinbase_amount;
295 : 36 : m_total_coinbase_amount = entry.total_coinbase_amount;
296 : 36 : m_total_unspendables_genesis_block = entry.total_unspendables_genesis_block;
297 : 36 : m_total_unspendables_bip30 = entry.total_unspendables_bip30;
298 : 36 : m_total_unspendables_scripts = entry.total_unspendables_scripts;
299 : 36 : m_total_unspendables_unclaimed_rewards = entry.total_unspendables_unclaimed_rewards;
300 : 36 : m_current_block_hash = block->hash;
301 : : }
302 : :
303 : : return true;
304 : : }
305 : :
306 : 137 : bool CoinStatsIndex::CustomCommit(CDBBatch& batch)
307 : : {
308 : : // DB_MUHASH should always be committed in a batch together with DB_BEST_BLOCK
309 : : // to prevent an inconsistent state of the DB.
310 : 137 : batch.Write(DB_MUHASH, m_muhash);
311 : 137 : return true;
312 : : }
313 : :
314 : 12515 : interfaces::Chain::NotifyOptions CoinStatsIndex::CustomOptions()
315 : : {
316 : 12515 : interfaces::Chain::NotifyOptions options;
317 : 12515 : options.connect_undo_data = true;
318 : 12515 : options.disconnect_data = true;
319 : 12515 : options.disconnect_undo_data = true;
320 : 12515 : return options;
321 : : }
322 : :
323 : : // Revert a single block as part of a reorg
324 : 163 : bool CoinStatsIndex::RevertBlock(const interfaces::BlockInfo& block)
325 : : {
326 : 163 : std::pair<uint256, DBVal> read_out;
327 : :
328 : : // Ignore genesis block
329 [ + - ]: 163 : if (block.height > 0) {
330 [ + - ]: 163 : if (!m_db->Read(index_util::DBHeightKey(block.height - 1), read_out)) {
331 : : return false;
332 : : }
333 : :
334 : 163 : uint256 expected_block_hash{*block.prev_hash};
335 [ - + ]: 163 : if (read_out.first != expected_block_hash) {
336 [ # # # # ]: 0 : LogWarning("previous block header belongs to unexpected block %s; expected %s",
337 : : read_out.first.ToString(), expected_block_hash.ToString());
338 : :
339 [ # # ]: 0 : if (!m_db->Read(index_util::DBHashKey(expected_block_hash), read_out)) {
340 [ # # ]: 0 : LogError("previous block header not found; expected %s",
341 : : expected_block_hash.ToString());
342 : 0 : return false;
343 : : }
344 : : }
345 : : }
346 : :
347 : : // Roll back muhash by removing the new UTXOs that were created by the
348 : : // block and reapplying the old UTXOs that were spent by the block
349 [ - + ]: 163 : assert(block.data);
350 [ - + ]: 163 : assert(block.undo_data);
351 [ - + + + ]: 330 : for (size_t i = 0; i < block.data->vtx.size(); ++i) {
352 : 167 : const auto& tx{block.data->vtx.at(i)};
353 [ + + ]: 167 : const bool is_coinbase{tx->IsCoinBase()};
354 : :
355 [ + + - + ]: 167 : if (is_coinbase && IsBIP30Unspendable(block.hash, block.height)) {
356 : 0 : continue;
357 : : }
358 : :
359 [ - + + + ]: 498 : for (uint32_t j = 0; j < tx->vout.size(); ++j) {
360 : 331 : const CTxOut& out{tx->vout[j]};
361 : 331 : const COutPoint outpoint{tx->GetHash(), j};
362 : 331 : const Coin coin{out, block.height, is_coinbase};
363 : :
364 [ + + ]: 331 : if (!coin.out.scriptPubKey.IsUnspendable()) {
365 [ + - ]: 168 : RemoveCoinHash(m_muhash, outpoint, coin);
366 : : }
367 : 331 : }
368 : :
369 : : // The coinbase tx has no undo data since no former output is spent
370 [ + + ]: 167 : if (!is_coinbase) {
371 : 4 : const auto& tx_undo{block.undo_data->vtxundo.at(i - 1)};
372 : :
373 [ - + + + ]: 8 : for (size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
374 : 4 : const Coin& coin{tx_undo.vprevout[j]};
375 : 4 : const COutPoint outpoint{tx->vin[j].prevout.hash, tx->vin[j].prevout.n};
376 : 4 : ApplyCoinHash(m_muhash, outpoint, coin);
377 : : }
378 : : }
379 : : }
380 : :
381 : : // Check that the rolled back muhash is consistent with the DB read out
382 : 163 : uint256 out;
383 : 163 : m_muhash.Finalize(out);
384 [ - + ]: 163 : Assert(read_out.second.muhash == out);
385 : :
386 : : // Apply the other values from the DB to the member variables
387 : 163 : m_transaction_output_count = read_out.second.transaction_output_count;
388 : 163 : m_total_amount = read_out.second.total_amount;
389 : 163 : m_bogo_size = read_out.second.bogo_size;
390 : 163 : m_total_subsidy = read_out.second.total_subsidy;
391 : 163 : m_total_prevout_spent_amount = read_out.second.total_prevout_spent_amount;
392 : 163 : m_total_new_outputs_ex_coinbase_amount = read_out.second.total_new_outputs_ex_coinbase_amount;
393 : 163 : m_total_coinbase_amount = read_out.second.total_coinbase_amount;
394 : 163 : m_total_unspendables_genesis_block = read_out.second.total_unspendables_genesis_block;
395 : 163 : m_total_unspendables_bip30 = read_out.second.total_unspendables_bip30;
396 : 163 : m_total_unspendables_scripts = read_out.second.total_unspendables_scripts;
397 : 163 : m_total_unspendables_unclaimed_rewards = read_out.second.total_unspendables_unclaimed_rewards;
398 : 163 : m_current_block_hash = *block.prev_hash;
399 : :
400 : 163 : return true;
401 : : }
|