Bitcoin Core 28.99.0
P2P Digital Currency
utxo_total_supply.cpp
Go to the documentation of this file.
1// Copyright (c) 2020 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 <chainparams.h>
7#include <consensus/merkle.h>
8#include <kernel/coinstats.h>
9#include <node/miner.h>
10#include <script/interpreter.h>
11#include <streams.h>
13#include <test/fuzz/fuzz.h>
14#include <test/fuzz/util.h>
15#include <test/util/mining.h>
17#include <util/chaintype.h>
18#include <validation.h>
19
21
22FUZZ_TARGET(utxo_total_supply)
23{
25 ChainTestingSetup test_setup{
27 {
28 .extra_args = {"-testactivationheight=bip34@2"},
29 },
30 };
31 SeedRandomStateForTest(SeedRand::ZEROS); // Can not be done before test_setup
32 // Create chainstate
33 test_setup.LoadVerifyActivateChainstate();
34 auto& node{test_setup.m_node};
35 auto& chainman{*Assert(test_setup.m_node.chainman)};
36 FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());
37
38 const auto ActiveHeight = [&]() {
39 LOCK(chainman.GetMutex());
40 return chainman.ActiveHeight();
41 };
42 BlockAssembler::Options options;
43 options.coinbase_output_script = CScript() << OP_FALSE;
44 const auto PrepareNextBlock = [&]() {
45 // Use OP_FALSE to avoid BIP30 check from hitting early
46 auto block = PrepareBlock(node, options);
47 // Replace OP_FALSE with OP_TRUE
48 {
49 CMutableTransaction tx{*block->vtx.back()};
50 tx.vout.at(0).scriptPubKey = CScript{} << OP_TRUE;
51 block->vtx.back() = MakeTransactionRef(tx);
52 }
53 return block;
54 };
55
57 auto current_block = PrepareNextBlock();
59 std::vector<std::pair<COutPoint, CTxOut>> txos;
61 kernel::CCoinsStats utxo_stats;
63 CAmount circulation{0};
64
65
66 // Store the tx out in the txo map
67 const auto StoreLastTxo = [&]() {
68 // get last tx
69 const CTransaction& tx = *current_block->vtx.back();
70 // get last out
71 const uint32_t i = tx.vout.size() - 1;
72 // store it
73 txos.emplace_back(COutPoint{tx.GetHash(), i}, tx.vout.at(i));
74 if (current_block->vtx.size() == 1 && tx.vout.at(i).scriptPubKey[0] == OP_RETURN) {
75 // also store coinbase
76 const uint32_t i = tx.vout.size() - 2;
77 txos.emplace_back(COutPoint{tx.GetHash(), i}, tx.vout.at(i));
78 }
79 };
80 const auto AppendRandomTxo = [&](CMutableTransaction& tx) {
81 const auto& txo = txos.at(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, txos.size() - 1));
82 tx.vin.emplace_back(txo.first);
83 tx.vout.emplace_back(txo.second.nValue, txo.second.scriptPubKey); // "Forward" coin with no fee
84 };
85 const auto UpdateUtxoStats = [&]() {
86 LOCK(chainman.GetMutex());
87 chainman.ActiveChainstate().ForceFlushStateToDisk();
88 utxo_stats = std::move(
89 *Assert(kernel::ComputeUTXOStats(kernel::CoinStatsHashType::NONE, &chainman.ActiveChainstate().CoinsDB(), chainman.m_blockman, {})));
90 // Check that miner can't print more money than they are allowed to
91 assert(circulation == utxo_stats.total_amount);
92 };
93
94
95 // Update internal state to chain tip
96 StoreLastTxo();
97 UpdateUtxoStats();
98 assert(ActiveHeight() == 0);
99 // Get at which height we duplicate the coinbase
100 // Assuming that the fuzzer will mine relatively short chains (less than 200 blocks), we want the duplicate coinbase to be not too high.
101 // Up to 300 seems reasonable.
102 int64_t duplicate_coinbase_height = fuzzed_data_provider.ConsumeIntegralInRange(0, 300);
103 // Always pad with OP_0 at the end to avoid bad-cb-length error
104 const CScript duplicate_coinbase_script = CScript() << duplicate_coinbase_height << OP_0;
105 // Mine the first block with this duplicate
106 current_block = PrepareNextBlock();
107 StoreLastTxo();
108
109 {
110 // Create duplicate (CScript should match exact format as in CreateNewBlock)
111 CMutableTransaction tx{*current_block->vtx.front()};
112 tx.vin.at(0).scriptSig = duplicate_coinbase_script;
113
114 // Mine block and create next block template
115 current_block->vtx.front() = MakeTransactionRef(tx);
116 }
117 current_block->hashMerkleRoot = BlockMerkleRoot(*current_block);
118 assert(!MineBlock(node, current_block).IsNull());
119 circulation += GetBlockSubsidy(ActiveHeight(), Params().GetConsensus());
120
121 assert(ActiveHeight() == 1);
122 UpdateUtxoStats();
123 current_block = PrepareNextBlock();
124 StoreLastTxo();
125
126 // Limit to avoid timeout, but enough to cover duplicate_coinbase_height
127 // and CVE-2018-17144.
128 LIMITED_WHILE(fuzzed_data_provider.remaining_bytes(), 2'00)
129 {
130 CallOneOf(
131 fuzzed_data_provider,
132 [&] {
133 // Append an input-output pair to the last tx in the current block
134 CMutableTransaction tx{*current_block->vtx.back()};
135 AppendRandomTxo(tx);
136 current_block->vtx.back() = MakeTransactionRef(tx);
137 StoreLastTxo();
138 },
139 [&] {
140 // Append a tx to the list of txs in the current block
142 AppendRandomTxo(tx);
143 current_block->vtx.push_back(MakeTransactionRef(tx));
144 StoreLastTxo();
145 },
146 [&] {
147 // Append the current block to the active chain
148 node::RegenerateCommitments(*current_block, chainman);
149 const bool was_valid = !MineBlock(node, current_block).IsNull();
150
151 const auto prev_utxo_stats = utxo_stats;
152 if (was_valid) {
153 if (duplicate_coinbase_height == ActiveHeight()) {
154 // we mined the duplicate coinbase
155 assert(current_block->vtx.at(0)->vin.at(0).scriptSig == duplicate_coinbase_script);
156 }
157
158 circulation += GetBlockSubsidy(ActiveHeight(), Params().GetConsensus());
159 }
160
161 UpdateUtxoStats();
162
163 if (!was_valid) {
164 // utxo stats must not change
165 assert(prev_utxo_stats.hashSerialized == utxo_stats.hashSerialized);
166 }
167
168 current_block = PrepareNextBlock();
169 StoreLastTxo();
170 });
171 }
172}
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:85
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
bool IsNull() const
Definition: transaction.h:42
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:296
const std::vector< CTxOut > vout
Definition: transaction.h:307
const Txid & GetHash() const LIFETIMEBOUND
Definition: transaction.h:343
T ConsumeIntegralInRange(T min, T max)
Generate a new block, without valid proof-of-work.
Definition: miner.h:140
T & front()
Definition: prevector.h:452
#define LIMITED_WHILE(condition, limit)
Can be used to limit a theoretically unbounded loop.
Definition: fuzz.h:22
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
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:116
Definition: messages.h:20
void RegenerateCommitments(CBlock &block, ChainstateManager &chainman)
Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed.
Definition: miner.cpp:56
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
@ OP_FALSE
Definition: script.h:77
@ OP_TRUE
Definition: script.h:84
@ OP_0
Definition: script.h:76
@ OP_RETURN
Definition: script.h:111
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
Testing setup that performs all steps up until right before ChainstateManager gets initialized.
Definition: setup_common.h:105
std::optional< CAmount > total_amount
The total amount, or nullopt if an overflow occurred calculating it.
Definition: coinstats.h:41
uint256 hashSerialized
Definition: coinstats.h:38
#define LOCK(cs)
Definition: sync.h:257
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
Definition: util.h:35
std::shared_ptr< CBlock > PrepareBlock(const NodeContext &node, const BlockAssembler::Options &assembler_options)
Definition: mining.cpp:112
COutPoint MineBlock(const NodeContext &node, const node::BlockAssembler::Options &assembler_options)
Returns the generated coin.
Definition: mining.cpp:64
void SeedRandomStateForTest(SeedRand seedtype)
Seed the global RNG state for testing and log the seed value.
Definition: random.cpp:19
@ ZEROS
Seed with a compile time constant of zeros.
FUZZ_TARGET(utxo_total_supply)
CAmount GetBlockSubsidy(int nHeight, const Consensus::Params &consensusParams)
assert(!tx.IsCoinBase())