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) 2019-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 <test/util/mining.h>7#include <addresstype.h>8#include <chain.h>9#include <chainparams.h>10#include <consensus/merkle.h>11#include <consensus/validation.h>12#include <interfaces/mining.h>13#include <key_io.h>14#include <node/context.h>15#include <pow.h>16#include <primitives/block.h>17#include <primitives/transaction.h>18#include <script/script.h>19#include <sync.h>20#include <test/util/script.h>21#include <uint256.h>22#include <util/check.h>23#include <validation.h>24#include <validationinterface.h>25#include <versionbits.h>27#include <cstdint>28#include <memory>29#include <optional>30#include <utility>32using node::NodeContext;34COutPoint generatetoaddress(const NodeContext& node, const std::string& address)35{36const auto dest = DecodeDestination(address);37assert(IsValidDestination(dest));38return MineBlock(node, {39.coinbase_output_script = GetScriptForDestination(dest),40});41}43std::vector<std::shared_ptr<CBlock>> CreateBlockChain(size_t total_height, const CChainParams& params)44{45std::vector<std::shared_ptr<CBlock>> ret{total_height};46auto time{params.GenesisBlock().nTime};47// NOTE: here `height` does not correspond to the block height but the block height - 1.48for (size_t height{0}; height < total_height; ++height) {49CBlock& block{*(ret.at(height) = std::make_shared<CBlock>())};51CMutableTransaction coinbase_tx;52coinbase_tx.nLockTime = static_cast<uint32_t>(height);53coinbase_tx.vin.resize(1);54coinbase_tx.vin[0].prevout.SetNull();55coinbase_tx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.56coinbase_tx.vout.resize(1);57coinbase_tx.vout[0].scriptPubKey = P2WSH_OP_TRUE;58coinbase_tx.vout[0].nValue = GetBlockSubsidy(height + 1, params.GetConsensus());59// Always include OP_0 as a dummy extraNonce.60coinbase_tx.vin[0].scriptSig = CScript() << (height + 1) << OP_0;61block.vtx = {MakeTransactionRef(std::move(coinbase_tx))};63block.nVersion = VERSIONBITS_LAST_OLD_BLOCK_VERSION;64block.hashPrevBlock = (height >= 1 ? *ret.at(height - 1) : params.GenesisBlock()).GetHash();65block.hashMerkleRoot = BlockMerkleRoot(block);66block.nTime = ++time;67block.nBits = params.GenesisBlock().nBits;68block.nNonce = 0;70while (!CheckProofOfWork(block.GetHash(), block.nBits, params.GetConsensus())) {71++block.nNonce;72assert(block.nNonce);73}74}75return ret;76}78bool BuildChain(const NodeContext& node, const CBlockIndex* pindex,79const CScript& coinbase_script_pub_key,80size_t length,81std::vector<std::shared_ptr<CBlock>>& chain)82{83auto mining{interfaces::MakeMining(node)};84const Consensus::Params& consensus{Assert(node.chainman)->GetConsensus()};86chain.resize(length);87for (auto& chain_block : chain) {88auto block_template{mining->createNewBlock({89.use_mempool = false,90.coinbase_output_script = coinbase_script_pub_key,91}, /*cooldown=*/false)};92CBlock block{Assert(block_template)->getBlock()};94// The template is built on the active tip, so repoint it at pindex and95// redo the fields that depend on the predecessor.96block.hashPrevBlock = pindex->GetBlockHash();97block.nTime = pindex->nTime + 1;98{99CMutableTransaction tx_coinbase{*block.vtx.at(0)};100tx_coinbase.nLockTime = static_cast<uint32_t>(pindex->nHeight);101tx_coinbase.vin.at(0).scriptSig = CScript{} << pindex->nHeight + 1;102block.vtx.at(0) = MakeTransactionRef(std::move(tx_coinbase));103block.hashMerkleRoot = BlockMerkleRoot(block);104}106while (!CheckProofOfWork(block.GetHash(), block.nBits, consensus)) ++block.nNonce;108chain_block = std::make_shared<CBlock>(std::move(block));110BlockValidationState state;111if (!Assert(node.chainman)->ProcessNewBlockHeaders({{*chain_block}}, true, state, &pindex)) {112return false;113}114}116return true;117}119COutPoint MineBlock(const NodeContext& node, const node::BlockCreateOptions& assembler_options)120{121auto block = PrepareBlock(node, assembler_options);122auto valid = MineBlock(node, block);123assert(!valid.IsNull());124return valid;125}127struct BlockValidationStateCatcher : public CValidationInterface {128const uint256 m_hash;129std::optional<BlockValidationState> m_state;131BlockValidationStateCatcher(const uint256& hash)132: m_hash{hash},133m_state{} {}135protected:136void BlockChecked(const std::shared_ptr<const CBlock>& block, const BlockValidationState& state) override137{138if (block->GetHash() != m_hash) return;139m_state = state;140}141};143COutPoint MineBlock(const NodeContext& node, std::shared_ptr<CBlock>& block)144{145while (!CheckProofOfWork(block->GetHash(), block->nBits, Params().GetConsensus())) {146++block->nNonce;147assert(block->nNonce);148}150return ProcessBlock(node, block);151}153COutPoint ProcessBlock(const NodeContext& node, const std::shared_ptr<CBlock>& block)154{155auto& chainman{*Assert(node.chainman)};156const auto old_height = WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight());157bool new_block;158BlockValidationStateCatcher bvsc{block->GetHash()};159node.validation_signals->RegisterValidationInterface(&bvsc);160const bool processed{chainman.ProcessNewBlock(block, true, true, &new_block)};161const bool duplicate{!new_block && processed};162assert(!duplicate);163node.validation_signals->UnregisterValidationInterface(&bvsc);164node.validation_signals->SyncWithValidationInterfaceQueue();165const bool was_valid{bvsc.m_state && bvsc.m_state->IsValid()};166assert(old_height + was_valid == WITH_LOCK(chainman.GetMutex(), return chainman.ActiveHeight()));168if (was_valid) return {block->vtx[0]->GetHash(), 0};169return {};170}172std::shared_ptr<CBlock> PrepareBlock(const NodeContext& node,173const node::BlockCreateOptions& assembler_options)174{175auto mining = interfaces::MakeMining(node);176auto block_template = mining->createNewBlock(assembler_options, /*cooldown=*/false);177auto block = std::make_shared<CBlock>(Assert(block_template)->getBlock());179LOCK(cs_main);180block->nTime = Assert(node.chainman)->ActiveChain().Tip()->GetMedianTimePast() + 1;181block->hashMerkleRoot = BlockMerkleRoot(*block);183return block;184}
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.