Merkle Root and Proofs
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
MerkleProofreturns nil ifindexis out of range or leaves is empty.- Proof steps are ordered from leaf level to root.
VerifyMerkleProofreturns true if the proof reconstructsroot.
Run tests to see results
No issues detected