Bitcoin ABC 0.26.3
P2P Digital Currency
Loading...
Searching...
No Matches
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
23 return 32 /* txid */ + 4 /* vout index */ + 4 /* height + coinbase */ +
24 8 /* amount */ + 2 /* scriptPubKey len */ +
25 script_pub_key.size() /* scriptPubKey */;
26}
27
28CDataStream TxOutSer(const COutPoint &outpoint, const Coin &coin) {
30 ss << outpoint;
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>
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
100 std::map<uint32_t, Coin> outputs;
101 while (pcursor->Valid()) {
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 return error("%s: unable to read value", __func__);
116 }
117 pcursor->Next();
118 }
119 if (!outputs.empty()) {
120 ApplyStats(stats, prevkey, outputs);
121 ApplyHash(hash_obj, prevkey, outputs);
122 }
123
124 FinalizeHash(hash_obj, stats);
125
126 stats.nDiskSize = view->EstimateSize();
127
128 return true;
129}
130
131std::optional<CCoinsStats>
134 const std::function<void()> &interruption_point) {
135 CBlockIndex *pindex = WITH_LOCK(
136 ::cs_main, return blockman.LookupBlockIndex(view->GetBestBlock()));
137 CCoinsStats stats{Assert(pindex)->nHeight, pindex->GetBlockHash()};
138
139 bool success = [&]() -> bool {
140 switch (hash_type) {
142 HashWriter ss{};
144 }
146 MuHash3072 muhash;
147 return ComputeUTXOStats(view, stats, muhash,
149 }
151 return ComputeUTXOStats(view, stats, nullptr,
153 }
154 } // no default case, so the compiler can warn about missing cases
155 assert(false);
156 }();
157
158 if (!success) {
159 return std::nullopt;
160 }
161 return stats;
162}
163
164// The legacy hash serializes the hashBlock
165static void PrepareHash(HashWriter &ss, const CCoinsStats &stats) {
166 ss << stats.hashBlock;
167}
168// MuHash does not need the prepare step
169static void PrepareHash(MuHash3072 &muhash, CCoinsStats &stats) {}
170static void PrepareHash(std::nullptr_t, CCoinsStats &stats) {}
171
172static void FinalizeHash(HashWriter &ss, CCoinsStats &stats) {
173 stats.hashSerialized = ss.GetHash();
174}
175static void FinalizeHash(MuHash3072 &muhash, CCoinsStats &stats) {
176 uint256 out;
177 muhash.Finalize(out);
178 stats.hashSerialized = out;
179}
180static void FinalizeHash(std::nullptr_t, CCoinsStats &stats) {}
181
182} // 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:146
Abstract view on the open txout dataset.
Definition coins.h:163
Double ended buffer combining vector and stream-like interfaces.
Definition streams.h:177
A UTXO entry.
Definition coins.h:28
uint32_t GetHeight() const
Definition coins.h:45
bool IsCoinBase() const
Definition coins.h:46
CTxOut & GetTxOut()
Definition coins.h:49
A writer stream (for serialization) that computes a 256-bit hash.
Definition hash.h:99
A class representing MuHash sets.
Definition muhash.h:96
void Finalize(uint256 &out) noexcept
Definition muhash.cpp:353
MuHash3072 & Insert(Span< const uint8_t > in) noexcept
Definition muhash.cpp:376
Maintains a tree of blocks (stored in m_block_index) which is consulted to determine where the most-w...
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
bool error(const char *fmt, const Args &...args)
Definition logging.h:226
unsigned int nHeight
static void FinalizeHash(HashWriter &ss, CCoinsStats &stats)
static void ApplyStats(CCoinsStats &stats, const TxId &txid, const std::map< uint32_t, Coin > &outputs)
Definition coinstats.cpp:79
CDataStream TxOutSer(const COutPoint &outpoint, const Coin &coin)
Definition coinstats.cpp:28
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
static void PrepareHash(HashWriter &ss, const CCoinsStats &stats)
uint64_t GetBogoSize(const CScript &script_pub_key)
Definition coinstats.cpp:22
T GetRand(T nMax=std::numeric_limits< T >::max()) noexcept
Generate a uniform random integer of type T in the range [0..nMax) nMax defaults to std::numeric_limi...
Definition random.h:85
#define VARINT(obj)
Definition serialize.h:579
#define VARINT_MODE(obj, mode)
Definition serialize.h:578
@ NONNEGATIVE_SIGNED
@ SER_DISK
Definition serialize.h:153
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:337
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 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
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())
static const int PROTOCOL_VERSION
network protocol versioning
Definition version.h:11