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 return error(
"%s: previous block header not found; expected %s",
141 __func__, expected_block_hash.ToString());
150 "6955e5a6c6cdf3f2574dd08e")}) ||
154 "ef14935db8de83d6f9306f2f")})};
157 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
158 const auto &tx{block.
vtx.at(i)};
161 if (is_bip30_block && tx->IsCoinBase()) {
167 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
168 const CTxOut &out{tx->vout[j]};
169 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
171 COutPoint outpoint{tx->GetId(), j};
174 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
182 if (tx->IsCoinBase()) {
186 coin.GetTxOut().nValue;
195 if (!tx->IsCoinBase()) {
196 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
198 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
199 Coin coin{tx_undo.vprevout[j]};
200 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
201 tx->vin[j].prevout.GetN()};
223 const Amount unclaimed_rewards{
230 std::pair<BlockHash, DBVal> value;
238 value.second.total_new_outputs_ex_coinbase_amount =
241 value.second.total_unspendables_genesis_block =
245 value.second.total_unspendables_unclaimed_rewards =
250 value.second.muhash = out;
255 return m_db->Write(DBHeightKey(pindex->
nHeight), value);
259 const std::string &index_name,
260 int start_height,
int stop_height) {
261 DBHeightKey key{start_height};
264 for (
int height = start_height; height <= stop_height; ++height) {
265 if (!db_it.
GetKey(key) || key.height != height) {
266 return error(
"%s: unexpected key in %s: expected (%c, %d)",
270 std::pair<BlockHash, DBVal> value;
272 return error(
"%s: unable to read value in %s at key (%c, %d)",
276 batch.
Write(DBHashKey(value.first), std::move(value.second));
288 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
298 if (!
m_db->WriteBatch(batch)) {
311 return error(
"%s: Failed to read block %s from disk", __func__,
312 iter_tip->GetBlockHash().ToString());
317 iter_tip = iter_tip->GetAncestor(iter_tip->nHeight - 1);
318 }
while (new_tip != iter_tip);
329 std::pair<BlockHash, DBVal> read_out;
330 if (!
db.Read(DBHeightKey(block.
height), read_out)) {
333 if (read_out.first == block.
hash) {
334 result = std::move(read_out.second);
340 return db.Read(DBHashKey(block.
hash), result);
343std::optional<CCoinsStats>
347 stats.index_used =
true;
355 stats.hashSerialized = entry.muhash;
356 stats.nTransactionOutputs = entry.transaction_output_count;
357 stats.nBogoSize = entry.bogo_size;
358 stats.nTotalAmount = entry.total_amount;
359 stats.total_subsidy = entry.total_subsidy;
360 stats.total_unspendable_amount = entry.total_unspendable_amount;
361 stats.total_prevout_spent_amount = entry.total_prevout_spent_amount;
362 stats.total_new_outputs_ex_coinbase_amount =
363 entry.total_new_outputs_ex_coinbase_amount;
364 stats.total_coinbase_amount = entry.total_coinbase_amount;
365 stats.total_unspendables_genesis_block =
366 entry.total_unspendables_genesis_block;
367 stats.total_unspendables_bip30 = entry.total_unspendables_bip30;
368 stats.total_unspendables_scripts = entry.total_unspendables_scripts;
369 stats.total_unspendables_unclaimed_rewards =
370 entry.total_unspendables_unclaimed_rewards;
376 const std::optional<interfaces::BlockKey> &block) {
383 "%s: Cannot read current %s state; index may be corrupted",
392 "%s: Cannot read current %s state; index may be corrupted",
398 if (entry.muhash != out) {
400 "%s: Cannot read current %s state; index may be corrupted",
411 entry.total_new_outputs_ex_coinbase_amount;
414 entry.total_unspendables_genesis_block;
418 entry.total_unspendables_unclaimed_rewards;
435 std::pair<BlockHash, DBVal> read_out;
437 const Amount block_subsidy{
447 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
452 if (read_out.first != expected_block_hash) {
453 LogPrintf(
"WARNING: previous block header belongs to unexpected "
454 "block %s; expected %s\n",
455 read_out.first.ToString(),
456 expected_block_hash.ToString());
458 if (!
m_db->Read(DBHashKey(expected_block_hash), read_out)) {
459 return error(
"%s: previous block header not found; expected %s",
460 __func__, expected_block_hash.ToString());
466 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
467 const auto &tx{block.
vtx.at(i)};
469 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
470 const CTxOut &out{tx->vout[j]};
471 COutPoint outpoint{tx->GetId(), j};
472 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
476 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
484 if (tx->IsCoinBase()) {
488 coin.GetTxOut().nValue;
497 if (!tx->IsCoinBase()) {
498 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
500 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
501 Coin coin{tx_undo.vprevout[j]};
502 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
503 tx->vin[j].prevout.GetN()};
516 const Amount unclaimed_rewards{
527 Assert(read_out.second.muhash == out);
530 read_out.second.transaction_output_count);
535 read_out.second.total_unspendable_amount);
537 read_out.second.total_prevout_spent_amount);
539 read_out.second.total_new_outputs_ex_coinbase_amount);
542 read_out.second.total_unspendables_genesis_block);
544 read_out.second.total_unspendables_bip30);
546 read_out.second.total_unspendables_scripts);
548 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.
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
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
bool CommitInternal(CDBBatch &batch) override
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
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
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.
bool error(const char *fmt, const Args &...args)
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...
CDataStream 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.
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 &, char)=delete
void ser_writedata8(Stream &s, uint8_t obj)
Lowest-level serialization and conversion.
uint32_t ser_readdata32be(Stream &s)
void Serialize(Stream &, char)=delete
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)