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) 2022-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#ifndef BITCOIN_HEADERSSYNC_H6#define BITCOIN_HEADERSSYNC_H8#include <arith_uint256.h>9#include <chain.h>10#include <consensus/params.h>11#include <net.h>12#include <primitives/block.h>13#include <uint256.h>14#include <util/bitdeque.h>15#include <util/hasher.h>17#include <deque>18#include <stdexcept>19#include <vector>21// A compressed CBlockHeader, which leaves out the prevhash22struct CompressedHeader {23// header24int32_t nVersion{0};25uint256 hashMerkleRoot;26uint32_t nTime{0};27uint32_t nBits{0};28uint32_t nNonce{0};30CompressedHeader()31{32hashMerkleRoot.SetNull();33}35explicit CompressedHeader(const CBlockHeader& header)36: nVersion{header.nVersion},37hashMerkleRoot{header.hashMerkleRoot},38nTime{header.nTime},39nBits{header.nBits},40nNonce{header.nNonce}41{42}44CBlockHeader GetFullHeader(const uint256& hash_prev_block) const45{46CBlockHeader ret;47ret.nVersion = nVersion;48ret.hashPrevBlock = hash_prev_block;49ret.hashMerkleRoot = hashMerkleRoot;50ret.nTime = nTime;51ret.nBits = nBits;52ret.nNonce = nNonce;53return ret;54};55};57/** HeadersSyncState:58*59* We wish to download a peer's headers chain in a DoS-resistant way.60*61* The Bitcoin protocol does not offer an easy way to determine the work on a62* peer's chain. Currently, we can query a peer's headers by using a GETHEADERS63* message, and our peer can return a set of up to 2000 headers that connect to64* something we know. If a peer's chain has more than 2000 blocks, then we need65* a way to verify that the chain actually has enough work on it to be useful to66* us -- by being above our anti-DoS minimum-chain-work threshold -- before we67* commit to storing those headers in memory. Otherwise, it would be cheap for68* an attacker to waste all our memory by serving us low-work headers69* (particularly for a new node coming online for the first time).70*71* To prevent memory-DoS with low-work headers, while still always being72* able to reorg to whatever the most-work chain is, we require that a chain73* meet a work threshold before committing it to memory. We can do this by74* downloading a peer's headers twice, whenever we are not sure that the chain75* has sufficient work:76*77* - In the first download phase, called pre-synchronization, we can calculate78* the work on the chain as we go (just by checking the nBits value on each79* header, and validating the proof-of-work).80*81* - Once we have reached a header where the cumulative chain work is82* sufficient, we switch to downloading the headers a second time, this time83* processing them fully, and possibly storing them in memory.84*85* To prevent an attacker from using (eg) the honest chain to convince us that86* they have a high-work chain, but then feeding us an alternate set of87* low-difficulty headers in the second phase, we store commitments to the88* chain we see in the first download phase that we check in the second phase,89* as follows:90*91* - In phase 1 (presync), store 1 bit (using a salted hash function) for every92* N headers that we see. With a reasonable choice of N, this uses relatively93* little memory even for a very long chain.94*95* - In phase 2 (redownload), keep a lookahead buffer and only accept headers96* from that buffer into the block index (permanent memory usage) once they97* have some target number of verified commitments on top of them. With this98* parametrization, we can achieve a given security target for potential99* permanent memory usage, while choosing N to minimize memory use during the100* sync (temporary, per-peer storage).101*/103class HeadersSyncState104{105public:106struct SystemClockError : std::runtime_error {107using std::runtime_error::runtime_error;108};110~HeadersSyncState() = default;112enum class State {113/** PRESYNC means the peer has not yet demonstrated their chain has114* sufficient work and we're only building commitments to the chain they115* serve us. */116PRESYNC,117/** REDOWNLOAD means the peer has given us a high-enough-work chain,118* and now we're redownloading the headers we saw before and trying to119* accept them */120REDOWNLOAD,121/** We're done syncing with this peer and can discard any remaining state */122FINAL123};125/** Return the current state of our download */126State GetState() const { return m_download_state; }128/** Return the height reached during the PRESYNC phase */129int64_t GetPresyncHeight() const { return m_current_height; }131/** Return the block timestamp of the last header received during the PRESYNC phase. */132uint32_t GetPresyncTime() const { return m_last_header_received.nTime; }134/** Return the amount of work in the chain received during the PRESYNC phase. */135arith_uint256 GetPresyncWork() const { return m_current_chain_work; }137/** Construct a HeadersSyncState object representing a headers sync via this138* download-twice mechanism).139*140* id: node id (for logging)141* consensus_params: parameters needed for difficulty adjustment validation142* chain_start: best known fork point that the peer's headers branch from143* minimum_required_work: amount of chain work required to accept the chain144*145* @throws SystemClockError if system clock is too far behind chain_start MTP.146*/147HeadersSyncState(NodeId id, const Consensus::Params& consensus_params,148const HeadersSyncParams& params, const CBlockIndex& chain_start,149const arith_uint256& minimum_required_work);151/** Result data structure for ProcessNextHeaders. */152struct ProcessingResult {153std::vector<CBlockHeader> pow_validated_headers;154bool success{false};155bool request_more{false};156};158/** Process a batch of headers, once a sync via this mechanism has started159*160* received_headers: headers that were received over the network for processing.161* Assumes the caller has already verified the headers162* are continuous, and has checked that each header163* satisfies the proof-of-work target included in the164* header (but not necessarily verified that the165* proof-of-work target is correct and passes consensus166* rules).167* full_headers_message: true if the message was at max capacity,168* indicating more headers may be available169* ProcessingResult.pow_validated_headers: will be filled in with any170* headers that the caller can fully process and171* validate now (because these returned headers are172* on a chain with sufficient work)173* ProcessingResult.success: set to false if an error is detected and the sync is174* aborted; true otherwise.175* ProcessingResult.request_more: if true, the caller is suggested to call176* NextHeadersRequestLocator and send a getheaders message using it.177*/178ProcessingResult ProcessNextHeaders(std::span<const CBlockHeader>179received_headers, bool full_headers_message);181/** Issue the next GETHEADERS message to our peer.182*183* This will return a locator appropriate for the current sync object, to continue the184* synchronization phase it is in.185*/186CBlockLocator NextHeadersRequestLocator() const;188protected:189/** The (secret) offset on the heights for which to create commitments.190*191* m_header_commitments entries are created at any height h for which192* (h % m_params.commitment_period) == m_commit_offset. */193const size_t m_commit_offset;195private:196/** Clear out all download state that might be in progress (freeing any used197* memory), and mark this object as no longer usable.198*/199void Finalize();201/**202* Only called in PRESYNC.203* Validate the work on the headers we received from the network, and204* store commitments for later. Update overall state with successfully205* processed headers.206* On failure, this invokes Finalize() and returns false.207*/208bool ValidateAndStoreHeadersCommitments(std::span<const CBlockHeader> headers);210/** In PRESYNC, process and update state for a single header */211bool ValidateAndProcessSingleHeader(const CBlockHeader& current);213/** In REDOWNLOAD, check a header's commitment (if applicable) and add to214* buffer for later processing */215bool ValidateAndStoreRedownloadedHeader(const CBlockHeader& header);217/** Return a set of headers that satisfy our proof-of-work threshold */218std::vector<CBlockHeader> PopHeadersReadyForAcceptance();220private:221/** NodeId of the peer (used for log messages) **/222const NodeId m_id;224/** We use the consensus params in our anti-DoS calculations */225const Consensus::Params& m_consensus_params;227/** Parameters that impact memory usage for a given chain, especially when attacked. */228const HeadersSyncParams m_params;230/** Store the last block in our block index that the peer's chain builds from */231const CBlockIndex& m_chain_start;233/** Minimum work that we're looking for on this chain. */234const arith_uint256 m_minimum_required_work;236/** Work that we've seen so far on the peer's chain */237arith_uint256 m_current_chain_work;239/** m_hasher is a salted hasher for making our 1-bit commitments to headers we've seen. */240const SaltedUint256Hasher m_hasher;242/** A queue of commitment bits, created during the 1st phase, and verified during the 2nd. */243bitdeque<> m_header_commitments;245/** m_max_commitments is a bound we calculate on how long an honest peer's chain could be,246* given the MTP rule.247*248* Any peer giving us more headers than this will have its sync aborted. This serves as a249* memory bound on m_header_commitments. */250uint64_t m_max_commitments{0};
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.