Inside Bitcoin
Opening the selected file…
Inside Bitcoin
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2020-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <chainparams.h>6#include <consensus/amount.h>7#include <consensus/merkle.h>8#include <kernel/coinstats.h>9#include <node/miner.h>10#include <primitives/block.h>11#include <primitives/transaction.h>12#include <script/script.h>13#include <sync.h>14#include <test/fuzz/FuzzedDataProvider.h>15#include <test/fuzz/fuzz.h>16#include <test/fuzz/util.h>17#include <test/util/mining.h>18#include <test/util/random.h>19#include <test/util/setup_common.h>20#include <test/util/time.h>21#include <txdb.h>22#include <uint256.h>23#include <util/check.h>24#include <validation.h>26#include <cstddef>27#include <cstdint>28#include <functional>29#include <memory>30#include <optional>31#include <utility>32#include <vector>34FUZZ_TARGET(utxo_total_supply)35{36SeedRandomStateForTest(SeedRand::ZEROS);37FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size());38FakeNodeClock clock{ConsumeTime(fuzzed_data_provider, /*min=*/1296688602)}; // regtest genesis block timestamp39/** The testing setup that creates a chainman only (no chainstate) */40ChainTestingSetup test_setup{41ChainType::REGTEST,42{43.extra_args = {44"-testactivationheight=bip34@2",45},46},47};48// Create chainstate49test_setup.LoadVerifyActivateChainstate();50auto& node{test_setup.m_node};51auto& chainman{*Assert(test_setup.m_node.chainman)};53const auto ActiveHeight = [&]() {54LOCK(chainman.GetMutex());55return chainman.ActiveHeight();56};57const auto PrepareNextBlock = [&]() {58// Use OP_FALSE to avoid BIP30 check from hitting early59auto block = PrepareBlock(node, {60.coinbase_output_script = CScript() << OP_FALSE,61});62// Replace OP_FALSE with OP_TRUE63{64CMutableTransaction tx{*block->vtx.back()};65tx.nLockTime = 0; // Use the same nLockTime for all as we want to duplicate one of them.66tx.vout.at(0).scriptPubKey = CScript{} << OP_TRUE;67block->vtx.back() = MakeTransactionRef(tx);68}69return block;70};72/** The block template this fuzzer is working on */73auto current_block = PrepareNextBlock();74/** Append-only set of tx outpoints, entries are not removed when spent */75std::vector<std::pair<COutPoint, CTxOut>> txos;76/** The utxo stats at the chain tip */77kernel::CCoinsStats utxo_stats;78/** The total amount of coins in the utxo set */79CAmount circulation{0};82// Store the tx out in the txo map83const auto StoreLastTxo = [&]() {84// get last tx85const CTransaction& tx = *current_block->vtx.back();86// get last out87const uint32_t i = tx.vout.size() - 1;88// store it89txos.emplace_back(COutPoint{tx.GetHash(), i}, tx.vout.at(i));90if (current_block->vtx.size() == 1 && tx.vout.at(i).scriptPubKey[0] == OP_RETURN) {91// also store coinbase92const uint32_t i = tx.vout.size() - 2;93txos.emplace_back(COutPoint{tx.GetHash(), i}, tx.vout.at(i));94}95};96const auto AppendRandomTxo = [&](CMutableTransaction& tx) {97const auto& txo = txos.at(fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, txos.size() - 1));98tx.vin.emplace_back(txo.first);99tx.vout.emplace_back(txo.second.nValue, txo.second.scriptPubKey); // "Forward" coin with no fee100};101const auto UpdateUtxoStats = [&](bool wipe_cache) {102LOCK(chainman.GetMutex());103chainman.ActiveChainstate().ForceFlushStateToDisk(wipe_cache);104utxo_stats = std::move(105*Assert(kernel::ComputeUTXOStats(kernel::CoinStatsHashType::NONE, chainman.ActiveChainstate().CoinsDB(), chainman.m_blockman, {})));106// Check that miner can't print more money than they are allowed to107assert(circulation == utxo_stats.total_amount);108};111// Update internal state to chain tip112StoreLastTxo();113UpdateUtxoStats(/*wipe_cache=*/fuzzed_data_provider.ConsumeBool());114assert(ActiveHeight() == 0);115// Get at which height we duplicate the coinbase116// Assuming that the fuzzer will mine relatively short chains (less than 200 blocks), we want the duplicate coinbase to be not too high.117// Up to 300 seems reasonable.118int64_t duplicate_coinbase_height = fuzzed_data_provider.ConsumeIntegralInRange(0, 300);119// Avoid bad-cb-length error at heights <= 16. Pad the BIP34-encoded height120// with OP_0 to satisfy the minimum 2-byte coinbase scriptSig length.121CScript duplicate_coinbase_script = CScript() << duplicate_coinbase_height;122if (duplicate_coinbase_height <= 16) {123duplicate_coinbase_script << OP_0;124}125// Mine the first block with this duplicate126current_block = PrepareNextBlock();127StoreLastTxo();129{130// Create duplicate (CScript should match exact format as in CreateNewBlock)131CMutableTransaction tx{*current_block->vtx.front()};132tx.vin.at(0).scriptSig = duplicate_coinbase_script;134// Mine block and create next block template135current_block->vtx.front() = MakeTransactionRef(tx);136}137current_block->hashMerkleRoot = BlockMerkleRoot(*current_block);138assert(!MineBlock(node, current_block).IsNull());139circulation += GetBlockSubsidy(ActiveHeight(), Params().GetConsensus());141assert(ActiveHeight() == 1);142UpdateUtxoStats(/*wipe_cache=*/fuzzed_data_provider.ConsumeBool());143current_block = PrepareNextBlock();144StoreLastTxo();146// Limit to avoid timeout, but enough to cover duplicate_coinbase_height147// and CVE-2018-17144.148LIMITED_WHILE (fuzzed_data_provider.remaining_bytes(), 2'00) {149CallOneOf(150fuzzed_data_provider,151[&] {152// Append an input-output pair to the last tx in the current block153CMutableTransaction tx{*current_block->vtx.back()};154AppendRandomTxo(tx);155current_block->vtx.back() = MakeTransactionRef(tx);156StoreLastTxo();157},158[&] {159// Append a tx to the list of txs in the current block160CMutableTransaction tx{};161AppendRandomTxo(tx);162current_block->vtx.push_back(MakeTransactionRef(tx));163StoreLastTxo();164},165[&] {166// Append the current block to the active chain167node::RegenerateCommitments(*current_block, chainman);168const bool was_valid = !MineBlock(node, current_block).IsNull();170const uint256 prev_hash_serialized{utxo_stats.hashSerialized};171if (was_valid) {172if (duplicate_coinbase_height == ActiveHeight()) {173// we mined the duplicate coinbase174assert(current_block->vtx.at(0)->vin.at(0).scriptSig == duplicate_coinbase_script);175}177circulation += GetBlockSubsidy(ActiveHeight(), Params().GetConsensus());178}180UpdateUtxoStats(/*wipe_cache=*/fuzzed_data_provider.ConsumeBool());182if (!was_valid) {183// utxo stats must not change184assert(prev_hash_serialized == utxo_stats.hashSerialized);185}187current_block = PrepareNextBlock();188StoreLastTxo();189});190}191}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.