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#ifndef BITCOIN_NODE_MINER_H7#define BITCOIN_NODE_MINER_H9#include <consensus/amount.h>10#include <node/mining_types.h>11#include <primitives/block.h>12#include <primitives/transaction.h>13#include <threadsafety.h>14#include <txmempool.h>15#include <util/feefrac.h>16#include <util/time.h>18#include <cstdint>19#include <memory>20#include <optional>21#include <string>22#include <vector>24class CBlockIndex;25class CChainParams;26class Chainstate;27class ChainstateManager;29namespace Consensus {30struct Params;31} // namespace Consensus32class uint256;33namespace interfaces {34struct BlockRef;35} // namespace interfaces37using interfaces::BlockRef;39namespace node {40class KernelNotifications;42struct CBlockTemplate43{44CBlock block;45// Fees per transaction, not including coinbase transaction (unlike CBlock::vtx).46std::vector<CAmount> vTxFees;47// Sigops per transaction, not including coinbase transaction (unlike CBlock::vtx).48std::vector<int64_t> vTxSigOpsCost;49/* A vector of package fee rates, ordered by the sequence in which50* packages are selected for inclusion in the block template.*/51std::vector<FeePerVSize> m_package_feerates;52/*53* Template containing all coinbase transaction fields that are set by our54* miner code.55*/56CoinbaseTx m_coinbase_tx;57};59/** Generate a new block, without valid proof-of-work */60class BlockAssembler61{62private:63// The constructed block template64std::unique_ptr<CBlockTemplate> pblocktemplate;66// Information on the current status of the block67uint64_t nBlockWeight;68uint64_t nBlockTx;69uint64_t nBlockSigOpsCost;70CAmount nFees;72// Chain context for the block73int nHeight;74int64_t m_lock_time_cutoff;76const CChainParams& chainparams;77const CTxMemPool* const m_mempool;78Chainstate& m_chainstate;80public:81explicit BlockAssembler(Chainstate& chainstate,82const CTxMemPool* mempool,83BlockCreateOptions create_options);85/** Construct a new block template */86std::unique_ptr<CBlockTemplate> CreateNewBlock();88/** The number of transactions in the last assembled block (excluding coinbase transaction) */89inline static std::optional<int64_t> m_last_block_num_txs{};90/** The weight of the last assembled block (including reserved weight for block header, txs count and coinbase tx) */91inline static std::optional<int64_t> m_last_block_weight{};93private:94const BlockCreateOptions m_options;96// utility functions97/** Clear the block's state and prepare for assembling a new block */98void resetBlock();99/** Add a tx to the block */100void AddToBlock(const CTxMemPoolEntry& entry);102// Methods for how to add transactions to a block.103/** Add transactions based on chunk feerate104*105* @pre BlockAssembler::m_mempool must not be nullptr106*/107void addChunks() EXCLUSIVE_LOCKS_REQUIRED(m_mempool->cs);109// helper functions for addChunks()110/** Test if a new chunk would "fit" in the block */111bool TestChunkBlockLimits(int64_t chunk_weight, int64_t chunk_sigops_cost) const;112/** Perform locktime checks on each transaction in a chunk:113* This check should always succeed, and is here114* only as an extra check in case of a bug */115bool TestChunkTransactions(const std::vector<CTxMemPoolEntryRef>& txs) const;116};118/**119* Get the minimum time a miner should use in the next block. This always120* accounts for the BIP94 timewarp rule, so does not necessarily reflect the121* consensus limit.122*/123int64_t GetMinimumTime(const CBlockIndex* pindexPrev, int64_t difficulty_adjustment_interval);125int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev);127/** Update an old GenerateCoinbaseCommitment from CreateNewBlock after the block txs have changed */128void RegenerateCommitments(CBlock& block, ChainstateManager& chainman);130/* Compute the block's merkle root, insert or replace the coinbase transaction and the merkle root into the block */131void AddMerkleRootAndCoinbase(CBlock& block, CTransactionRef coinbase, uint32_t version, uint32_t timestamp, uint32_t nonce);133//! Submit a block and capture the validation state via the BlockChecked callback.134//! Returns whether the block was accepted as a new valid block.135bool SubmitBlock(ChainstateManager& chainman, const std::shared_ptr<const CBlock>& block, std::string& reason, std::string& debug);137/* Interrupt a blocking call. */138void InterruptWait(KernelNotifications& kernel_notifications, bool& interrupt_wait);139/**140* Return a new block template when fees rise to a certain threshold or after a141* new tip; return nullopt if timeout is reached.142*/143std::unique_ptr<CBlockTemplate> WaitAndCreateNewBlock(ChainstateManager& chainman,144KernelNotifications& kernel_notifications,145CTxMemPool* mempool,146const std::unique_ptr<CBlockTemplate>& block_template,147const BlockWaitOptions& wait_options,148const BlockCreateOptions& create_options,149bool& interrupt_wait);151/* Locks cs_main and returns the block hash and block height of the active chain if it exists; otherwise, returns nullopt.*/152std::optional<BlockRef> GetTip(ChainstateManager& chainman);154/* Waits for the connected tip to change until timeout has elapsed. During node initialization, this will wait until the tip is connected (regardless of `timeout`).155* Returns the current tip, or nullopt if the node is shutting down or interrupt()156* is called.157*/158std::optional<BlockRef> WaitTipChanged(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const uint256& current_tip, MillisecondsDouble& timeout, bool& interrupt);160/**161* Wait while the best known header extends the current chain tip AND at least162* one block is being added to the tip every 3 seconds. If the tip is163* sufficiently far behind, allow up to 20 seconds for the next tip update.164*165* It’s not safe to keep waiting, because a malicious miner could announce a166* header and delay revealing the block, causing all other miners using this167* software to stall. At the same time, we need to balance between the default168* waiting time being brief, but not ending the cooldown prematurely when a169* random block is slow to download (or process).170*171* The cooldown only applies to createNewBlock(), which is typically called172* once per connected client. Subsequent templates are provided by waitNext().173*174* @param last_tip tip at the start of the cooldown window.175* @param interrupt_mining set to true to interrupt the cooldown.176*177* @returns false if interrupted.178*/179bool CooldownIfHeadersAhead(ChainstateManager& chainman, KernelNotifications& kernel_notifications, const BlockRef& last_tip, bool& interrupt_mining);180} // namespace node182#endif // BITCOIN_NODE_MINER_H
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.