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) 2018-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 <chain.h>6#include <chainparams.h>7#include <consensus/consensus.h>8#include <consensus/merkle.h>9#include <consensus/validation.h>10#include <interfaces/mining.h>11#include <node/blockstorage.h>12#include <pow.h>13#include <primitives/block.h>14#include <primitives/transaction.h>15#include <random.h>16#include <script/script.h>17#include <sync.h>18#include <test/util/common.h>19#include <test/util/script.h>20#include <test/util/setup_common.h>21#include <txmempool.h>22#include <uint256.h>23#include <util/check.h>24#include <validation.h>25#include <validationinterface.h>27#include <boost/test/unit_test.hpp>29#include <cstddef>30#include <cstdint>31#include <memory>32#include <span>33#include <thread>34#include <utility>35#include <vector>37using kernel::ChainstateRole;39namespace validation_block_tests {40struct MinerTestingSetup : public RegTestingSetup {41std::shared_ptr<CBlock> Block(const uint256& prev_hash);42std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash);43std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash);44std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock);45void BuildChain(const uint256& root, int height, unsigned int invalid_rate, unsigned int branch_rate, unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks);46};47} // namespace validation_block_tests49BOOST_FIXTURE_TEST_SUITE(validation_block_tests, MinerTestingSetup)51struct TestSubscriber final : public CValidationInterface {52uint256 m_expected_tip;54explicit TestSubscriber(uint256 tip) : m_expected_tip(tip) {}56void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override57{58BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());59}61void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override62{63BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);64BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());66m_expected_tip = block->GetHash();67}69void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override70{71BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());72BOOST_CHECK_EQUAL(m_expected_tip, pindex->GetBlockHash());74m_expected_tip = block->hashPrevBlock;75}76};78std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)79{80static int i = 0;81static uint64_t time = Params().GenesisBlock().nTime;83auto mining{interfaces::MakeMining(m_node)};84auto block_template{mining->createNewBlock({85.coinbase_output_script = CScript{} << i++ << OP_TRUE,86}, /*cooldown=*/false)};87BOOST_REQUIRE(block_template);88auto pblock = std::make_shared<CBlock>(block_template->getBlock());89pblock->hashPrevBlock = prev_hash;90pblock->nTime = ++time;92// Make the coinbase transaction with two outputs:93// One zero-value one that has a unique pubkey to make sure that blocks at the same height can have a different hash94// Another one that has the coinbase reward in a P2WSH with OP_TRUE as witness program to make it easy to spend95CMutableTransaction txCoinbase(*pblock->vtx[0]);96txCoinbase.vout.resize(2);97txCoinbase.vout[1].scriptPubKey = P2WSH_OP_TRUE;98txCoinbase.vout[1].nValue = txCoinbase.vout[0].nValue;99txCoinbase.vout[0].nValue = 0;100txCoinbase.vin[0].scriptWitness.SetNull();101// Always pad with OP_0 as dummy extraNonce (also avoids bad-cb-length error for block <=16)102const int prev_height{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(prev_hash)->nHeight)};103txCoinbase.vin[0].scriptSig = CScript{} << prev_height + 1 << OP_0;104txCoinbase.nLockTime = static_cast<uint32_t>(prev_height);105pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));107return pblock;108}110std::shared_ptr<CBlock> MinerTestingSetup::FinalizeBlock(std::shared_ptr<CBlock> pblock)111{112const CBlockIndex* prev_block{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};113m_node.chainman->GenerateCoinbaseCommitment(*pblock, prev_block);115pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);117while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {118++(pblock->nNonce);119}121// submit block header, so that miner can get the block height from the122// global state and the node has the topology of the chain123BlockValidationState ignored;124BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlockHeaders({{*pblock}}, true, ignored));126return pblock;127}129// construct a valid block130std::shared_ptr<const CBlock> MinerTestingSetup::GoodBlock(const uint256& prev_hash)131{132return FinalizeBlock(Block(prev_hash));133}135// construct an invalid block (but with a valid header)136std::shared_ptr<const CBlock> MinerTestingSetup::BadBlock(const uint256& prev_hash)137{138auto pblock = Block(prev_hash);140CMutableTransaction coinbase_spend;141coinbase_spend.vin.emplace_back(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0);142coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);144CTransactionRef tx = MakeTransactionRef(coinbase_spend);145pblock->vtx.push_back(tx);147auto ret = FinalizeBlock(pblock);148return ret;149}151// NOLINTNEXTLINE(misc-no-recursion)152void MinerTestingSetup::BuildChain(const uint256& root, int height, const unsigned int invalid_rate, const unsigned int branch_rate, const unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks)153{154if (height <= 0 || blocks.size() >= max_size) return;156bool gen_invalid = m_rng.randrange(100U) < invalid_rate;157bool gen_fork = m_rng.randrange(100U) < branch_rate;159const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);160blocks.push_back(pblock);161if (!gen_invalid) {162BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);163}165if (gen_fork) {166blocks.push_back(GoodBlock(root));167BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);168}169}171BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)172{173// build a large-ish chain that's likely to have some forks174std::vector<std::shared_ptr<const CBlock>> blocks;175while (blocks.size() < 50) {176blocks.clear();177BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);178}180bool ignored;181// Connect the genesis block and drain any outstanding events182BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(std::make_shared<CBlock>(Params().GenesisBlock()), true, true, &ignored));183m_node.validation_signals->SyncWithValidationInterfaceQueue();185// subscribe to events (this subscriber will validate event ordering)186const CBlockIndex* initial_tip = nullptr;187{188LOCK(cs_main);189initial_tip = m_node.chainman->ActiveChain().Tip();190}191auto sub = std::make_shared<TestSubscriber>(initial_tip->GetBlockHash());192m_node.validation_signals->RegisterSharedValidationInterface(sub);194// create a bunch of threads that repeatedly process a block generated above at random195// this will create parallelism and randomness inside validation - the ValidationInterface196// will subscribe to events generated during block validation and assert on ordering invariance197std::vector<std::thread> threads;198threads.reserve(10);199for (int i = 0; i < 10; i++) {200threads.emplace_back([&]() {201bool ignored;202FastRandomContext insecure;203for (int i = 0; i < 1000; i++) {204const auto& block = blocks[insecure.randrange(blocks.size() - 1)];205Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);206}208// to make sure that eventually we process the full chain - do it here209for (const auto& block : blocks) {210if (block->vtx.size() == 1) {211bool processed = Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);212assert(processed);213}214}215});216}218for (auto& t : threads) {219t.join();220}221m_node.validation_signals->SyncWithValidationInterfaceQueue();223m_node.validation_signals->UnregisterSharedValidationInterface(sub);225LOCK(cs_main);226BOOST_CHECK_EQUAL(sub->m_expected_tip, m_node.chainman->ActiveChain().Tip()->GetBlockHash());227}229/**230* Test that mempool updates happen atomically with reorgs.231*232* This prevents RPC clients, among others, from retrieving immediately-out-of-date mempool data233* during large reorgs.234*235* The test verifies this by creating a chain of `num_txs` blocks, matures their coinbases, and then236* submits txns spending from their coinbase to the mempool. A fork chain is then processed,237* invalidating the txns and evicting them from the mempool.238*239* We verify that the mempool updates atomically by polling it continuously240* from another thread during the reorg and checking that its size only changes241* once. The size changing exactly once indicates that the polling thread's242* view of the mempool is either consistent with the chain state before reorg,243* or consistent with the chain state after the reorg, and not just consistent244* with some intermediate state during the reorg.245*/246BOOST_AUTO_TEST_CASE(mempool_locks_reorg)247{248bool ignored;249auto ProcessBlock = [&](std::shared_ptr<const CBlock> block) -> bool {250return Assert(m_node.chainman)->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&ignored);
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.