LCOV - code coverage report
Current view: top level - src/index - coinstatsindex.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 0.0 % 240 0
Test Date: 2025-11-10 04:08:56 Functions: 0.0 % 15 0
Branches: 0.0 % 160 0

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

Generated by: LCOV version 2.0-1