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.
3752// The block only is a candidate for the most-work-chain if it has the same3753// or more work than our current tip.3754if (m_chain.Tip() != nullptr && setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) {3755return;3756}3758const CBlockIndex* target_block{TargetBlock()};3759if (!target_block) {3760// If no specific target block, add all entries that have more3761// work than the tip.3762setBlockIndexCandidates.insert(pindex);3763} else {3764// If there is a target block, only consider connecting blocks3765// towards the target block.3766if (target_block->GetAncestor(pindex->nHeight) == pindex) {3767setBlockIndexCandidates.insert(pindex);3768}3769}3770}3772/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */3773void ChainstateManager::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pindexNew, const FlatFilePos& pos)3774{3775AssertLockHeld(cs_main);3776pindexNew->nTx = block.vtx.size();3777// Typically m_chain_tx_count will be 0 at this point, but it can be nonzero if this3778// is a pruned block which is being downloaded again, or if this is an3779// assumeutxo snapshot block which has a hardcoded m_chain_tx_count value from the3780// snapshot metadata. If the pindex is not the snapshot block and the3781// m_chain_tx_count value is not zero, assert that value is actually correct.3782auto prev_tx_sum = [](CBlockIndex& block) { return block.nTx + (block.pprev ? block.pprev->m_chain_tx_count : 0); };3783if (!Assume(pindexNew->m_chain_tx_count == 0 || pindexNew->m_chain_tx_count == prev_tx_sum(*pindexNew) ||3784std::ranges::any_of(m_chainstates, [&](const auto& cs) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return cs->SnapshotBase() == pindexNew; }))) {3785LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",3786pindexNew->nHeight, pindexNew->m_chain_tx_count, prev_tx_sum(*pindexNew), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);3787pindexNew->m_chain_tx_count = 0;3788}3789pindexNew->nFile = pos.nFile;3790pindexNew->nDataPos = pos.nPos;3791pindexNew->nUndoPos = 0;3792pindexNew->nStatus |= BLOCK_HAVE_DATA;3793if (DeploymentActiveAt(*pindexNew, *this, Consensus::DEPLOYMENT_SEGWIT)) {3794pindexNew->nStatus |= BLOCK_OPT_WITNESS;3795}3796pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);3797m_blockman.m_dirty_blockindex.insert(pindexNew);3799if (pindexNew->pprev == nullptr || pindexNew->pprev->HaveNumChainTxs()) {3800// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.3801std::deque<CBlockIndex*> queue;3802queue.push_back(pindexNew);3804// Recursively process any descendant blocks that now may be eligible to be connected.3805while (!queue.empty()) {3806CBlockIndex *pindex = queue.front();3807queue.pop_front();3808// Before setting m_chain_tx_count, assert that it is 0 or already set to3809// the correct value. This assert will fail after receiving the3810// assumeutxo snapshot block if assumeutxo snapshot metadata has an3811// incorrect hardcoded AssumeutxoData::m_chain_tx_count value.3812if (!Assume(pindex->m_chain_tx_count == 0 || pindex->m_chain_tx_count == prev_tx_sum(*pindex))) {3813LogWarning("Internal bug detected: block %d has unexpected m_chain_tx_count %i that should be %i (%s %s). Please report this issue here: %s\n",3814pindex->nHeight, pindex->m_chain_tx_count, prev_tx_sum(*pindex), CLIENT_NAME, FormatFullVersion(), CLIENT_BUGREPORT);3815}3816pindex->m_chain_tx_count = prev_tx_sum(*pindex);3817pindex->nSequenceId = nBlockSequenceId++;3818for (const auto& c : m_chainstates) {3819c->TryAddBlockIndexCandidate(pindex);3820}3821std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = m_blockman.m_blocks_unlinked.equal_range(pindex);3822while (range.first != range.second) {3823std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;3824queue.push_back(it->second);3825range.first++;3826m_blockman.m_blocks_unlinked.erase(it);3827}3828}3829} else {3830if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {3831m_blockman.AddUnlinkedBlock(pindexNew);3832}3833}3834}3836static bool CheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true)3837{3838// Check proof of work matches claimed amount3839if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits, consensusParams))3840return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "high-hash", "proof of work failed");3842return true;3843}3845static bool CheckMerkleRoot(const CBlock& block, BlockValidationState& state)3846{3847if (block.m_checked_merkle_root) return true;3849bool mutated;3850uint256 merkle_root = BlockMerkleRoot(block, &mutated);3851if (block.hashMerkleRoot != merkle_root) {3852return state.Invalid(3853/*result=*/BlockValidationResult::BLOCK_MUTATED,3854/*reject_reason=*/"bad-txnmrklroot",3855/*debug_message=*/"hashMerkleRoot mismatch");3856}3858// Check for merkle tree malleability (CVE-2012-2459): repeating sequences3859// of transactions in a block without affecting the merkle root of a block,3860// while still invalidating it.3861if (mutated) {3862return state.Invalid(3863/*result=*/BlockValidationResult::BLOCK_MUTATED,3864/*reject_reason=*/"bad-txns-duplicate",3865/*debug_message=*/"duplicate transaction");3866}3868block.m_checked_merkle_root = true;3869return true;3870}3872/** CheckWitnessMalleation performs checks for block malleation with regard to3873* its witnesses.3874*3875* Note: If the witness commitment is expected (i.e. `expect_witness_commitment3876* = true`), then the block is required to have at least one transaction and the3877* first transaction needs to have at least one input. */3878static bool CheckWitnessMalleation(const CBlock& block, bool expect_witness_commitment, BlockValidationState& state)3879{3880if (expect_witness_commitment) {3881if (block.m_checked_witness_commitment) return true;3883int commitpos = GetWitnessCommitmentIndex(block);3884if (commitpos != NO_WITNESS_COMMITMENT) {3885assert(!block.vtx.empty() && !block.vtx[0]->vin.empty());3886const auto& witness_stack{block.vtx[0]->vin[0].scriptWitness.stack};3888if (witness_stack.size() != 1 || witness_stack[0].size() != 32) {3889return state.Invalid(3890/*result=*/BlockValidationResult::BLOCK_MUTATED,3891/*reject_reason=*/"bad-witness-nonce-size",3892/*debug_message=*/strprintf("%s : invalid witness reserved value size", __func__));3893}3895// The malleation check is ignored; as the transaction tree itself3896// already does not permit it, it is impossible to trigger in the3897// witness tree.3898uint256 hash_witness = BlockWitnessMerkleRoot(block);3900CHash256().Write(hash_witness).Write(witness_stack[0]).Finalize(hash_witness);3901if (memcmp(hash_witness.begin(), &block.vtx[0]->vout[commitpos].scriptPubKey[6], 32)) {3902return state.Invalid(3903/*result=*/BlockValidationResult::BLOCK_MUTATED,3904/*reject_reason=*/"bad-witness-merkle-match",3905/*debug_message=*/strprintf("%s : witness merkle commitment mismatch", __func__));3906}3908block.m_checked_witness_commitment = true;3909return true;3910}3911}3913// No witness data is allowed in blocks that don't commit to witness data, as this would otherwise leave room for spam3914for (const auto& tx : block.vtx) {3915if (tx->HasWitness()) {3916return state.Invalid(3917/*result=*/BlockValidationResult::BLOCK_MUTATED,3918/*reject_reason=*/"unexpected-witness",3919/*debug_message=*/strprintf("%s : unexpected witness data found", __func__));3920}3921}3923return true;3924}3926bool CheckBlock(const CBlock& block, BlockValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)3927{3928// These are checks that are independent of context.3930if (block.fChecked)3931return true;3933// Check that the header is valid (particularly PoW). This is mostly3934// redundant with the call in AcceptBlockHeader.3935if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))3936return false;3938// Signet only: check block solution3939if (consensusParams.signet_blocks && fCheckPOW && !CheckSignetBlockSolution(block, consensusParams)) {3940return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-signet-blksig", "signet block signature validation failure");3941}3943// Check the merkle root.3944if (fCheckMerkleRoot && !CheckMerkleRoot(block, state)) {3945return false;3946}3948// All potential-corruption validation must be done before we do any3949// transaction validation, as otherwise we may mark the header as invalid3950// because we receive the wrong transactions for it.3951// Note that witness malleability is checked in ContextualCheckBlock, so no3952// checks that use witness data may be performed here.3954// Size limits3955if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(TX_NO_WITNESS(block)) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)3956return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-length", "size limits failed");3958// First transaction must be coinbase, the rest must not be3959if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())3960return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-missing", "first tx is not coinbase");3961for (unsigned int i = 1; i < block.vtx.size(); i++)3962if (block.vtx[i]->IsCoinBase())3963return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-cb-multiple", "more than one coinbase");3965// Check transactions3966// Must check for duplicate inputs (see CVE-2018-17144)3967for (const auto& tx : block.vtx) {3968TxValidationState tx_state;3969if (!CheckTransaction(*tx, tx_state)) {3970// CheckBlock() does context-free validation checks. The only3971// possible failures are consensus failures.3972assert(tx_state.GetResult() == TxValidationResult::TX_CONSENSUS);3973return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, tx_state.GetRejectReason(),3974strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), tx_state.GetDebugMessage()));3975}3976}3977// This underestimates the number of sigops, because unlike ConnectBlock it3978// does not count witness and p2sh sigops.3979unsigned int nSigOps = 0;3980for (const auto& tx : block.vtx)3981{3982nSigOps += GetLegacySigOpCount(*tx);3983}3984if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)3985return state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-blk-sigops", "out-of-bounds SigOpCount");3987if (fCheckPOW && fCheckMerkleRoot)3988block.fChecked = true;3990return true;3991}3993void ChainstateManager::UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev) const3994{3995int commitpos = GetWitnessCommitmentIndex(block);3996static const std::vector<unsigned char> nonce(32, 0x00);3997if (commitpos != NO_WITNESS_COMMITMENT && DeploymentActiveAfter(pindexPrev, *this, Consensus::DEPLOYMENT_SEGWIT) && !block.vtx[0]->HasWitness()) {3998CMutableTransaction tx(*block.vtx[0]);3999tx.vin[0].scriptWitness.stack.resize(1);4000tx.vin[0].scriptWitness.stack[0] = nonce;