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");
109 m_db = std::make_unique<CoinStatsIndex::DB>(path /
"db", n_cache_size,
116 const Amount block_subsidy{
126 std::pair<BlockHash, DBVal> read_out;
127 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
132 if (read_out.first != expected_block_hash) {
133 LogPrintf(
"WARNING: previous block header belongs to unexpected "
134 "block %s; expected %s\n",
135 read_out.first.ToString(),
136 expected_block_hash.ToString());
138 if (!
m_db->Read(DBHashKey(expected_block_hash), read_out)) {
139 return error(
"%s: previous block header not found; expected %s",
140 __func__, expected_block_hash.ToString());
149 "6955e5a6c6cdf3f2574dd08e")}) ||
153 "ef14935db8de83d6f9306f2f")})};
156 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
157 const auto &tx{block.
vtx.at(i)};
160 if (is_bip30_block && tx->IsCoinBase()) {
166 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
167 const CTxOut &out{tx->vout[j]};
168 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
170 COutPoint outpoint{tx->GetId(), j};
173 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
181 if (tx->IsCoinBase()) {
185 coin.GetTxOut().nValue;
194 if (!tx->IsCoinBase()) {
195 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
197 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
198 Coin coin{tx_undo.vprevout[j]};
199 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
200 tx->vin[j].prevout.GetN()};
222 const Amount unclaimed_rewards{
229 std::pair<BlockHash, DBVal> value;
237 value.second.total_new_outputs_ex_coinbase_amount =
240 value.second.total_unspendables_genesis_block =
244 value.second.total_unspendables_unclaimed_rewards =
249 value.second.muhash = out;
254 return m_db->Write(DBHeightKey(pindex->
nHeight), value);
258 const std::string &index_name,
259 int start_height,
int stop_height) {
260 DBHeightKey key{start_height};
263 for (
int height = start_height; height <= stop_height; ++height) {
264 if (!db_it.
GetKey(key) || key.height != height) {
265 return error(
"%s: unexpected key in %s: expected (%c, %d)",
269 std::pair<BlockHash, DBVal> value;
271 return error(
"%s: unable to read value in %s at key (%c, %d)",
275 batch.
Write(DBHashKey(value.first), std::move(value.second));
287 std::unique_ptr<CDBIterator> db_it(
m_db->NewIterator());
297 if (!
m_db->WriteBatch(batch)) {
310 return error(
"%s: Failed to read block %s from disk", __func__,
311 iter_tip->GetBlockHash().ToString());
316 iter_tip = iter_tip->GetAncestor(iter_tip->nHeight - 1);
317 }
while (new_tip != iter_tip);
328 std::pair<BlockHash, DBVal> read_out;
329 if (!
db.Read(DBHeightKey(block_index->
nHeight), read_out)) {
333 result = std::move(read_out.second);
342std::optional<CCoinsStats>
346 stats.index_used =
true;
353 stats.hashSerialized = entry.muhash;
354 stats.nTransactionOutputs = entry.transaction_output_count;
355 stats.nBogoSize = entry.bogo_size;
356 stats.nTotalAmount = entry.total_amount;
357 stats.total_subsidy = entry.total_subsidy;
358 stats.total_unspendable_amount = entry.total_unspendable_amount;
359 stats.total_prevout_spent_amount = entry.total_prevout_spent_amount;
360 stats.total_new_outputs_ex_coinbase_amount =
361 entry.total_new_outputs_ex_coinbase_amount;
362 stats.total_coinbase_amount = entry.total_coinbase_amount;
363 stats.total_unspendables_genesis_block =
364 entry.total_unspendables_genesis_block;
365 stats.total_unspendables_bip30 = entry.total_unspendables_bip30;
366 stats.total_unspendables_scripts = entry.total_unspendables_scripts;
367 stats.total_unspendables_unclaimed_rewards =
368 entry.total_unspendables_unclaimed_rewards;
380 "%s: Cannot read current %s state; index may be corrupted",
395 "%s: Cannot read current %s state; index may be corrupted",
401 if (entry.muhash != out) {
403 "%s: Cannot read current %s state; index may be corrupted",
414 entry.total_new_outputs_ex_coinbase_amount;
417 entry.total_unspendables_genesis_block;
421 entry.total_unspendables_unclaimed_rewards;
438 std::pair<BlockHash, DBVal> read_out;
440 const Amount block_subsidy{
450 if (!
m_db->Read(DBHeightKey(pindex->
nHeight - 1), read_out)) {
455 if (read_out.first != expected_block_hash) {
456 LogPrintf(
"WARNING: previous block header belongs to unexpected "
457 "block %s; expected %s\n",
458 read_out.first.ToString(),
459 expected_block_hash.ToString());
461 if (!
m_db->Read(DBHashKey(expected_block_hash), read_out)) {
462 return error(
"%s: previous block header not found; expected %s",
463 __func__, expected_block_hash.ToString());
469 for (
size_t i = 0; i < block.
vtx.size(); ++i) {
470 const auto &tx{block.
vtx.at(i)};
472 for (uint32_t j = 0; j < tx->vout.size(); ++j) {
473 const CTxOut &out{tx->vout[j]};
474 COutPoint outpoint{tx->GetId(), j};
475 Coin coin{out,
static_cast<uint32_t
>(pindex->
nHeight),
479 if (coin.GetTxOut().scriptPubKey.IsUnspendable()) {
487 if (tx->IsCoinBase()) {
491 coin.GetTxOut().nValue;
500 if (!tx->IsCoinBase()) {
501 const auto &tx_undo{block_undo.
vtxundo.at(i - 1)};
503 for (
size_t j = 0; j < tx_undo.vprevout.size(); ++j) {
504 Coin coin{tx_undo.vprevout[j]};
505 COutPoint outpoint{tx->vin[j].prevout.GetTxId(),
506 tx->vin[j].prevout.GetN()};
519 const Amount unclaimed_rewards{
530 Assert(read_out.second.muhash == out);
533 read_out.second.transaction_output_count);
538 read_out.second.total_unspendable_amount);
540 read_out.second.total_prevout_spent_amount);
542 read_out.second.total_new_outputs_ex_coinbase_amount);
545 read_out.second.total_unspendables_genesis_block);
547 read_out.second.total_unspendables_bip30);
549 read_out.second.total_unspendables_scripts);
551 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.
virtual bool Init()
Initialize internal state from the database and block index.
virtual bool CommitInternal(CDBBatch &batch)
Virtual method called internally by Commit that can be overridden to atomically commit more index sta...
Chainstate * m_chainstate
const CBlockIndex * CurrentIndex()
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
const char * GetName() const override
Get the name of the index for display in logs.
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
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
CoinStatsIndex(size_t n_cache_size, bool f_memory=false, bool f_wipe=false)
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.
Amount m_total_new_outputs_ex_coinbase_amount
Amount m_total_unspendable_amount
Amount m_total_unspendables_unclaimed_rewards
bool Init() override
Initialize internal state from the database and block index.
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 bool LookUpOne(const CDBWrapper &db, const CBlockIndex *block_index, DBVal &result)
static constexpr uint8_t DB_MUHASH
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)
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.
uint256 uint256S(const char *str)
uint256 from const char *.
Amount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)