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 <chain.h>7#include <tinyformat.h>8#include <util/check.h>10std::string CBlockIndex::ToString() const11{12return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)",13pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString());14}16void CChain::SetTip(CBlockIndex& block)17{18CBlockIndex* pindex = █19vChain.resize(pindex->nHeight + 1);20while (pindex && vChain[pindex->nHeight] != pindex) {21vChain[pindex->nHeight] = pindex;22pindex = pindex->pprev;23}24}26std::vector<uint256> LocatorEntries(const CBlockIndex* index)27{28int step = 1;29std::vector<uint256> have;30if (index == nullptr) return have;32have.reserve(32);33while (index) {34have.emplace_back(index->GetBlockHash());35if (index->nHeight == 0) break;36// Exponentially larger steps back, plus the genesis block.37int height = std::max(index->nHeight - step, 0);38// Use skiplist.39index = index->GetAncestor(height);40if (have.size() > 10) step *= 2;41}42return have;43}45CBlockLocator GetLocator(const CBlockIndex* index)46{47return CBlockLocator{LocatorEntries(index)};48}50const CBlockIndex* CChain::FindFork(const CBlockIndex& index) const51{52const auto* pindex{&index};53if (pindex->nHeight > Height())54pindex = pindex->GetAncestor(Height());55while (pindex && !Contains(*pindex))56pindex = pindex->pprev;57return pindex;58}60CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime, int height) const61{62std::pair<int64_t, int> blockparams = std::make_pair(nTime, height);63std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), blockparams,64[](CBlockIndex* pBlock, const std::pair<int64_t, int>& blockparams) -> bool { return pBlock->GetBlockTimeMax() < blockparams.first || pBlock->nHeight < blockparams.second; });65return (lower == vChain.end() ? nullptr : *lower);66}68/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */69int static inline InvertLowestOne(int n) { return n & (n - 1); }71/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */72int static inline GetSkipHeight(int height) {73if (height < 2)74return 0;76// Determine which height to jump back to. Any number strictly lower than height is acceptable,77// but the following expression seems to perform well in simulations (max 110 steps to go back78// up to 2**18 blocks).79return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);80}82const CBlockIndex* CBlockIndex::GetAncestor(int height) const83{84if (height > nHeight || height < 0) {85return nullptr;86}88const CBlockIndex* pindexWalk = this;89int heightWalk = nHeight;90while (heightWalk > height) {91int heightSkip = GetSkipHeight(heightWalk);92int heightSkipPrev = GetSkipHeight(heightWalk - 1);93if (pindexWalk->pskip != nullptr &&94(heightSkip == height ||95(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&96heightSkipPrev >= height)))) {97// Only follow pskip if pprev->pskip isn't better than pskip->pprev.98pindexWalk = pindexWalk->pskip;99heightWalk = heightSkip;100} else {101assert(pindexWalk->pprev);102pindexWalk = pindexWalk->pprev;103heightWalk--;104}105}106return pindexWalk;107}109CBlockIndex* CBlockIndex::GetAncestor(int height)110{111return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height));112}114void CBlockIndex::BuildSkip()115{116if (pprev)117pskip = pprev->GetAncestor(GetSkipHeight(nHeight));118}120arith_uint256 GetBitsProof(uint32_t bits)121{122arith_uint256 bnTarget;123bool fNegative;124bool fOverflow;125bnTarget.SetCompact(bits, &fNegative, &fOverflow);126if (fNegative || fOverflow || bnTarget == 0)127return 0;128// We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256129// as it's too large for an arith_uint256. However, as 2**256 is at least as large130// as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,131// or ~bnTarget / (bnTarget+1) + 1.132return (~bnTarget / (bnTarget + 1)) + 1;133}135int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)136{137arith_uint256 r;138int sign = 1;139if (to.nChainWork > from.nChainWork) {140r = to.nChainWork - from.nChainWork;141} else {142r = from.nChainWork - to.nChainWork;143sign = -1;144}145r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);146if (r.bits() > 63) {147return sign * std::numeric_limits<int64_t>::max();148}149return sign * int64_t(r.GetLow64());150}152/** Find the last common ancestor two blocks have.153* Both pa and pb must be non-nullptr. */154const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) {155// First rewind to the last common height (the forking point cannot be past one of the two).156if (pa->nHeight > pb->nHeight) {157pa = pa->GetAncestor(pb->nHeight);158} else if (pb->nHeight > pa->nHeight) {159pb = pb->GetAncestor(pa->nHeight);160}161while (pa != pb) {162// Jump back until pa and pb have a common "skip" ancestor.163while (pa->pskip != pb->pskip) {164// This logic relies on the property that equal-height blocks have equal-height skip165// pointers.166Assume(pa->nHeight == pb->nHeight);167Assume(pa->pskip->nHeight == pb->pskip->nHeight);168pa = pa->pskip;169pb = pb->pskip;170}171// At this point, pa and pb are different, but have equal pskip. The forking point lies in172// between pa/pb on the one end, and pa->pskip/pb->pskip on the other end.173pa = pa->pprev;174pb = pb->pprev;175}176return pa;177}