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) 2009-2010 Satoshi Nakamoto2// Copyright (c) 2009-present The Bitcoin Core developers3// Distributed under the MIT software license, see the accompanying4// file COPYING or http://www.opensource.org/licenses/mit-license.php.6#ifndef BITCOIN_MERKLEBLOCK_H7#define BITCOIN_MERKLEBLOCK_H9#include <common/bloom.h>10#include <primitives/block.h>11#include <primitives/transaction_identifier.h>12#include <serialize.h>13#include <uint256.h>15#include <set>16#include <vector>18// Helper functions for serialization.19std::vector<unsigned char> BitsToBytes(const std::vector<bool>& bits);20std::vector<bool> BytesToBits(const std::vector<unsigned char>& bytes);22/** Data structure that represents a partial merkle tree.23*24* It represents a subset of the txid's of a known block, in a way that25* allows recovery of the list of txid's and the merkle root, in an26* authenticated way.27*28* The encoding works as follows: we traverse the tree in depth-first order,29* storing a bit for each traversed node, signifying whether the node is the30* parent of at least one matched leaf txid (or a matched txid itself). In31* case we are at the leaf level, or this bit is 0, its merkle node hash is32* stored, and its children are not explored further. Otherwise, no hash is33* stored, but we recurse into both (or the only) child branch. During34* decoding, the same depth-first traversal is performed, consuming bits and35* hashes as they written during encoding.36*37* The serialization is fixed and provides a hard guarantee about the38* encoded size:39*40* SIZE <= 10 + ceil(32.25*N)41*42* Where N represents the number of leaf nodes of the partial tree. N itself43* is bounded by:44*45* N <= total_transactions46* N <= 1 + matched_transactions*tree_height47*48* The serialization format:49* - uint32 total_transactions (4 bytes)50* - varint number of hashes (1-3 bytes)51* - uint256[] hashes in depth-first order (<= 32*N bytes)52* - varint number of bytes of flag bits (1-3 bytes)53* - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)54* The size constraints follow from this.55*/56class CPartialMerkleTree57{58protected:59/** the total number of transactions in the block */60unsigned int nTransactions;62/** node-is-parent-of-matched-txid bits */63std::vector<bool> vBits;65/** txids and internal hashes */66std::vector<uint256> vHash;68/** flag set when encountering invalid data */69bool fBad;71/** helper function to efficiently calculate the number of nodes at given height in the merkle tree */72unsigned int CalcTreeWidth(int height) const {73return (nTransactions+(1 << height)-1) >> height;74}76/** calculate the hash of a node in the merkle tree (at leaf level: the txid's themselves) */77uint256 CalcHash(int height, unsigned int pos, const std::vector<Txid> &vTxid);79/** recursive function that traverses tree nodes, storing the data as bits and hashes */80void TraverseAndBuild(int height, unsigned int pos, const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch);82/**83* recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.84* it returns the hash of the respective node and its respective index.85*/86uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex);88public:90SERIALIZE_METHODS(CPartialMerkleTree, obj)91{92READWRITE(obj.nTransactions, obj.vHash);93std::vector<unsigned char> bytes;94SER_WRITE(obj, bytes = BitsToBytes(obj.vBits));95READWRITE(bytes);96SER_READ(obj, obj.vBits = BytesToBits(bytes));97SER_READ(obj, obj.fBad = false);98}100/** Construct a partial merkle tree from a list of transaction ids, and a mask that selects a subset of them */101CPartialMerkleTree(const std::vector<Txid> &vTxid, const std::vector<bool> &vMatch);103CPartialMerkleTree();105/**106* extract the matching txid's represented by this partial merkle tree107* and their respective indices within the partial tree.108* returns the merkle root, or 0 in case of failure109*/110uint256 ExtractMatches(std::vector<Txid> &vMatch, std::vector<unsigned int> &vnIndex);112/** Get number of transactions the merkle proof is indicating for cross-reference with113* local blockchain knowledge.114*/115unsigned int GetNumTransactions() const { return nTransactions; };117};120/**121* Used to relay blocks as header + vector<merkle branch>122* to filtered nodes.123*124* NOTE: The class assumes that the given CBlock has *at least* 1 transaction. If the CBlock has 0 txs, it will hit an assertion.125*/126class CMerkleBlock127{128public:129/** Public only for unit testing */130CBlockHeader header;131CPartialMerkleTree txn;133/**134* Public only for unit testing and relay testing (not relayed).135*136* Used only when a bloom filter is specified to allow137* testing the transactions which matched the bloom filter.138*/139std::vector<std::pair<unsigned int, Txid> > vMatchedTxn;141/**142* Create from a CBlock, filtering transactions according to filter143* Note that this will call IsRelevantAndUpdate on the filter for each transaction,144* thus the filter will likely be modified.145*/146CMerkleBlock(const CBlock& block, CBloomFilter& filter) : CMerkleBlock(block, &filter, nullptr) { }148// Create from a CBlock, matching the txids in the set149CMerkleBlock(const CBlock& block, const std::set<Txid>& txids) : CMerkleBlock{block, nullptr, &txids} {}151CMerkleBlock() = default;153SERIALIZE_METHODS(CMerkleBlock, obj) { READWRITE(obj.header, obj.txn); }155private:156// Combined constructor to consolidate code157CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<Txid>* txids);158};160#endif // BITCOIN_MERKLEBLOCK_H