commit 8186527a6b08d906a2803ca4d21d6f379cbbd5c9
parent 38b24458c7572b82a74239081c964f7e75d7e334
Author: Shivakumar <[email protected]>
Date: Sat, 23 May 2026 00:23:44 +0530
test(merkle): add unit tests and fuzz tests for proof and merkle tree
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
4 files changed, 530 insertions(+), 0 deletions(-)
diff --git a/internal/merkle/helper_test.go b/internal/merkle/helper_test.go
@@ -0,0 +1,83 @@
+// 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"
+ "strconv"
+ "testing"
+
+ "certichain/internal/crypto"
+)
+
+// mustTree is a test helper function that creates a
+// RFC 6962 Merkle tree.
+func mustTree(t *testing.T, data [][]byte) *Tree {
+ t.Helper()
+
+ tree, err := New(data)
+ if err != nil {
+ t.Fatalf("New() error = %v", err)
+ }
+
+ return tree
+}
+
+// mustProof generates an inclusion proof for leaf index.
+func mustProof(t *testing.T, tree *Tree, leafIndex int) *Proof {
+ t.Helper()
+
+ proof, err := tree.GenerateProof(leafIndex)
+ if err != nil {
+ t.Fatalf("GenerateProof(%d) error = %v", leafIndex, err)
+ }
+
+ return proof
+}
+
+// makeLeaves generates n deterministic, unique leaf byte slice.
+func makeLeaves(n int) [][]byte {
+ out := make([][]byte, n)
+
+ for i := range out {
+ out[i] = []byte(strconv.Itoa(i))
+ }
+
+ return out
+}
+
+// flipBytes returns a copy of the data with the byte at the pos
+// XOR-flipped.
+func flipBytes(data []byte, pos int) []byte {
+ out := bytes.Clone(data)
+ out[pos] ^= 0xff
+
+ return out
+}
+
+// flipHashByte returns a copy of the hash (h) with the byte at
+// the pos XOR-flipped.
+func flipHashByte(h crypto.Hash, pos int) crypto.Hash {
+ h[pos] ^= 0xff
+ return h
+}
+
+// cloneSteps returns a deep copy of a ProofStep slice.
+func cloneSteps(steps []ProofStep) []ProofStep {
+ out := make([]ProofStep, len(steps))
+ copy(out, steps)
+
+ return out
+}
diff --git a/internal/merkle/merkle_test.go b/internal/merkle/merkle_test.go
@@ -0,0 +1,225 @@
+// 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"
+ "strconv"
+ "testing"
+
+ "certichain/internal/crypto"
+)
+
+// TestVerify_RoundTrip verifies that every leaf in a constructed tree
+// can be proven to exist (positive cases) and that proofs for one leaf
+// are not accepted for another (negative cases).
+//
+// It tests multiple tree sizes to ensure the RFC 6962 split rule
+// is correctly implemented across various tree topologies.
+func TestVerify_RoundTrip(t *testing.T) {
+ t.Parallel()
+
+ // sizes covers edge cases: 1 (root is leaf), 2 (perfect balance),
+ // 3 (odd promotion), and non-power-of-2 large counts.
+ sizes := []int{1, 2, 3, 7, 8, 9, 16, 100}
+
+ for _, n := range sizes {
+ t.Run("n="+strconv.Itoa(n), func(t *testing.T) {
+ t.Parallel()
+
+ data := makeLeaves(n)
+ tree := mustTree(t, data)
+ root := tree.Root()
+
+ for i := range data {
+ proof := mustProof(t, tree, i)
+
+ // 1. Positive Verification: Verify the correct leaf matches the proof.
+ ok, err := Verify(data[i], proof, root)
+ if err != nil {
+ t.Errorf("leaf %d: Verify() unexpected error = %v", i, err)
+ continue
+ }
+ if !ok {
+ t.Errorf("leaf %d: Verify() returned false for valid proof", i)
+ }
+
+ // 2. Negative Verification: Ensure other leaves are rejected by this proof.
+ for j := range data {
+ if i == j {
+ continue
+ }
+
+ ok, err := Verify(data[j], proof, root)
+ if err != nil {
+ t.Errorf("leaf %d with proof %d: Verify() unexpected error = %v",
+ j, i, err)
+ continue
+ }
+ if ok {
+ t.Errorf("leaf %d: Verify() returned true for proof for leaf %d", j, i)
+ }
+ }
+ }
+ })
+ }
+}
+
+// TestNew_InvalidInput ensures that the Merkle tree constructor
+// rejects empty or malformed input data according to protocol rules.
+func TestNew_InvalidInput(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ data [][]byte
+ }{
+ {
+ name: "nil input",
+ data: nil,
+ },
+ {
+ name: "empty input",
+ data: [][]byte{},
+ },
+ {
+ name: "contains nil leaf",
+ data: [][]byte{
+ []byte("a"),
+ nil,
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ _, err := New(tt.data)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ })
+ }
+}
+
+// TestNew_RootHash manually calculates the expected root hash for
+// small tree sizes to verify the structural correctness of the tree
+// building algorithm.
+func TestNew_RootHash(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ data [][]byte
+ want func([][]byte) crypto.Hash
+ }{
+ {
+ name: "single leaf",
+ data: [][]byte{
+ []byte("hello"),
+ },
+ want: func(data [][]byte) crypto.Hash {
+ return hashLeaf(data[0])
+ },
+ },
+ {
+ name: "two leaves",
+ data: [][]byte{
+ []byte("certichain"),
+ []byte("testing"),
+ },
+ want: func(data [][]byte) crypto.Hash {
+ left := hashLeaf(data[0])
+ right := hashLeaf(data[1])
+
+ return hashNode(left, right)
+ },
+ },
+ {
+ name: "odd leaf count (RFC 6962 promotion)",
+ data: [][]byte{
+ []byte("a"),
+ []byte("b"),
+ []byte("c"),
+ },
+ want: func(data [][]byte) crypto.Hash {
+ a := hashLeaf(data[0])
+ b := hashLeaf(data[1])
+ c := hashLeaf(data[2])
+
+ // RFC 6962 split: k = 2 (largest power of 2 < 3)
+ // Root = hashNode(hashNode(a, b), c)
+ left := hashNode(a, b)
+
+ return hashNode(left, c)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ tree, err := New(tt.data)
+ if err != nil {
+ t.Fatalf("New() error: %v", err)
+ }
+
+ want := tt.want(tt.data)
+ got := tree.root.hash
+
+ if got != want {
+ t.Fatalf(
+ "unexpected root hash: \ngot: %x\nwant: %x",
+ got,
+ want,
+ )
+ }
+ })
+ }
+}
+
+// FuzzVerify exercises the Verify function with arbitrary leaf data and roots
+// to ensure it is robust against crashes and correctly handles malformed inputs.
+func FuzzVerify(f *testing.F) {
+ // Seed corpus with a valid setup to give the fuzzer a starting point.
+ data := [][]byte{[]byte("fuzz1"), []byte("fuzz2")}
+ tree, _ := New(data)
+ root := tree.Root()
+ proof, _ := tree.GenerateProof(0)
+
+ f.Add([]byte("fuzz1"), root)
+ f.Add([]byte("garbage"), make([]byte, 32))
+
+ f.Fuzz(func(t *testing.T, leafData []byte, root []byte) {
+ ok, err := Verify(leafData, proof, root)
+
+ // If input data is valid (32 byte root), and it's the exact
+ // data we used to seed, then it must verify.
+ if bytes.Equal(leafData, []byte("fuzz1")) && bytes.Equal(root, tree.Root()) {
+ if !ok || err != nil {
+ t.Errorf("Failed to verify seed data: ok=%v, err=%v", ok, err)
+ }
+ }
+
+ // Basic sanity: if root is wrong size, it must return an error.
+ if len(root) != crypto.HashSize {
+ if err == nil {
+ t.Error("Verify accepted a root with invalid size")
+ }
+ }
+ })
+}
diff --git a/internal/merkle/proof_test.go b/internal/merkle/proof_test.go
@@ -0,0 +1,157 @@
+// 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 (
+ "fmt"
+ "strconv"
+ "testing"
+
+ "certichain/internal/crypto"
+)
+
+// TestGenerateProof_InvalidIndex checks the out of bound
+// indexes.
+func TestGenerateProof_InvalidIndex(t *testing.T) {
+ t.Parallel()
+
+ data := makeLeaves(3)
+ tree := mustTree(t, data)
+
+ tests := []struct {
+ name string
+ index int
+ }{
+ {"negative index", -1},
+ {"out of index", 3},
+ {"equal to length", len(data)},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ _, err := tree.GenerateProof(tt.index)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ })
+ }
+}
+
+func TestGenerateProof_ValidateIndex(t *testing.T) {
+ t.Parallel()
+
+ data := makeLeaves(3)
+ tree := mustTree(t, data)
+
+ for i := range data {
+ t.Run(fmt.Sprintf("leaf-%d", i), func(t *testing.T) {
+ t.Parallel()
+
+ proof := mustProof(t, tree, i)
+
+ if proof == nil {
+ t.Fatal("proof is nil")
+ }
+
+ ok, err := Verify(data[i], proof, tree.Root())
+ if err != nil {
+ t.Fatalf("Verify() error = %v", err)
+ }
+
+ if !ok {
+ t.Fatal("proof verification failed")
+ }
+
+ if proof.Index != i {
+ t.Fatalf(
+ "wrong proof index: got %d want %d",
+ proof.Index,
+ i,
+ )
+ }
+ })
+ }
+}
+
+// TestVerify_InvalidInput checks that Verify rejects all type
+// of malformed input.
+func TestVerify_InvalidInput(t *testing.T) {
+ t.Parallel()
+
+ tree := mustTree(t, makeLeaves(4))
+ validleaf := []byte(strconv.Itoa(0))
+ validProof := mustProof(t, tree, 0)
+ validRoot := tree.Root()
+
+ tests := []struct {
+ name string
+ leafData []byte
+ proof *Proof
+ root []byte
+ }{
+ {
+ name: "nil leaf data",
+ leafData: nil,
+ proof: validProof,
+ root: validRoot,
+ },
+ {
+ name: "nil proof",
+ leafData: validleaf,
+ proof: nil,
+ root: validRoot,
+ },
+ {
+ name: "nil root",
+ leafData: validleaf,
+ proof: validProof,
+ root: nil,
+ },
+ {
+ name: "empty root",
+ leafData: validleaf,
+ proof: validProof,
+ root: []byte{},
+ },
+ {
+ name: "invalid root size (long)",
+ leafData: validleaf,
+ proof: validProof,
+ root: make([]byte, crypto.HashSize+1),
+ },
+ {
+ name: "invalid root size (short)",
+ leafData: validleaf,
+ proof: validProof,
+ root: make([]byte, crypto.HashSize-1),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ ok, err := Verify(tt.leafData, tt.proof, tt.root)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ if ok {
+ t.Fatal("expected false, for true")
+ }
+ })
+ }
+}
diff --git a/internal/merkle/tree_test.go b/internal/merkle/tree_test.go
@@ -0,0 +1,65 @@
+// 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"
+ "strconv"
+ "testing"
+)
+
+func TestTree_RootReturnCopy(t *testing.T) {
+ t.Parallel()
+
+ data := [][]byte{
+ []byte("certichain"),
+ }
+
+ tree := mustTree(t, data)
+
+ root1 := tree.Root()
+ root2 := tree.Root()
+
+ if !bytes.Equal(root1, root2) {
+ t.Fatal("Root() returned inconsistent root hashes")
+ }
+
+ root1[0] ^= 0xff
+
+ if bytes.Equal(root1, root2) {
+ t.Fatal("Root() did not return a defensive copy")
+ }
+}
+
+func TestTree_LeafCount(t *testing.T) {
+ t.Parallel()
+
+ const leafCount = 10_000
+
+ data := make([][]byte, leafCount)
+ for i := range data {
+ data[i] = []byte(strconv.Itoa(i))
+ }
+
+ tree := mustTree(t, data)
+
+ if got := tree.LeafCount(); got != leafCount {
+ t.Fatalf(
+ "unexpected leaf count: got = %x\nwant = %x",
+ got,
+ leafCount,
+ )
+ }
+}