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) 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#include <headerssync.h>7#include <pow.h>8#include <util/check.h>9#include <util/log.h>10#include <util/time.h>11#include <util/vector.h>13// Our memory analysis in headerssync-params.py assumes this many bytes for a14// CompressedHeader (we should re-calculate parameters if we compress further).15static_assert(sizeof(CompressedHeader) == 48);17HeadersSyncState::HeadersSyncState(NodeId id,18const Consensus::Params& consensus_params,19const HeadersSyncParams& params,20const CBlockIndex& chain_start,21const arith_uint256& minimum_required_work)22: m_commit_offset((assert(params.commitment_period > 0), // HeadersSyncParams field must be initialized to non-zero.23FastRandomContext().randrange(params.commitment_period))),24m_id(id),25m_consensus_params(consensus_params),26m_params(params),27m_chain_start(chain_start),28m_minimum_required_work(minimum_required_work),29m_current_chain_work(chain_start.nChainWork),30m_last_header_received(m_chain_start.GetBlockHeader()),31m_current_height(chain_start.nHeight)32{33// Estimate the number of blocks that could possibly exist on the peer's34// chain *right now* using 6 blocks/second (fastest blockrate given the MTP35// rule) times the number of seconds from the last allowed block until36// today. This serves as a memory bound on how many commitments we might37// store from this peer, and we can safely give up syncing if the peer38// exceeds this bound, because it's not possible for a consensus-valid39// chain to be longer than this (at the current time -- in the future we40// could try again, if necessary, to sync a longer chain).41const auto now{NodeClock::now()};42const int64_t max_seconds_since_start{Ticks<std::chrono::seconds>(now - NodeSeconds{std::chrono::seconds{chain_start.GetMedianTimePast()}})43+ MAX_FUTURE_BLOCK_TIME};44if (max_seconds_since_start < 0) {45throw SystemClockError{strprintf(46"System clock is more than %d minutes behind chain start MTP (%s vs %s).",47MAX_FUTURE_BLOCK_TIME / 60,48FormatISO8601DateTime(TicksSinceEpoch<std::chrono::seconds>(now)),49FormatISO8601DateTime(chain_start.GetMedianTimePast()))};50}51m_max_commitments = 6 * max_seconds_since_start / m_params.commitment_period;53LogDebug(BCLog::NET, "Initial headers sync started with peer=%d: height=%i, max_commitments=%i, min_work=%s\n", m_id, m_current_height, m_max_commitments, m_minimum_required_work.ToString());54}56/** Free any memory in use, and mark this object as no longer usable. This is57* required to guarantee that we won't reuse this object with the same58* SaltedUint256Hasher for another sync. */59void HeadersSyncState::Finalize()60{61Assume(m_download_state != State::FINAL);62ClearShrink(m_header_commitments);63m_last_header_received.SetNull();64ClearShrink(m_redownloaded_headers);65m_redownload_buffer_last_hash.SetNull();66m_redownload_buffer_first_prev_hash.SetNull();67m_process_all_remaining_headers = false;68m_current_height = 0;70m_download_state = State::FINAL;71}73/** Process the next batch of headers received from our peer.74* Validate and store commitments, and compare total chainwork to our target to75* see if we can switch to REDOWNLOAD mode. */76HeadersSyncState::ProcessingResult HeadersSyncState::ProcessNextHeaders(77std::span<const CBlockHeader> received_headers, const bool full_headers_message)78{79ProcessingResult ret;81Assume(!received_headers.empty());82if (received_headers.empty()) return ret;84Assume(m_download_state != State::FINAL);85if (m_download_state == State::FINAL) return ret;87if (m_download_state == State::PRESYNC) {88// During PRESYNC, we minimally validate block headers and89// occasionally add commitments to them, until we reach our work90// threshold (at which point m_download_state is updated to REDOWNLOAD).91ret.success = ValidateAndStoreHeadersCommitments(received_headers);92if (ret.success) {93if (full_headers_message || m_download_state == State::REDOWNLOAD) {94// A full headers message means the peer may have more to give us;95// also if we just switched to REDOWNLOAD then we need to re-request96// headers from the beginning.97ret.request_more = true;98} else {99Assume(m_download_state == State::PRESYNC);100// If we're in PRESYNC and we get a non-full headers101// message, then the peer's chain has ended and definitely doesn't102// have enough work, so we can stop our sync.103LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (presync phase)\n", m_id, m_current_height);104}105}106} else if (m_download_state == State::REDOWNLOAD) {107// During REDOWNLOAD, we compare our stored commitments to what we108// receive, and add headers to our redownload buffer. When the buffer109// gets big enough (meaning that we've checked enough commitments),110// we'll return a batch of headers to the caller for processing.111ret.success = true;112for (const auto& hdr : received_headers) {113if (!ValidateAndStoreRedownloadedHeader(hdr)) {114// Something went wrong -- the peer gave us an unexpected chain.115// We could consider looking at the reason for failure and116// punishing the peer, but for now just give up on sync.117ret.success = false;118break;119}120}122if (ret.success) {123// Return any headers that are ready for acceptance.124ret.pow_validated_headers = PopHeadersReadyForAcceptance();126// If we hit our target blockhash, then all remaining headers will be127// returned and we can clear any leftover internal state.128if (m_redownloaded_headers.empty() && m_process_all_remaining_headers) {129LogDebug(BCLog::NET, "Initial headers sync complete with peer=%d: releasing all at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height);130} else if (full_headers_message) {131// If the headers message is full, we need to request more.132ret.request_more = true;133} else {134// For some reason our peer gave us a high-work chain, but is now135// declining to serve us that full chain again. Give up.136// Note that there's no more processing to be done with these137// headers, so we can still return success.138LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: incomplete headers message at height=%i (redownload phase)\n", m_id, m_redownload_buffer_last_height);139}140}141}143if (!(ret.success && ret.request_more)) Finalize();144return ret;145}147bool HeadersSyncState::ValidateAndStoreHeadersCommitments(std::span<const CBlockHeader> headers)148{149// The caller should not give us an empty set of headers.150Assume(headers.size() > 0);151if (headers.size() == 0) return true;153Assume(m_download_state == State::PRESYNC);154if (m_download_state != State::PRESYNC) return false;156if (headers[0].hashPrevBlock != m_last_header_received.GetHash()) {157// Somehow our peer gave us a header that doesn't connect.158// This might be benign -- perhaps our peer reorged away from the chain159// they were on. Give up on this sync for now (likely we will start a160// new sync with a new starting point).161LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (presync phase)\n", m_id, m_current_height);162return false;163}165// If it does connect, (minimally) validate and occasionally store166// commitments.167for (const auto& hdr : headers) {168if (!ValidateAndProcessSingleHeader(hdr)) {169return false;170}171}173if (m_current_chain_work >= m_minimum_required_work) {174m_redownloaded_headers.clear();175m_redownload_buffer_last_height = m_chain_start.nHeight;176m_redownload_buffer_first_prev_hash = m_chain_start.GetBlockHash();177m_redownload_buffer_last_hash = m_chain_start.GetBlockHash();178m_redownload_chain_work = m_chain_start.nChainWork;179m_download_state = State::REDOWNLOAD;180LogDebug(BCLog::NET, "Initial headers sync transition with peer=%d: reached sufficient work at height=%i, redownloading from height=%i\n", m_id, m_current_height, m_redownload_buffer_last_height);181}182return true;183}185bool HeadersSyncState::ValidateAndProcessSingleHeader(const CBlockHeader& current)186{187Assume(m_download_state == State::PRESYNC);188if (m_download_state != State::PRESYNC) return false;190int next_height = m_current_height + 1;192// Verify that the difficulty isn't growing too fast; an adversary with193// limited hashing capability has a greater chance of producing a high194// work chain if they compress the work into as few blocks as possible,195// so don't let anyone give a chain that would violate the difficulty196// adjustment maximum.197if (!PermittedDifficultyTransition(m_consensus_params, next_height,198m_last_header_received.nBits, current.nBits)) {199LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (presync phase)\n", m_id, next_height);200return false;201}203if (next_height % m_params.commitment_period == m_commit_offset) {204// Add a commitment.205m_header_commitments.push_back(m_hasher(current.GetHash()) & 1);206if (m_header_commitments.size() > m_max_commitments) {207// The peer's chain is too long; give up.208// It's possible the chain grew since we started the sync; so209// potentially we could succeed in syncing the peer's chain if we210// try again later.211LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: exceeded max commitments at height=%i (presync phase)\n", m_id, next_height);212return false;213}214}216m_current_chain_work += GetBlockProof(current);217m_last_header_received = current;218m_current_height = next_height;220return true;221}223bool HeadersSyncState::ValidateAndStoreRedownloadedHeader(const CBlockHeader& header)224{225Assume(m_download_state == State::REDOWNLOAD);226if (m_download_state != State::REDOWNLOAD) return false;228int64_t next_height = m_redownload_buffer_last_height + 1;230// Ensure that we're working on a header that connects to the chain we're231// downloading.232if (header.hashPrevBlock != m_redownload_buffer_last_hash) {233LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: non-continuous headers at height=%i (redownload phase)\n", m_id, next_height);234return false;235}237// Check that the difficulty adjustments are within our tolerance:238uint32_t previous_nBits{0};239if (!m_redownloaded_headers.empty()) {240previous_nBits = m_redownloaded_headers.back().nBits;241} else {242previous_nBits = m_chain_start.nBits;243}245if (!PermittedDifficultyTransition(m_consensus_params, next_height,246previous_nBits, header.nBits)) {247LogDebug(BCLog::NET, "Initial headers sync aborted with peer=%d: invalid difficulty transition at height=%i (redownload phase)\n", m_id, next_height);248return false;249}
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.