7#include <chainparams.h>
19#include <validation.h>
33 uint64_t transaction_output_count;
37 Amount total_unspendable_amount;
38 Amount total_prevout_spent_amount;
39 Amount total_new_outputs_ex_coinbase_amount;
40 Amount total_coinbase_amount;
41 Amount total_unspendables_genesis_block;
42 Amount total_unspendables_bip30;
43 Amount total_unspendables_scripts;
44 Amount total_unspendables_unclaimed_rewards;
53 READWRITE(obj.total_prevout_spent_amount);
54 READWRITE(obj.total_new_outputs_ex_coinbase_amount);
56 READWRITE(obj.total_unspendables_genesis_block);
58 READWRITE(obj.total_unspendables_scripts);
59 READWRITE(obj.total_unspendables_unclaimed_rewards);
66 explicit DBHeightKey(
int height_in) : height(height_in) {}
68 template <
typename Stream>
void Serialize(Stream &s)
const {
73 template <
typename Stream>
void Unserialize(Stream &s) {
76 throw std::ios_base::failure(
77 "Invalid format for coinstatsindex DB height key");
86 explicit DBHashKey(
const BlockHash &hash_in) : block_hash(hash_in) {}
92 throw std::ios_base::failure(
93 "Invalid format for coinstatsindex DB hash key");
105 size_t n_cache_size,
bool f_memory,
bool f_wipe)
110 m_db = std::make_unique<CoinStatsIndex::DB>(path /
"db", n_cache_size,
117 const Amount block_subsidy{
127 std::pair<BlockHash, DBVal> read_out;
128 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
133 if (read_out.first != expected_block_hash) {
134 LogPrintf(
"WARNING: previous block header belongs to unexpected "
135 "block %s; expected %s\n",
136 read_out.first.ToString(),
137 expected_block_hash.ToString());
139 if (!
m_db->Read(DBHashKey(expected_block_hash), read_out)) {
140 LogError(
"%s: previous block header not found; expected %s\n",
141 __func__, expected_block_hash.ToString());
151 "6955e5a6c6cdf3f2574dd08e")}) ||
155 "ef14935db8de83d6f9306f2f")})};
158 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
159 const auto &tx{block.
vtx.at(i)};
162 if (is_bip30_block && tx->IsCoinBase()) {
168 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
169 const CTxOut &out{tx->vout[j]};
170 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
172 COutPoint outpoint{tx->GetId(), j};
175 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
183 if (tx->IsCoinBase()) {
187 coin.GetTxOut().nValue;
196 if (!tx->IsCoinBase()) {
197 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
199 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
200 Coin coin{tx_undo.vprevout[j]};
201 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
202 tx->vin[j].prevout.GetN()};
224 const Amount unclaimed_rewards{
231 std::pair<BlockHash, DBVal> value;
239 value.second.total_new_outputs_ex_coinbase_amount =
242 value.second.total_unspendables_genesis_block =
246 value.second.total_unspendables_unclaimed_rewards =
251 value.second.muhash = out;
256 return m_db->Write(DBHeightKey(pindex->
nHeight), value);
260 const std::string &index_name,
261 int start_height,
int stop_height) {
262 DBHeightKey key{start_height};
265 for (
int height = start_height; height <= stop_height; ++height) {
266 if (!db_it.
GetKey(key) || key.height != height) {
267 LogError(
"%s: unexpected key in %s: expected (%c, %d)\n", __func__,
272 std::pair<BlockHash, DBVal> value;
274 LogError(
"%s: unable to read value in %s at key (%c, %d)\n",
279 batch.
Write(DBHashKey(value.first), std::move(value.second));
291 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
301 if (!
m_db->WriteBatch(batch)) {
314 LogError(
"%s: Failed to read block %s from disk\n", __func__,
315 iter_tip->GetBlockHash().ToString());
321 iter_tip = iter_tip->GetAncestor(iter_tip->nHeight - 1);
322 }
while (new_tip != iter_tip);
333 std::pair<BlockHash, DBVal> read_out;
334 if (!
db.Read(DBHeightKey(block.
height), read_out)) {
337 if (read_out.first == block.
hash) {
338 result = std::move(read_out.second);
344 return db.Read(DBHashKey(block.
hash), result);
347std::optional<CCoinsStats>
351 stats.index_used =
true;
359 stats.hashSerialized = entry.muhash;
360 stats.nTransactionOutputs = entry.transaction_output_count;
361 stats.nBogoSize = entry.bogo_size;
362 stats.nTotalAmount = entry.total_amount;
363 stats.total_subsidy = entry.total_subsidy;
364 stats.total_unspendable_amount = entry.total_unspendable_amount;
365 stats.total_prevout_spent_amount = entry.total_prevout_spent_amount;
366 stats.total_new_outputs_ex_coinbase_amount =
367 entry.total_new_outputs_ex_coinbase_amount;
368 stats.total_coinbase_amount = entry.total_coinbase_amount;
369 stats.total_unspendables_genesis_block =
370 entry.total_unspendables_genesis_block;
371 stats.total_unspendables_bip30 = entry.total_unspendables_bip30;
372 stats.total_unspendables_scripts = entry.total_unspendables_scripts;
373 stats.total_unspendables_unclaimed_rewards =
374 entry.total_unspendables_unclaimed_rewards;
380 const std::optional<interfaces::BlockKey> &block) {
387 "%s: Cannot read current %s state; index may be corrupted\n",
397 "%s: Cannot read current %s state; index may be corrupted\n",
404 if (entry.muhash != out) {
406 "%s: Cannot read current %s state; index may be corrupted\n",
418 entry.total_new_outputs_ex_coinbase_amount;
421 entry.total_unspendables_genesis_block;
425 entry.total_unspendables_unclaimed_rewards;
442 std::pair<BlockHash, DBVal> read_out;
444 const Amount block_subsidy{
454 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
459 if (read_out.first != expected_block_hash) {
460 LogPrintf(
"WARNING: previous block header belongs to unexpected "
461 "block %s; expected %s\n",
462 read_out.first.ToString(),
463 expected_block_hash.ToString());
465 if (!
m_db->Read(DBHashKey(expected_block_hash), read_out)) {
466 LogError(
"%s: previous block header not found; expected %s\n",
467 __func__, expected_block_hash.ToString());
474 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
475 const auto &tx{block.
vtx.at(i)};
477 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
478 const CTxOut &out{tx->vout[j]};
479 COutPoint outpoint{tx->GetId(), j};
480 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
484 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
492 if (tx->IsCoinBase()) {
496 coin.GetTxOut().nValue;
505 if (!tx->IsCoinBase()) {
506 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
508 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
509 Coin coin{tx_undo.vprevout[j]};
510 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
511 tx->vin[j].prevout.GetN()};
524 const Amount unclaimed_rewards{
535 Assert(read_out.second.muhash == out);
538 read_out.second.transaction_output_count);
543 read_out.second.total_unspendable_amount);
545 read_out.second.total_prevout_spent_amount);
547 read_out.second.total_new_outputs_ex_coinbase_amount);
550 read_out.second.total_unspendables_genesis_block);
552 read_out.second.total_unspendables_bip30);
554 read_out.second.total_unspendables_scripts);
556 read_out.second.total_unspendables_unclaimed_rewards);
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Base class for indices of blockchain data.
const std::string & GetName() const LIFETIMEBOUND
Get the name of the index for display in logs.
Chainstate * m_chainstate
virtual bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip)
Rewind index to an earlier chain tip during a chain reorg.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Undo information for a CBlock.
std::vector< CTxUndo > vtxundo
Batch of changes queued to be written to a CDBWrapper.
void Write(const K &key, const V &value)
An output of a transaction.
node::BlockManager & m_blockman
Reference to a BlockManager instance which itself is shared across all Chainstate instances.
Amount m_total_prevout_spent_amount
Amount m_total_unspendables_bip30
Amount m_total_unspendables_genesis_block
CoinStatsIndex(std::unique_ptr< interfaces::Chain > chain, size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
uint64_t m_transaction_output_count
bool Rewind(const CBlockIndex *current_tip, const CBlockIndex *new_tip) override
Rewind index to an earlier chain tip during a chain reorg.
Amount m_total_coinbase_amount
bool ReverseBlock(const CBlock &block, const CBlockIndex *pindex)
std::unique_ptr< BaseIndex::DB > m_db
std::optional< kernel::CCoinsStats > LookUpStats(const CBlockIndex *block_index) const
bool CustomCommit(CDBBatch &batch) override
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
Amount m_total_unspendables_scripts
bool WriteBlock(const CBlock &block, const CBlockIndex *pindex) override
Write update index entries for a newly connected block.
bool CustomInit(const std::optional< interfaces::BlockKey > &block) override
Initialize internal state from the database and block index.
Amount m_total_new_outputs_ex_coinbase_amount
Amount m_total_unspendable_amount
Amount m_total_unspendables_unclaimed_rewards
MuHash3072 & Remove(Span< const uint8_t > in) noexcept
void Finalize(uint256 &out) noexcept
MuHash3072 & Insert(Span< const uint8_t > in) noexcept
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
static constexpr uint8_t DB_MUHASH
static bool LookUpOne(const CDBWrapper &db, const interfaces::BlockKey &block, DBVal &result)
std::unique_ptr< CoinStatsIndex > g_coin_stats_index
The global UTXO set hash object.
static bool CopyHeightIndexToHashIndex(CDBIterator &db_it, CDBBatch &batch, const std::string &index_name, int start_height, int stop_height)
static constexpr uint8_t DB_BLOCK_HASH
static constexpr uint8_t DB_BLOCK_HEIGHT
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
DataStream TxOutSer(const COutPoint &outpoint, const Coin &coin)
uint64_t GetBogoSize(const CScript &script_pub_key)
Implement std::hash so RCUPtr can be used as a key for maps or sets.
void Serialize(Stream &, V)=delete
uint8_t ser_readdata8(Stream &s)
void ser_writedata32be(Stream &s, uint32_t obj)
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
void Unserialize(Stream &, V)=delete
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
uint32_t ser_readdata32be(Stream &s)
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
A BlockHash is a unqiue identifier for a block.
Hash/height pair to help track and identify blocks.
uint256 uint256S(const char *str)
uint256 from const char *.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)