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) 2015-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 <consensus/merkle.h>6#include <test/util/common.h>7#include <test/util/random.h>8#include <test/util/setup_common.h>10#include <boost/test/unit_test.hpp>12BOOST_FIXTURE_TEST_SUITE(merkle_tests, BasicTestingSetup)14static uint256 ComputeMerkleRootFromBranch(const uint256& leaf, const std::vector<uint256>& vMerkleBranch, uint32_t nIndex) {15uint256 hash = leaf;16for (std::vector<uint256>::const_iterator it = vMerkleBranch.begin(); it != vMerkleBranch.end(); ++it) {17if (nIndex & 1) {18hash = Hash(*it, hash);19} else {20hash = Hash(hash, *it);21}22nIndex >>= 1;23}24return hash;25}27// Older version of the merkle root computation code, for comparison.28static uint256 BlockBuildMerkleTree(const CBlock& block, bool* fMutated, std::vector<uint256>& vMerkleTree)29{30vMerkleTree.clear();31vMerkleTree.reserve(block.vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.32for (std::vector<CTransactionRef>::const_iterator it(block.vtx.begin()); it != block.vtx.end(); ++it)33vMerkleTree.push_back((*it)->GetHash().ToUint256());34int j = 0;35bool mutated = false;36for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)37{38for (int i = 0; i < nSize; i += 2)39{40int i2 = std::min(i+1, nSize-1);41if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {42// Two identical hashes at the end of the list at a particular level.43mutated = true;44}45vMerkleTree.push_back(Hash(vMerkleTree[j+i], vMerkleTree[j+i2]));46}47j += nSize;48}49if (fMutated) {50*fMutated = mutated;51}52return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());53}55// Older version of the merkle branch computation code, for comparison.56static std::vector<uint256> BlockGetMerkleBranch(const CBlock& block, const std::vector<uint256>& vMerkleTree, int nIndex)57{58std::vector<uint256> vMerkleBranch;59int j = 0;60for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)61{62int i = std::min(nIndex^1, nSize-1);63vMerkleBranch.push_back(vMerkleTree[j+i]);64nIndex >>= 1;65j += nSize;66}67return vMerkleBranch;68}70static inline int ctz(uint32_t i) {71if (i == 0) return 0;72int j = 0;73while (!(i & 1)) {74j++;75i >>= 1;76}77return j;78}80BOOST_AUTO_TEST_CASE(merkle_test)81{82for (int i = 0; i < 32; i++) {83// Try 32 block sizes: all sizes from 0 to 16 inclusive, and then 15 random sizes.84int ntx = (i <= 16) ? i : 17 + (m_rng.randrange(4000));85// Try up to 3 mutations.86for (int mutate = 0; mutate <= 3; mutate++) {87int duplicate1 = mutate >= 1 ? 1 << ctz(ntx) : 0; // The last how many transactions to duplicate first.88if (duplicate1 >= ntx) break; // Duplication of the entire tree results in a different root (it adds a level).89int ntx1 = ntx + duplicate1; // The resulting number of transactions after the first duplication.90int duplicate2 = mutate >= 2 ? 1 << ctz(ntx1) : 0; // Likewise for the second mutation.91if (duplicate2 >= ntx1) break;92int ntx2 = ntx1 + duplicate2;93int duplicate3 = mutate >= 3 ? 1 << ctz(ntx2) : 0; // And for the third mutation.94if (duplicate3 >= ntx2) break;95int ntx3 = ntx2 + duplicate3;96// Build a block with ntx different transactions.97CBlock block;98block.vtx.resize(ntx);99for (int j = 0; j < ntx; j++) {100CMutableTransaction mtx;101mtx.nLockTime = j;102block.vtx[j] = MakeTransactionRef(std::move(mtx));103}104// Compute the root of the block before mutating it.105bool unmutatedMutated = false;106uint256 unmutatedRoot = BlockMerkleRoot(block, &unmutatedMutated);107BOOST_CHECK(unmutatedMutated == false);108// Optionally mutate by duplicating the last transactions, resulting in the same merkle root.109block.vtx.resize(ntx3);110for (int j = 0; j < duplicate1; j++) {111block.vtx[ntx + j] = block.vtx[ntx + j - duplicate1];112}113for (int j = 0; j < duplicate2; j++) {114block.vtx[ntx1 + j] = block.vtx[ntx1 + j - duplicate2];115}116for (int j = 0; j < duplicate3; j++) {117block.vtx[ntx2 + j] = block.vtx[ntx2 + j - duplicate3];118}119// Compute the merkle root and merkle tree using the old mechanism.120bool oldMutated = false;121std::vector<uint256> merkleTree;122uint256 oldRoot = BlockBuildMerkleTree(block, &oldMutated, merkleTree);123// Compute the merkle root using the new mechanism.124bool newMutated = false;125uint256 newRoot = BlockMerkleRoot(block, &newMutated);126BOOST_CHECK(oldRoot == newRoot);127BOOST_CHECK(newRoot == unmutatedRoot);128BOOST_CHECK((newRoot == uint256()) == (ntx == 0));129BOOST_CHECK(oldMutated == newMutated);130BOOST_CHECK(newMutated == !!mutate);131// If no mutation was done (once for every ntx value), try up to 16 branches.132if (mutate == 0) {133for (int loop = 0; loop < std::min(ntx, 16); loop++) {134// If ntx <= 16, try all branches. Otherwise, try 16 random ones.135int mtx = loop;136if (ntx > 16) {137mtx = m_rng.randrange(ntx);138}139std::vector<uint256> newBranch = TransactionMerklePath(block, mtx);140std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx);141BOOST_CHECK(oldBranch == newBranch);142BOOST_CHECK(ComputeMerkleRootFromBranch(block.vtx[mtx]->GetHash().ToUint256(), newBranch, mtx) == oldRoot);143}144}145}146}147}150BOOST_AUTO_TEST_CASE(merkle_test_empty_block)151{152bool mutated = false;153CBlock block;154uint256 root = BlockMerkleRoot(block, &mutated);156BOOST_CHECK_EQUAL(root.IsNull(), true);157BOOST_CHECK_EQUAL(mutated, false);159// Verify TransactionMerklePath handles empty block correctly160// This tests the early-return path in MerkleComputation161std::vector<uint256> merkle_path = TransactionMerklePath(block, 0);162BOOST_CHECK(merkle_path.empty());163}165BOOST_AUTO_TEST_CASE(merkle_test_oneTx_block)166{167bool mutated = false;168CBlock block;170block.vtx.resize(1);171CMutableTransaction mtx;172mtx.nLockTime = 0;173block.vtx[0] = MakeTransactionRef(std::move(mtx));174uint256 root = BlockMerkleRoot(block, &mutated);175BOOST_CHECK_EQUAL(root, block.vtx[0]->GetHash().ToUint256());176BOOST_CHECK_EQUAL(mutated, false);177}179BOOST_AUTO_TEST_CASE(merkle_test_OddTxWithRepeatedLastTx_block)180{181bool mutated;182CBlock block, blockWithRepeatedLastTx;184block.vtx.resize(3);186for (std::size_t pos = 0; pos < block.vtx.size(); pos++) {187CMutableTransaction mtx;188mtx.nLockTime = pos;189block.vtx[pos] = MakeTransactionRef(std::move(mtx));190}192blockWithRepeatedLastTx = block;193blockWithRepeatedLastTx.vtx.push_back(blockWithRepeatedLastTx.vtx.back());195uint256 rootofBlock = BlockMerkleRoot(block, &mutated);196BOOST_CHECK_EQUAL(mutated, false);198uint256 rootofBlockWithRepeatedLastTx = BlockMerkleRoot(blockWithRepeatedLastTx, &mutated);199BOOST_CHECK_EQUAL(rootofBlock, rootofBlockWithRepeatedLastTx);200BOOST_CHECK_EQUAL(mutated, true);201}203BOOST_AUTO_TEST_CASE(merkle_test_mutated_return_value)204{205// CVE-2012-2459 construction: [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] produce the same root.206const std::vector leaves{uint256{1}, uint256{2}, uint256{3}, uint256{4}, uint256{5}, uint256{6}};207auto mutated_leaves{leaves};208mutated_leaves.insert(mutated_leaves.end(), leaves.end() - 2, leaves.end()); // repeat last two elements210bool mutated{true};211const uint256 unmutated_root{ComputeMerkleRoot(leaves, &mutated)};212BOOST_CHECK(!mutated);213BOOST_CHECK_EQUAL(unmutated_root, ComputeMerkleRoot(mutated_leaves, &mutated));214BOOST_CHECK( mutated);216const std::vector nontrailing_duplicate_leaves{uint256{1}, uint256{1}, uint256{3}, uint256{4}};217mutated = false;218const uint256 nontrailing_duplicate_root{ComputeMerkleRoot(nontrailing_duplicate_leaves, &mutated)};219BOOST_CHECK(nontrailing_duplicate_root == ComputeMerkleRoot(nontrailing_duplicate_leaves));220BOOST_CHECK(mutated);221}223BOOST_AUTO_TEST_CASE(merkle_test_LeftSubtreeRightSubtree)224{225CBlock block, leftSubtreeBlock, rightSubtreeBlock;227block.vtx.resize(4);228std::size_t pos;229for (pos = 0; pos < block.vtx.size(); pos++) {230CMutableTransaction mtx;231mtx.nLockTime = pos;232block.vtx[pos] = MakeTransactionRef(std::move(mtx));233}235for (pos = 0; pos < block.vtx.size() / 2; pos++)236leftSubtreeBlock.vtx.push_back(block.vtx[pos]);238for (pos = block.vtx.size() / 2; pos < block.vtx.size(); pos++)239rightSubtreeBlock.vtx.push_back(block.vtx[pos]);241uint256 root = BlockMerkleRoot(block);242uint256 rootOfLeftSubtree = BlockMerkleRoot(leftSubtreeBlock);243uint256 rootOfRightSubtree = BlockMerkleRoot(rightSubtreeBlock);244std::vector<uint256> leftRight;245leftRight.push_back(rootOfLeftSubtree);246leftRight.push_back(rootOfRightSubtree);247uint256 rootOfLR = ComputeMerkleRoot(leftRight);249BOOST_CHECK_EQUAL(root, rootOfLR);250}
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.