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) 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>7#include <crypto/sha256.h>8#include <hash.h>9#include <primitives/block.h>10#include <primitives/transaction.h>11#include <util/check.h>13#include <cstddef>14#include <utility>16/* WARNING! If you're reading this because you're learning about crypto17and/or designing a new system that will use merkle trees, keep in mind18that the following merkle tree algorithm has a serious flaw related to19duplicate txids, resulting in a vulnerability (CVE-2012-2459).21The reason is that if the number of hashes in the list at a given level22is odd, the last one is duplicated before computing the next level (which23is unusual in Merkle trees). This results in certain sequences of24transactions leading to the same merkle root. For example, these two25trees:27A A28/ \ / \29B C B C30/ \ | / \ / \31D E F D E F F32/ \ / \ / \ / \ / \ / \ / \331 2 3 4 5 6 1 2 3 4 5 6 5 635for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and366 are repeated) result in the same root hash A (because the hash of both37of (F) and (F,F) is C).39The vulnerability results from being able to send a block with such a40transaction list, with the same merkle root, and the same block hash as41the original without duplication, resulting in failed validation. If the42receiving node proceeds to mark that block as permanently invalid43however, it will fail to accept further unmodified (and thus potentially44valid) versions of the same block. We defend against this by detecting45the case where we would hash two identical hashes at the end of the list46together, and treating that identically to the block having an invalid47merkle root. Assuming no double-SHA256 collisions, this will detect all48known ways of changing the transactions without affecting the merkle49root.50*/51uint256 ComputeMerkleRoot(std::vector<uint256> hashes, bool* mutated) {52bool mutation = false;53while (hashes.size() > 1) {54if (mutated) {55// Check every level because equal pairs can appear above the leaves,56// as in the [1,2,3,4,5,6,5,6] construction described above.57// Continuing after finding one is redundant, but mutated blocks should58// not propagate through the network anyway, and the total number of59// comparisons is the same as for an unmutated input of the same length.60for (size_t pos = 0; pos + 1 < hashes.size(); pos += 2) {61if (hashes[pos] == hashes[pos + 1]) mutation = true;62}63}64if (hashes.size() & 1) {65hashes.push_back(hashes.back());66}67SHA256D64(hashes[0].begin(), hashes[0].begin(), hashes.size() / 2);68hashes.resize(hashes.size() / 2);69}70if (mutated) *mutated = mutation;71if (hashes.size() == 0) return uint256();72return hashes[0];73}76uint256 BlockMerkleRoot(const CBlock& block, bool* mutated)77{78std::vector<uint256> leaves;79leaves.reserve((block.vtx.size() + 1) & ~1ULL); // capacity rounded up to even80for (size_t s = 0; s < block.vtx.size(); s++) {81leaves.push_back(block.vtx[s]->GetHash().ToUint256());82}83return ComputeMerkleRoot(std::move(leaves), mutated);84}86uint256 BlockWitnessMerkleRoot(const CBlock& block)87{88std::vector<uint256> leaves;89leaves.reserve((block.vtx.size() + 1) & ~1ULL); // capacity rounded up to even90leaves.emplace_back(); // The witness hash of the coinbase is 0.91for (size_t s = 1; s < block.vtx.size(); s++) {92leaves.push_back(block.vtx[s]->GetWitnessHash().ToUint256());93}94return ComputeMerkleRoot(std::move(leaves));95}97/* This implements a constant-space merkle path calculator, limited to 2^32 leaves. */98static void MerkleComputation(const std::vector<uint256>& leaves, uint32_t leaf_pos, std::vector<uint256>& path)99{100path.clear();101Assume(leaves.size() <= UINT32_MAX);102if (leaves.size() == 0) {103return;104}105// count is the number of leaves processed so far.106uint32_t count = 0;107// inner is an array of eagerly computed subtree hashes, indexed by tree108// level (0 being the leaves).109// For example, when count is 25 (11001 in binary), inner[4] is the hash of110// the first 16 leaves, inner[3] of the next 8 leaves, and inner[0] equal to111// the last leaf. The other inner entries are undefined.112uint256 inner[32];113// Which position in inner is a hash that depends on the matching leaf.114int matchlevel = -1;115// First process all leaves into 'inner' values.116while (count < leaves.size()) {117uint256 h = leaves[count];118bool matchh = count == leaf_pos;119count++;120int level;121// For each of the lower bits in count that are 0, do 1 step. Each122// corresponds to an inner value that existed before processing the123// current leaf, and each needs a hash to combine it.124for (level = 0; !(count & ((uint32_t{1}) << level)); level++) {125if (matchh) {126path.push_back(inner[level]);127} else if (matchlevel == level) {128path.push_back(h);129matchh = true;130}131h = Hash(inner[level], h);132}133// Store the resulting hash at inner position level.134inner[level] = h;135if (matchh) {136matchlevel = level;137}138}139// Do a final 'sweep' over the rightmost branch of the tree to process140// odd levels, and reduce everything to a single top value.141// Level is the level (counted from the bottom) up to which we've sweeped.142int level = 0;143// As long as bit number level in count is zero, skip it. It means there144// is nothing left at this level.145while (!(count & ((uint32_t{1}) << level))) {146level++;147}148uint256 h = inner[level];149bool matchh = matchlevel == level;150while (count != ((uint32_t{1}) << level)) {151// If we reach this point, h is an inner value that is not the top.152// We combine it with itself (Bitcoin's special rule for odd levels in153// the tree) to produce a higher level one.154if (matchh) {155path.push_back(h);156}157h = Hash(h, h);158// Increment count to the value it would have if two entries at this159// level had existed.160count += ((uint32_t{1}) << level);161level++;162// And propagate the result upwards accordingly.163while (!(count & ((uint32_t{1}) << level))) {164if (matchh) {165path.push_back(inner[level]);166} else if (matchlevel == level) {167path.push_back(h);168matchh = true;169}170h = Hash(inner[level], h);171level++;172}173}174}176static std::vector<uint256> ComputeMerklePath(const std::vector<uint256>& leaves, uint32_t position) {177std::vector<uint256> ret;178MerkleComputation(leaves, position, ret);179return ret;180}182std::vector<uint256> TransactionMerklePath(const CBlock& block, uint32_t position)183{184std::vector<uint256> leaves;185leaves.resize(block.vtx.size());186for (size_t s = 0; s < block.vtx.size(); s++) {187leaves[s] = block.vtx[s]->GetHash().ToUint256();188}189return ComputeMerklePath(leaves, position);190}