Merkle Root and Proofs

medium · bitcoin, merkle, hash

Merkle Root and Proofs (Bitcoin-style)

Given a list of leaves, build a Merkle tree using double SHA-256.

Rules:

  • Leaf hash: H(leaf) = SHA256(SHA256(leaf))
  • Internal node: H(left || right) (also double SHA-256)
  • If a level has an odd number of nodes, duplicate the last hash.
  • The Merkle root of an empty list is the all-zero hash.

Types and functions

type ProofStep struct {
    Hash [32]byte
    Left bool // true if Hash is the left sibling
}

func MerkleRoot(leaves [][]byte) [32]byte
func MerkleProof(leaves [][]byte, index int) []ProofStep
func VerifyMerkleProof(leaf []byte, proof []ProofStep, root [32]byte) bool

Behavior

  • MerkleProof returns nil if index is out of range or leaves is empty.
  • Proof steps are ordered from leaf level to root.
  • VerifyMerkleProof returns true if the proof reconstructs root.
Run tests to see results
No issues detected