commit 38b24458c7572b82a74239081c964f7e75d7e334
parent 90b21e8be012cb1a782e9e7043f53ba9f54ca1d5
Author: Shivakumar <[email protected]>
Date: Sat, 23 May 2026 00:22:08 +0530
feat(merkle): add functions for proof and merkle tree
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
2 files changed, 295 insertions(+), 0 deletions(-)
diff --git a/internal/merkle/proof.go b/internal/merkle/proof.go
@@ -0,0 +1,129 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package merkle
+
+import (
+ "bytes"
+ "errors"
+ "math/bits"
+
+ "certichain/internal/crypto"
+)
+
+// Direction indicates where the sibling node
+// is located relative to the current hash.
+type Direction byte
+
+const (
+ DirLeft Direction = iota
+ DirRight
+)
+
+// ProofStep represents a single step in the Merkle proof.
+//
+// SiblingHash is the hash paired with the current hash at
+// this tree level.
+//
+// Direction indicates whether the sibling hash was on the
+// left or right side during the parent hash computation.
+type ProofStep struct {
+ SiblingHash crypto.Hash
+ Direction Direction
+}
+
+// Proof represents a Merkle inclusion proof.
+//
+// Steps contain the ordered proof path from leaf to the
+// root.
+//
+// Index is the original leaf index the proof was generated
+// for.
+type Proof struct {
+ Steps []ProofStep
+ Index int
+}
+
+// GenerateProof method generates an inclusion proof for the
+// leaf at the provided index.
+func (t *Tree) GenerateProof(leafIndex int) (*Proof, error) {
+ if t == nil || t.root == nil {
+ return nil, errors.New("merkle: nil tree")
+ }
+
+ if leafIndex < 0 || leafIndex >= t.leafCount {
+ return nil, errors.New("merkle: leaf index out of bound")
+ }
+
+ current := t.leaves[leafIndex]
+
+ depth := bits.Len(uint(t.leafCount - 1))
+ proof := &Proof{
+ Index: leafIndex,
+ Steps: make([]ProofStep, 0, depth),
+ }
+
+ for current.parent != nil {
+ parent := current.parent
+
+ if current == parent.left {
+ proof.Steps = append(proof.Steps, ProofStep{
+ SiblingHash: parent.right.hash,
+ Direction: DirRight,
+ })
+ } else {
+ proof.Steps = append(proof.Steps, ProofStep{
+ SiblingHash: parent.left.hash,
+ Direction: DirLeft,
+ })
+ }
+
+ current = parent
+ }
+
+ return proof, nil
+}
+
+// Verify checks whether a leaf is included in a Merkle tree
+// with the given root using an RFC 6962 inclusion proof.
+func Verify(leafData []byte, proof *Proof, root []byte) (bool, error) {
+ if leafData == nil {
+ return false, errors.New("merkle: nil leaf data")
+ }
+
+ if proof == nil {
+ return false, errors.New("merkle: nil proof")
+ }
+
+ if len(root) != crypto.HashSize {
+ return false, errors.New("merkle: invalid root size")
+ }
+
+ current := hashLeaf(leafData)
+
+ for _, step := range proof.Steps {
+ switch step.Direction {
+ case DirLeft:
+ current = hashNode(step.SiblingHash, current)
+
+ case DirRight:
+ current = hashNode(current, step.SiblingHash)
+
+ default:
+ return false, errors.New("merkle: invalid proof direction")
+ }
+ }
+
+ return bytes.Equal(current[:], root), nil
+}
diff --git a/internal/merkle/tree.go b/internal/merkle/tree.go
@@ -0,0 +1,166 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package merkle
+
+import (
+ "errors"
+
+ "certichain/internal/crypto"
+)
+
+// RFC 6962 prefixes
+//
+// Leaf hashes are computed as:
+//
+// SHA256(0x00 | leaf_data)
+//
+// Node hashes are computed as:
+//
+// SHA256(0x01 | left_hash | right_hash)
+const (
+ leafHashPrefix byte = 0x00
+ nodeHashPrefix byte = 0x01
+)
+
+// Node represents a single Merkle tree node.
+//
+// Leaf node have nil children.
+// Internal nodes have pointers to left and right children.
+type Node struct {
+ hash crypto.Hash
+ left *Node
+ right *Node
+ parent *Node
+}
+
+// Tree represents an RFC 6962 Merkle tree.
+//
+// The leaves slice preserves the original leaf ordering so
+// inclusion proofs can later be generated efficiently without
+// re-traversing the entire tree.
+type Tree struct {
+ root *Node
+ leaves []*Node
+ leafCount int
+}
+
+// New constructs a new RFC 6962 Merkle tree from raw leaf data.
+//
+// The tree is constructed using the RFC 6962 canonical split rule:
+// split of the largest power of two smaller than n.
+func New(data [][]byte) (*Tree, error) {
+ if len(data) == 0 {
+ return nil, errors.New("merkle: empty input")
+ }
+
+ leaves := make([]*Node, 0, len(data))
+
+ for _, datum := range data {
+ if datum == nil {
+ return nil, errors.New("merkle: empty leaf data")
+ }
+
+ leaf := &Node{
+ hash: hashLeaf(datum),
+ }
+ leaves = append(leaves, leaf)
+ }
+
+ return &Tree{
+ root: buildSubtree(leaves),
+ leaves: leaves,
+ leafCount: len(leaves),
+ }, nil
+}
+
+// buildSubtree recursively constructs an RFC 6962 Merkle subtree.
+func buildSubtree(nodes []*Node) *Node {
+ if len(nodes) == 0 {
+ panic("merkle: buildSubtree called with empty nodes")
+ }
+ n := len(nodes)
+
+ if n == 1 {
+ return nodes[0]
+ }
+
+ k := 1
+ for k<<1 < n {
+ k <<= 1
+ }
+
+ left := buildSubtree(nodes[:k])
+ right := buildSubtree(nodes[k:])
+
+ parent := &Node{
+ hash: hashNode(left.hash, right.hash),
+ left: left,
+ right: right,
+ }
+
+ left.parent, right.parent = parent, parent
+
+ return parent
+}
+
+// Root returns the copy of the Merkle root hash.
+//
+// A copy is returned to prevent callers from mutating
+// internal tree state.
+func (t *Tree) Root() []byte {
+ if t == nil || t.root == nil {
+ return nil
+ }
+
+ root := make([]byte, crypto.HashSize)
+ copy(root, t.root.hash[:])
+
+ return root
+}
+
+// LeafCount returns the number of original leaves used to
+// construct the tree.
+func (t *Tree) LeafCount() int {
+ if t == nil {
+ return 0
+ }
+
+ return t.leafCount
+}
+
+// hashLeaf computes an RFC 6962 leaf hash:
+//
+// returns SHA256(0x00 | leaf_data)
+func hashLeaf(data []byte) crypto.Hash {
+ buf := make([]byte, 1+len(data))
+
+ buf[0] = leafHashPrefix
+ copy(buf[1:], data)
+
+ return crypto.HashBytes(buf)
+}
+
+// hashNode computes an RFC 6962 internal node hash:
+//
+// returns SHA256(0x01 | left_hash | right_hash)
+func hashNode(left, right crypto.Hash) crypto.Hash {
+ var buf [1 + 2*crypto.HashSize]byte
+
+ buf[0] = nodeHashPrefix
+ copy(buf[1:1+crypto.HashSize], left[:])
+ copy(buf[1+crypto.HashSize:], right[:])
+
+ return crypto.HashBytes(buf[:])
+}