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.
2251const Consensus::Params& consensusparams = chainman.GetConsensus();2253// BIP16 didn't become active until Apr 1 2012 (on mainnet, and2254// retroactively applied to testnet)2255// However, only one historical block violated the P2SH rules (on both2256// mainnet and testnet).2257// Similarly, only one historical block violated the TAPROOT rules on2258// mainnet.2259// For simplicity, always leave P2SH+WITNESS+TAPROOT on except for the two2260// violating blocks.2261script_verify_flags flags{SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_TAPROOT};2262const auto it{consensusparams.script_flag_exceptions.find(*Assert(block_index.phashBlock))};2263if (it != consensusparams.script_flag_exceptions.end()) {2264flags = it->second;2265}2267// Enforce the DERSIG (BIP66) rule2268if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_DERSIG)) {2269flags |= SCRIPT_VERIFY_DERSIG;2270}2272// Enforce CHECKLOCKTIMEVERIFY (BIP65)2273if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CLTV)) {2274flags |= SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY;2275}2277// Enforce CHECKSEQUENCEVERIFY (BIP112)2278if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_CSV)) {2279flags |= SCRIPT_VERIFY_CHECKSEQUENCEVERIFY;2280}2282// Enforce BIP147 NULLDUMMY (activated simultaneously with segwit)2283if (DeploymentActiveAt(block_index, chainman, Consensus::DEPLOYMENT_SEGWIT)) {2284flags |= SCRIPT_VERIFY_NULLDUMMY;2285}2287return flags;2288}2291/** Apply the effects of this block (with given index) on the UTXO set represented by coins.2292* Validity checks that depend on the UTXO set are also done; ConnectBlock()2293* can fail if those validity checks fail (among other reasons). */2294bool Chainstate::ConnectBlock(const CBlock& block, BlockValidationState& state, CBlockIndex* pindex,2295CCoinsViewCache& view, bool fJustCheck)2296{2297AssertLockHeld(cs_main);2298assert(pindex);2300uint256 block_hash{block.GetHash()};2301assert(*pindex->phashBlock == block_hash);2303const auto time_start{SteadyClock::now()};2304const CChainParams& params{m_chainman.GetParams()};2306// Check it again in case a previous version let a bad block in2307// NOTE: We don't currently (re-)invoke ContextualCheckBlock() or2308// ContextualCheckBlockHeader() here. This means that if we add a new2309// consensus rule that is enforced in one of those two functions, then we2310// may have let in a block that violates the rule prior to updating the2311// software, and we would NOT be enforcing the rule here. Fully solving2312// upgrade from one software version to the next after a consensus rule2313// change is potentially tricky and issue-specific (see NeedsRedownload()2314// for one approach that was used for BIP 141 deployment).2315// Also, currently the rule against blocks more than 2 hours in the future2316// is enforced in ContextualCheckBlockHeader(); we wouldn't want to2317// re-enforce that rule here (at least until we make it impossible for2318// the clock to go backward).2319if (!CheckBlock(block, state, params.GetConsensus(), !fJustCheck, !fJustCheck)) {2320if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {2321// We don't write down blocks to disk if they may have been2322// corrupted, so this should be impossible unless we're having hardware2323// problems.2324return FatalError(m_chainman.GetNotifications(), state, _("Corrupt block found indicating potential hardware failure."));2325}2326LogError("%s: Consensus::CheckBlock: %s\n", __func__, state.ToString());2327return false;2328}2330// verify that the view's current state corresponds to the previous block2331uint256 hashPrevBlock = pindex->pprev == nullptr ? uint256() : pindex->pprev->GetBlockHash();2332assert(hashPrevBlock == view.GetBestBlock());2334m_chainman.num_blocks_total++;2336// Special case for the genesis block, skipping connection of its transactions2337// (its coinbase is unspendable)2338if (block_hash == params.GetConsensus().hashGenesisBlock) {2339if (!fJustCheck)2340view.SetBestBlock(pindex->GetBlockHash());2341return true;2342}2344const char* script_check_reason;2345if (m_chainman.AssumedValidBlock().IsNull()) {2346script_check_reason = "assumevalid=0 (always verify)";2347} else {2348constexpr int64_t TWO_WEEKS_IN_SECONDS{60 * 60 * 24 * 7 * 2};2349// We've been configured with the hash of a block which has been externally verified to have a valid history.2350// A suitable default value is included with the software and updated from time to time. Because validity2351// relative to a piece of software is an objective fact these defaults can be easily reviewed.2352// This setting doesn't force the selection of any particular chain but makes validating some faster by2353// effectively caching the result of part of the verification.2354BlockMap::const_iterator it{m_blockman.m_block_index.find(m_chainman.AssumedValidBlock())};2355if (it == m_blockman.m_block_index.end()) {2356script_check_reason = "assumevalid hash not in headers";2357} else if (it->second.GetAncestor(pindex->nHeight) != pindex) {2358script_check_reason = (pindex->nHeight > it->second.nHeight) ? "block height above assumevalid height" : "block not in assumevalid chain";2359} else if (m_chainman.m_best_header->GetAncestor(pindex->nHeight) != pindex) {2360script_check_reason = "block not in best header chain";2361} else if (m_chainman.m_best_header->nChainWork < m_chainman.MinimumChainWork()) {2362script_check_reason = "best header chainwork below minimumchainwork";2363} else if (GetBlockProofEquivalentTime(*m_chainman.m_best_header, *pindex, *m_chainman.m_best_header, params.GetConsensus()) <= TWO_WEEKS_IN_SECONDS) {2364script_check_reason = "block too recent relative to best header";2365} else {2366// This block is a member of the assumed verified chain and an ancestor of the best header.2367// Script verification is skipped when connecting blocks under the2368// assumevalid block. Assuming the assumevalid block is valid this2369// is safe because block merkle hashes are still computed and checked,2370// Of course, if an assumed valid block is invalid due to false scriptSigs2371// this optimization would allow an invalid chain to be accepted.2372// The equivalent time check discourages hash power from extorting the network via DOS attack2373// into accepting an invalid block through telling users they must manually set assumevalid.2374// Requiring a software change or burying the invalid block, regardless of the setting, makes2375// it hard to hide the implication of the demand. This also avoids having release candidates2376// that are hardly doing any signature verification at all in testing without having to2377// artificially set the default assumed verified block further back.2378// The test against the minimum chain work prevents the skipping when denied access to any chain at2379// least as good as the expected chain.2380script_check_reason = nullptr;2381}2382}2384const auto time_1{SteadyClock::now()};2385m_chainman.time_check += time_1 - time_start;2386LogDebug(BCLog::BENCH, " - Sanity checks: %.2fms [%.2fs (%.2fms/blk)]\n",2387Ticks<MillisecondsDouble>(time_1 - time_start),2388Ticks<SecondsDouble>(m_chainman.time_check),2389Ticks<MillisecondsDouble>(m_chainman.time_check) / m_chainman.num_blocks_total);2391// Do not allow blocks that contain transactions which 'overwrite' older transactions,2392// unless those are already completely spent.2393// If such overwrites are allowed, coinbases and transactions depending upon those2394// can be duplicated to remove the ability to spend the first instance -- even after2395// being sent to another address.2396// See BIP30, CVE-2012-1909, and https://r6.ca/blog/20120206T005236Z.html for more information.2397// This rule was originally applied to all blocks with a timestamp after March 15, 2012, 0:00 UTC.2398// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the2399// two in the chain that violate it. This prevents exploiting the issue against nodes during their2400// initial block download.2401bool fEnforceBIP30 = !IsBIP30Repeat(*pindex);2403// Once BIP34 activated it was not possible to create new duplicate coinbases and thus other than starting2404// with the 2 existing duplicate coinbase pairs, not possible to create overwriting txs. But by the2405// time BIP34 activated, in each of the existing pairs the duplicate coinbase had overwritten the first2406// before the first had been spent. Since those coinbases are sufficiently buried it's no longer possible to create further2407// duplicate transactions descending from the known pairs either.2408// If we're on the known chain at height greater than where BIP34 activated, we can save the db accesses needed for the BIP30 check.2410// BIP34 requires that a block at height X (block X) has its coinbase2411// scriptSig start with a CScriptNum of X (indicated height X). The above2412// logic of no longer requiring BIP30 once BIP34 activates is flawed in the2413// case that there is a block X before the BIP34 height of 227,931 which has2414// an indicated height Y where Y is greater than X. The coinbase for block2415// X would also be a valid coinbase for block Y, which could be a BIP302416// violation. An exhaustive search of all mainnet coinbases before the2417// BIP34 height which have an indicated height greater than the block height2418// reveals many occurrences. The 3 lowest indicated heights found are2419// 209,921, 490,897, and 1,983,702 and thus coinbases for blocks at these 32420// heights would be the first opportunity for BIP30 to be violated.2422// The search reveals a great many blocks which have an indicated height2423// greater than 1,983,702, so we simply remove the optimization to skip2424// BIP30 checking for blocks at height 1,983,702 or higher. Before we reach2425// that block in another 25 years or so, we should take advantage of a2426// future consensus change to do a new and improved version of BIP34 that2427// will actually prevent ever creating any duplicate coinbases in the2428// future.2429static constexpr int BIP34_IMPLIES_BIP30_LIMIT = 1983702;2431// There is no potential to create a duplicate coinbase at block 209,9212432// because this is still before the BIP34 height and so explicit BIP302433// checking is still active.2435// The final case is block 176,684 which has an indicated height of2436// 490,897. Unfortunately, this issue was not discovered until about 2 weeks2437// before block 490,897 so there was not much opportunity to address this2438// case other than to carefully analyze it and determine it would not be a2439// problem. Block 490,897 was, in fact, mined with a different coinbase than2440// block 176,684, but it is important to note that even if it hadn't been or2441// is remined on an alternate fork with a duplicate coinbase, we would still2442// not run into a BIP30 violation. This is because the coinbase for 176,6842443// is spent in block 185,956 in transaction2444// d4f7fbbf92f4a3014a230b2dc70b8058d02eb36ac06b4a0736d9d60eaa9e8781. This2445// spending transaction can't be duplicated because it also spends coinbase2446// 0328dd85c331237f18e781d692c92de57649529bd5edf1d01036daea32ffde29. This2447// coinbase has an indicated height of over 4.2 billion, and wouldn't be2448// duplicatable until that height, and it's currently impossible to create a2449// chain that long. Nevertheless we may wish to consider a future soft fork2450// which retroactively prevents block 490,897 from creating a duplicate2451// coinbase. The two historical BIP30 violations often provide a confusing2452// edge case when manipulating the UTXO and it would be simpler not to have2453// another edge case to deal with.2455// testnet3 has no blocks before the BIP34 height with indicated heights2456// post BIP34 before approximately height 486,000,000. After block2457// 1,983,702 testnet3 starts doing unnecessary BIP30 checking again.2458assert(pindex->pprev);2459CBlockIndex* pindexBIP34height = pindex->pprev->GetAncestor(params.GetConsensus().BIP34Height);2460//Only continue to enforce if we're below BIP34 activation height or the block hash at that height doesn't correspond.2461fEnforceBIP30 = fEnforceBIP30 && (!pindexBIP34height || !(pindexBIP34height->GetBlockHash() == params.GetConsensus().BIP34Hash));2463// TODO: Remove BIP30 checking from block height 1,983,702 on, once we have a2464// consensus change that ensures coinbases at those heights cannot2465// duplicate earlier coinbases.2466if (fEnforceBIP30 || pindex->nHeight >= BIP34_IMPLIES_BIP30_LIMIT) {2467for (const auto& tx : block.vtx) {2468for (size_t o = 0; o < tx->vout.size(); o++) {2469if (view.HaveCoin(COutPoint(tx->GetHash(), o))) {2470state.Invalid(BlockValidationResult::BLOCK_CONSENSUS, "bad-txns-BIP30",2471"tried to overwrite transaction");2472}2473}2474}2475}2477// Enforce BIP68 (sequence locks)2478int nLockTimeFlags = 0;2479if (DeploymentActiveAt(*pindex, m_chainman, Consensus::DEPLOYMENT_CSV)) {2480nLockTimeFlags |= LOCKTIME_VERIFY_SEQUENCE;2481}2483// Get the script flags for this block2484script_verify_flags flags{GetBlockScriptFlags(*pindex, m_chainman)};2486const auto time_2{SteadyClock::now()};2487m_chainman.time_forks += time_2 - time_1;2488LogDebug(BCLog::BENCH, " - Fork checks: %.2fms [%.2fs (%.2fms/blk)]\n",2489Ticks<MillisecondsDouble>(time_2 - time_1),2490Ticks<SecondsDouble>(m_chainman.time_forks),2491Ticks<MillisecondsDouble>(m_chainman.time_forks) / m_chainman.num_blocks_total);2493const bool fScriptChecks{!!script_check_reason};2494const kernel::ChainstateRole role{GetRole()};2495if (script_check_reason != m_last_script_check_reason_logged && role.validated && !role.historical) {2496if (fScriptChecks) {2497LogInfo("Enabling script verification at block #%d (%s): %s.",2498pindex->nHeight, block_hash.ToString(), script_check_reason);2499} else {2500LogInfo("Disabling script verification at block #%d (%s).",