Bitcoin ABC 0.32.4
P2P Digital Currency
coinstats.cpp
Go to the documentation of this file.
1// Copyright (c) 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 <kernel/coinstats.h>
6
7#include <coins.h>
8#include <crypto/muhash.h>
9#include <hash.h>
10#include <logging.h>
11#include <primitives/txid.h>
12#include <serialize.h>
13#include <util/check.h>
14#include <validation.h>
15
16#include <map>
17
18namespace kernel {
19CCoinsStats::CCoinsStats(int block_height, const BlockHash &block_hash)
20 : nHeight(block_height), hashBlock(block_hash) {}
21
22uint64_t GetBogoSize(const CScript &script_pub_key) {
23 return 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ +
24 8 /* amount */ + 2 /* scriptPubKey len */ +
25 script_pub_key.size() /* scriptPubKey */;
26}
27
28DataStream TxOutSer(const COutPoint &outpoint, const Coin &coin) {
29 DataStream ss{};
30 ss << outpoint;
31 ss << static_cast<uint32_t>(coin.GetHeight() * 2 + coin.IsCoinBase());
32 ss << coin.GetTxOut();
33 return ss;
34}
35
48static void ApplyHash(HashWriter &ss, const TxId &txid,
49 const std::map<uint32_t, Coin> &outputs) {
50 for (auto it = outputs.begin(); it != outputs.end(); ++it) {
51 if (it == outputs.begin()) {
52 ss << txid;
53 ss << VARINT(it->second.GetHeight() * 2 + it->second.IsCoinBase());
54 }
55
56 ss << VARINT(it->first + 1);
57 ss << it->second.GetTxOut().scriptPubKey;
58 ss << VARINT_MODE(it->second.GetTxOut().nValue / SATOSHI,
60
61 if (it == std::prev(outputs.end())) {
62 ss << VARINT(0u);
63 }
64 }
65}
66
67static void ApplyHash(std::nullptr_t, const TxId &txid,
68 const std::map<uint32_t, Coin> &outputs) {}
69
70static void ApplyHash(MuHash3072 &muhash, const TxId &txid,
71 const std::map<uint32_t, Coin> &outputs) {
72 for (auto it = outputs.begin(); it != outputs.end(); ++it) {
73 COutPoint outpoint = COutPoint(txid, it->first);
74 Coin coin = it->second;
75 muhash.Insert(MakeUCharSpan(TxOutSer(outpoint, coin)));
76 }
77}
78
79static void ApplyStats(CCoinsStats &stats, const TxId &txid,
80 const std::map<uint32_t, Coin> &outputs) {
81 assert(!outputs.empty());
82 stats.nTransactions++;
83 for (auto it = outputs.begin(); it != outputs.end(); ++it) {
84 stats.nTransactionOutputs++;
85 stats.nTotalAmount += it->second.GetTxOut().nValue;
86 stats.nBogoSize += GetBogoSize(it->second.GetTxOut().scriptPubKey);
87 }
88}
89
91template <typename T>
92static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj,
93 const std::function<void()> &interruption_point) {
94 std::unique_ptr<CCoinsViewCursor> pcursor(view->Cursor());
95 assert(pcursor);
96
97 PrepareHash(hash_obj, stats);
98
99 TxId prevkey;
100 std::map<uint32_t, Coin> outputs;
101 while (pcursor->Valid()) {
102 interruption_point();
103 COutPoint key;
104 Coin coin;
105 if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
106 if (!outputs.empty() && key.GetTxId() != prevkey) {
107 ApplyStats(stats, prevkey, outputs);
108 ApplyHash(hash_obj, prevkey, outputs);
109 outputs.clear();
110 }
111 prevkey = key.GetTxId();
112 outputs[key.GetN()] = std::move(coin);
113 stats.coins_count++;
114 } else {
115 LogError("%s: unable to read value\n", __func__);
116 return false;
117 }
118 pcursor->Next();
119 }
120 if (!outputs.empty()) {
121 ApplyStats(stats, prevkey, outputs);
122 ApplyHash(hash_obj, prevkey, outputs);
123 }
124
125 FinalizeHash(hash_obj, stats);
126
127 stats.nDiskSize = view->EstimateSize();
128
129 return true;
130}
131
132std::optional<CCoinsStats>
134 node::BlockManager &blockman,
135 const std::function<void()> &interruption_point) {
136 CBlockIndex *pindex = WITH_LOCK(
137 ::cs_main, return blockman.LookupBlockIndex(view->GetBestBlock()));
138 CCoinsStats stats{Assert(pindex)->nHeight, pindex->GetBlockHash()};
139
140 bool success = [&]() -> bool {
141 switch (hash_type) {
143 HashWriter ss{};
144 return ComputeUTXOStats(view, stats, ss, interruption_point);
145 }
147 MuHash3072 muhash;
148 return ComputeUTXOStats(view, stats, muhash,
149 interruption_point);
150 }
152 return ComputeUTXOStats(view, stats, nullptr,
153 interruption_point);
154 }
155 } // no default case, so the compiler can warn about missing cases
156 assert(false);
157 }();
158
159 if (!success) {
160 return std::nullopt;
161 }
162 return stats;
163}
164
165// The legacy hash serializes the hashBlock
166static void PrepareHash(HashWriter &ss, const CCoinsStats &stats) {
167 ss << stats.hashBlock;
168}
169// MuHash does not need the prepare step
170static void PrepareHash(MuHash3072 &muhash, CCoinsStats &stats) {}
171static void PrepareHash(std::nullptr_t, CCoinsStats &stats) {}
172
173static void FinalizeHash(HashWriter &ss, CCoinsStats &stats) {
174 stats.hashSerialized = ss.GetHash();
175}
176static void FinalizeHash(MuHash3072 &muhash, CCoinsStats &stats) {
177 uint256 out;
178 muhash.Finalize(out);
179 stats.hashSerialized = out;
180}
181static void FinalizeHash(std::nullptr_t, CCoinsStats &stats) {}
182
183} // namespace kernel
static constexpr Amount SATOSHI
Definition: amount.h:143
#define Assert(val)
Identity function.
Definition: check.h:84
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
BlockHash GetBlockHash() const
Definition: blockindex.h:130
Abstract view on the open txout dataset.
Definition: coins.h:305
virtual CCoinsViewCursor * Cursor() const
Get a cursor to iterate over the whole state.
Definition: coins.cpp:26
virtual BlockHash GetBestBlock() const
Retrieve the block hash whose state this CCoinsView currently represents.
Definition: coins.cpp:16
virtual size_t EstimateSize() const
Estimate database size (0 if not implemented)
Definition: coins.h:339
A UTXO entry.
Definition: coins.h:29
uint32_t GetHeight() const
Definition: coins.h:46
bool IsCoinBase() const
Definition: coins.h:47
CTxOut & GetTxOut()
Definition: coins.h:50
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:173
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:114
A class representing MuHash sets.
Definition: muhash.h:107
void Finalize(uint256 &out) noexcept
Definition: muhash.cpp:683
MuHash3072 & Insert(Span< const uint8_t > in) noexcept
Definition: muhash.cpp:706
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
Definition: blockstorage.h:107
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
256-bit opaque blob.
Definition: uint256.h:129
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
#define LogError(...)
Definition: logging.h:419
unsigned int nHeight
Definition: init.h:28
static void FinalizeHash(HashWriter &ss, CCoinsStats &stats)
Definition: coinstats.cpp:173
static void ApplyStats(CCoinsStats &stats, const TxId &txid, const std::map< uint32_t, Coin > &outputs)
Definition: coinstats.cpp:79
static void ApplyHash(HashWriter &ss, const TxId &txid, const std::map< uint32_t, Coin > &outputs)
Warning: be very careful when changing this! assumeutxo and UTXO snapshot validation commitments are ...
Definition: coinstats.cpp:48
static bool ComputeUTXOStats(CCoinsView *view, CCoinsStats &stats, T hash_obj, const std::function< void()> &interruption_point)
Calculate statistics about the unspent transaction output set.
Definition: coinstats.cpp:92
CoinStatsHashType
Definition: coinstats.h:23
DataStream TxOutSer(const COutPoint &outpoint, const Coin &coin)
Definition: coinstats.cpp:28
static void PrepareHash(HashWriter &ss, const CCoinsStats &stats)
Definition: coinstats.cpp:166
uint64_t GetBogoSize(const CScript &script_pub_key)
Definition: coinstats.cpp:22
#define VARINT(obj)
Definition: serialize.h:569
#define VARINT_MODE(obj, mode)
Definition: serialize.h:568
@ NONNEGATIVE_SIGNED
constexpr auto MakeUCharSpan(V &&v) -> decltype(UCharSpanCast(Span{std::forward< V >(v)}))
Like the Span constructor, but for (const) uint8_t member types only.
Definition: span.h:350
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
A TxId is the identifier of a transaction.
Definition: txid.h:14
uint64_t nDiskSize
Definition: coinstats.h:36
uint64_t coins_count
The number of coins contained.
Definition: coinstats.h:40
uint64_t nTransactions
Definition: coinstats.h:32
uint64_t nTransactionOutputs
Definition: coinstats.h:33
uint64_t nBogoSize
Definition: coinstats.h:34
BlockHash hashBlock
Definition: coinstats.h:31
uint256 hashSerialized
Definition: coinstats.h:35
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
assert(!tx.IsCoinBase())