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_CHAIN_H7#define BITCOIN_CHAIN_H9#include <arith_uint256.h>10#include <consensus/params.h>11#include <flatfile.h>12#include <kernel/cs_main.h>13#include <primitives/block.h>14#include <serialize.h>15#include <sync.h>16#include <uint256.h>17#include <util/time.h>19#include <algorithm>20#include <cassert>21#include <cstdint>22#include <string>23#include <vector>25/**26* Maximum amount of time that a block timestamp is allowed to exceed the27* current time before the block will be accepted.28*/29inline constexpr int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60;31/**32* Timestamp window used as a grace period by code that compares external33* timestamps (such as timestamps passed to RPCs, or wallet key creation times)34* to block timestamps. This should be set at least as high as35* MAX_FUTURE_BLOCK_TIME.36*/37inline constexpr int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME;38//! Init values for CBlockIndex nSequenceId when loaded from disk39inline constexpr int32_t SEQ_ID_BEST_CHAIN_FROM_DISK = 0;40inline constexpr int32_t SEQ_ID_INIT_FROM_DISK = 1;42enum BlockStatus : uint32_t {43//! Unused.44BLOCK_VALID_UNKNOWN = 0,46//! Reserved (was BLOCK_VALID_HEADER).47BLOCK_VALID_RESERVED = 1,49//! All parent headers found, difficulty matches, timestamp >= median previous. Implies all parents50//! are also at least TREE.51BLOCK_VALID_TREE = 2,53/**54* Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,55* sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS.56*57* If a block's validity is at least VALID_TRANSACTIONS, CBlockIndex::nTx will be set. If a block and all previous58* blocks back to the genesis block or an assumeutxo snapshot block are at least VALID_TRANSACTIONS,59* CBlockIndex::m_chain_tx_count will be set.60*/61BLOCK_VALID_TRANSACTIONS = 3,63//! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30.64//! Implies all previous blocks back to the genesis block or an assumeutxo snapshot block are at least VALID_CHAIN.65BLOCK_VALID_CHAIN = 4,67//! Scripts & signatures ok. Implies all previous blocks back to the genesis block or an assumeutxo snapshot block68//! are at least VALID_SCRIPTS.69BLOCK_VALID_SCRIPTS = 5,71//! All validity bits.72BLOCK_VALID_MASK = BLOCK_VALID_RESERVED | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |73BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS,75BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat76BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat77BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,79BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed80BLOCK_FAILED_CHILD = 64, //!< Unused flag that was previously set when descending from failed block82BLOCK_OPT_WITNESS = 128, //!< block data in blk*.dat was received with a witness-enforcing client84BLOCK_STATUS_RESERVED = 256, //!< Unused flag that was previously set on assumeutxo snapshot blocks and their85//!< ancestors before they were validated, and unset when they were validated.86};88/** The block chain is a tree shaped structure starting with the89* genesis block at the root, with each block potentially having multiple90* candidates to be the next block. A blockindex may have multiple pprev pointing91* to it, but at most one of them can be part of the currently active branch.92*/93class CBlockIndex94{95public:96//! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex97const uint256* phashBlock{nullptr};99//! pointer to the index of the predecessor of this block100CBlockIndex* pprev{nullptr};102//! pointer to the index of some further predecessor of this block103CBlockIndex* pskip{nullptr};105//! height of the entry in the chain. The genesis block has height 0106int nHeight{0};108//! Which # file this block is stored in (blk?????.dat)109int nFile GUARDED_BY(::cs_main){0};111//! Byte offset within blk?????.dat where this block's data is stored112uint64_t nDataPos GUARDED_BY(::cs_main){0};114//! Byte offset within rev?????.dat where this block's undo data is stored115uint64_t nUndoPos GUARDED_BY(::cs_main){0};117//! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block118arith_uint256 nChainWork{};120//! Number of transactions in this block. This will be nonzero if the block121//! reached the VALID_TRANSACTIONS level, and zero otherwise.122//! Note: in a potential headers-first mode, this number cannot be relied upon123unsigned int nTx{0};125//! (memory only) Number of transactions in the chain up to and including this block.126//! This value will be non-zero if this block and all previous blocks back127//! to the genesis block or an assumeutxo snapshot block have reached the128//! VALID_TRANSACTIONS level.129uint64_t m_chain_tx_count{0};131//! Verification status of this block. See enum BlockStatus132//!133//! Note: this value is modified to show BLOCK_OPT_WITNESS during UTXO snapshot134//! load to avoid a spurious startup failure requiring -reindex.135//! @sa NeedsRedownload136//! @sa ActivateSnapshot137uint32_t nStatus GUARDED_BY(::cs_main){0};139//! block header140int32_t nVersion{0};141uint256 hashMerkleRoot{};142uint32_t nTime{0};143uint32_t nBits{0};144uint32_t nNonce{0};146//! (memory only) Sequential id assigned to distinguish order in which blocks are received.147//! Initialized to SEQ_ID_INIT_FROM_DISK{1} when loading blocks from disk, except for blocks148//! belonging to the best chain which overwrite it to SEQ_ID_BEST_CHAIN_FROM_DISK{0}.149int32_t nSequenceId{SEQ_ID_INIT_FROM_DISK};151//! (memory only) Maximum nTime in the chain up to and including this block.152unsigned int nTimeMax{0};154explicit CBlockIndex(const CBlockHeader& block)155: nVersion{block.nVersion},156hashMerkleRoot{block.hashMerkleRoot},157nTime{block.nTime},158nBits{block.nBits},159nNonce{block.nNonce}160{161}163FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)164{165AssertLockHeld(::cs_main);166FlatFilePos ret;167if (nStatus & BLOCK_HAVE_DATA) {168ret.nFile = nFile;169ret.nPos = nDataPos;170}171return ret;172}174FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(::cs_main)175{176AssertLockHeld(::cs_main);177FlatFilePos ret;178if (nStatus & BLOCK_HAVE_UNDO) {179ret.nFile = nFile;180ret.nPos = nUndoPos;181}182return ret;183}185CBlockHeader GetBlockHeader() const186{187CBlockHeader block;188block.nVersion = nVersion;189if (pprev)190block.hashPrevBlock = pprev->GetBlockHash();191block.hashMerkleRoot = hashMerkleRoot;192block.nTime = nTime;193block.nBits = nBits;194block.nNonce = nNonce;195return block;196}198uint256 GetBlockHash() const199{200assert(phashBlock != nullptr);201return *phashBlock;202}204/**205* Check whether this block and all previous blocks back to the genesis block or an assumeutxo snapshot block have206* reached VALID_TRANSACTIONS and had transactions downloaded (and stored to disk) at some point.207*208* Does not imply the transactions are consensus-valid (ConnectTip might fail)209* Does not imply the transactions are still stored on disk. (IsBlockPruned might return true)210*211* Note that this will be true for the snapshot base block, if one is loaded, since its m_chain_tx_count value will have212* been set manually based on the related AssumeutxoData entry.213*/214bool HaveNumChainTxs() const { return m_chain_tx_count != 0; }216NodeSeconds Time() const217{218return NodeSeconds{std::chrono::seconds{nTime}};219}221int64_t GetBlockTime() const222{223return (int64_t)nTime;224}226int64_t GetBlockTimeMax() const227{228return (int64_t)nTimeMax;229}231static constexpr int nMedianTimeSpan = 11;233int64_t GetMedianTimePast() const234{235int64_t pmedian[nMedianTimeSpan];236int64_t* pbegin = &pmedian[nMedianTimeSpan];237int64_t* pend = &pmedian[nMedianTimeSpan];239const CBlockIndex* pindex = this;240for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)241*(--pbegin) = pindex->GetBlockTime();243std::sort(pbegin, pend);244return pbegin[(pend - pbegin) / 2];245}247std::string ToString() const;249//! Check whether this block index entry is valid up to the passed validity level.250bool IsValid(enum BlockStatus nUpTo) const
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.