Inside Bitcoin
Opening the selected file…
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) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#include <node/miner.h>8#include <chain.h>9#include <chainparams.h>10#include <common/args.h>11#include <consensus/amount.h>12#include <consensus/consensus.h>13#include <consensus/merkle.h>14#include <consensus/params.h>15#include <consensus/tx_verify.h>16#include <consensus/validation.h>17#include <interfaces/types.h>18#include <node/blockstorage.h>19#include <node/kernel_notifications.h>20#include <node/mining_args.h>21#include <node/mining_types.h>22#include <policy/feerate.h>23#include <policy/policy.h>24#include <pow.h>25#include <primitives/block.h>26#include <primitives/transaction.h>27#include <script/script.h>28#include <sync.h>29#include <tinyformat.h>30#include <txgraph.h>31#include <txmempool.h>32#include <uint256.h>33#include <util/check.h>34#include <util/feefrac.h>35#include <util/log.h>36#include <util/result.h>37#include <util/signalinterrupt.h>38#include <util/time.h>39#include <util/translation.h>40#include <validation.h>41#include <validationinterface.h>42#include <versionbits.h>44#include <algorithm>45#include <compare>46#include <condition_variable>47#include <cstddef>48#include <functional>49#include <numeric>50#include <span>51#include <stdexcept>52#include <string>53#include <utility>55namespace node {57int64_t GetMinimumTime(const CBlockIndex* pindexPrev, const int64_t difficulty_adjustment_interval)58{59int64_t min_time{pindexPrev->GetMedianTimePast() + 1};60// Height of block to be mined.61const int height{pindexPrev->nHeight + 1};62// Account for BIP94 timewarp rule on all networks. This makes future63// activation safer.64if (height % difficulty_adjustment_interval == 0) {65min_time = std::max<int64_t>(min_time, pindexPrev->GetBlockTime() - MAX_TIMEWARP);66}67// Account for the BIP54 Murch-Zawy rule on all networks: the last block of68// a difficulty adjustment period may not be earlier than its first block.69if (height % difficulty_adjustment_interval == difficulty_adjustment_interval - 1) {70const int first_height{height - static_cast<int>(difficulty_adjustment_interval) + 1};71const CBlockIndex* first_block{Assert(pindexPrev->GetAncestor(first_height))};72min_time = std::max<int64_t>(min_time, first_block->GetBlockTime());73}74return min_time;75}77int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)78{79int64_t nOldTime = pblock->nTime;80int64_t nNewTime{std::max<int64_t>(GetMinimumTime(pindexPrev, consensusParams.DifficultyAdjustmentInterval()),81TicksSinceEpoch<std::chrono::seconds>(NodeClock::now()))};83if (nOldTime < nNewTime) {84pblock->nTime = nNewTime;85}87// Updating time can change work required on testnet:88if (consensusParams.fPowAllowMinDifficultyBlocks) {89pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams);90}92return nNewTime - nOldTime;93}95void RegenerateCommitments(CBlock& block, ChainstateManager& chainman)96{97CMutableTransaction tx{*block.vtx.at(0)};98tx.vout.erase(tx.vout.begin() + GetWitnessCommitmentIndex(block));99block.vtx.at(0) = MakeTransactionRef(tx);101const CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock));102chainman.GenerateCoinbaseCommitment(block, prev_block);104block.hashMerkleRoot = BlockMerkleRoot(block);105}107BlockAssembler::BlockAssembler(Chainstate& chainstate,108const CTxMemPool* mempool,109BlockCreateOptions options)110: chainparams{chainstate.m_chainman.GetParams()},111m_mempool{options.use_mempool ? mempool : nullptr},112m_chainstate{chainstate},113m_options{[&] {114if (auto result{CheckMiningOptions(options, /*use_argnames=*/false)}; !result) {115throw std::runtime_error(util::ErrorString(result).original);116}117return FlattenMiningOptions(std::move(options));118}()}119{120}122void BlockAssembler::resetBlock()123{124// Reserve space for fixed-size block header, txs count, and coinbase tx.125nBlockWeight = *Assert(m_options.block_reserved_weight);126nBlockSigOpsCost = m_options.coinbase_output_max_additional_sigops;128// These counters do not include coinbase tx129nBlockTx = 0;130nFees = 0;131}133std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()134{135const auto time_start{SteadyClock::now()};137resetBlock();139pblocktemplate.reset(new CBlockTemplate());140CBlock* const pblock = &pblocktemplate->block; // pointer for convenience142// Add dummy coinbase tx as first transaction. It is skipped by the143// getblocktemplate RPC and mining interface consumers must not use it.144pblock->vtx.emplace_back();146LOCK(::cs_main);147CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();148assert(pindexPrev != nullptr);149nHeight = pindexPrev->nHeight + 1;151pblock->nVersion = m_chainstate.m_chainman.m_versionbitscache.ComputeBlockVersion(pindexPrev, chainparams.GetConsensus());152// -regtest only: allow overriding block.nVersion with153// -blockversion=N to test forking scenarios154if (chainparams.MineBlocksOnDemand()) {155pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);156}158pblock->nTime = TicksSinceEpoch<std::chrono::seconds>(NodeClock::now());159m_lock_time_cutoff = pindexPrev->GetMedianTimePast();161if (m_mempool) {162LOCK(m_mempool->cs);163m_mempool->StartBlockBuilding();164addChunks();165m_mempool->StopBlockBuilding();166}168const auto time_1{SteadyClock::now()};170m_last_block_num_txs = nBlockTx;171m_last_block_weight = nBlockWeight;173// Create coinbase transaction.174CMutableTransaction coinbaseTx;176// Construct coinbase transaction struct in parallel177CoinbaseTx& coinbase_tx{pblocktemplate->m_coinbase_tx};178coinbase_tx.version = coinbaseTx.version;180coinbaseTx.vin.resize(1);181coinbaseTx.vin[0].prevout.SetNull();182coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.183coinbase_tx.sequence = coinbaseTx.vin[0].nSequence;185// Add an output that spends the full coinbase reward.186coinbaseTx.vout.resize(1);187coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;188// Block subsidy + fees189const CAmount block_reward{nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())};190coinbaseTx.vout[0].nValue = block_reward;191coinbase_tx.block_reward_remaining = block_reward;193// Start the coinbase scriptSig with the block height as required by BIP34.194// Mining clients are expected to append extra data to this prefix, so195// increasing its length would reduce the space they can use and may break196// existing clients.197coinbaseTx.vin[0].scriptSig = CScript() << nHeight;198// Set script_sig_prefix here, so IPC mining clients are not affected by199// the optional scriptSig padding below. They provide their own extraNonce,200// and in a typical setup a pool name or realistic extraNonce already makes201// the scriptSig long enough.202coinbase_tx.script_sig_prefix = coinbaseTx.vin[0].scriptSig;203if (nHeight <= 16) {204// For blocks at heights <= 16, the BIP34-encoded height alone is only205// one byte. Consensus requires coinbase scriptSigs to be at least two206// bytes long (bad-cb-length), so an OP_0 is always appended at those207// heights.208coinbaseTx.vin[0].scriptSig << OP_0;209}210Assert(nHeight > 0);211coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);212coinbase_tx.lock_time = coinbaseTx.nLockTime;214pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));215m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);217const CTransactionRef& final_coinbase{pblock->vtx[0]};218if (final_coinbase->HasWitness()) {219const auto& witness_stack{final_coinbase->vin[0].scriptWitness.stack};220// Consensus requires the coinbase witness stack to have exactly one221// element of 32 bytes.222Assert(witness_stack.size() == 1 && witness_stack[0].size() == 32);223coinbase_tx.witness = uint256(witness_stack[0]);224}225if (const int witness_index = GetWitnessCommitmentIndex(*pblock); witness_index != NO_WITNESS_COMMITMENT) {226Assert(witness_index >= 0 && static_cast<size_t>(witness_index) < final_coinbase->vout.size());227coinbase_tx.required_outputs.push_back(final_coinbase->vout[witness_index]);228}230LogDebug(BCLog::MINING, "CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost);232// Fill in header233pblock->hashPrevBlock = pindexPrev->GetBlockHash();234UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev);235pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus());236pblock->nNonce = 0;238if (m_options.test_block_validity) {239if (BlockValidationState state{TestBlockValidity(m_chainstate, *pblock, /*check_pow=*/false, /*check_merkle_root=*/false)}; !state.IsValid()) {240throw std::runtime_error(strprintf("TestBlockValidity failed: %s", state.ToString()));241}242}243const auto time_2{SteadyClock::now()};245LogDebug(BCLog::BENCH, "CreateNewBlock() chunks: %.2fms, validity: %.2fms (total %.2fms)\n",246Ticks<MillisecondsDouble>(time_1 - time_start),247Ticks<MillisecondsDouble>(time_2 - time_1),248Ticks<MillisecondsDouble>(time_2 - time_start));250return std::move(pblocktemplate);