certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

merkle_test.go (5399B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package merkle
     16 
     17 import (
     18 	"bytes"
     19 	"strconv"
     20 	"testing"
     21 
     22 	"certichain/internal/crypto"
     23 )
     24 
     25 // TestVerify_RoundTrip verifies that every leaf in a constructed tree
     26 // can be proven to exist (positive cases) and that proofs for one leaf
     27 // are not accepted for another (negative cases).
     28 //
     29 // It tests multiple tree sizes to ensure the RFC 6962 split rule
     30 // is correctly implemented across various tree topologies.
     31 func TestVerify_RoundTrip(t *testing.T) {
     32 	t.Parallel()
     33 
     34 	// sizes covers edge cases: 1 (root is leaf), 2 (perfect balance),
     35 	// 3 (odd promotion), and non-power-of-2 large counts.
     36 	sizes := []int{1, 2, 3, 7, 8, 9, 16, 100}
     37 
     38 	for _, n := range sizes {
     39 		t.Run("n="+strconv.Itoa(n), func(t *testing.T) {
     40 			t.Parallel()
     41 
     42 			data := makeLeaves(n)
     43 			tree := mustTree(t, data)
     44 			root := tree.Root()
     45 
     46 			for i := range data {
     47 				proof := mustProof(t, tree, i)
     48 
     49 				// 1. Positive Verification: Verify the correct leaf matches the proof.
     50 				ok, err := Verify(data[i], proof, root)
     51 				if err != nil {
     52 					t.Errorf("leaf %d: Verify() unexpected error = %v", i, err)
     53 					continue
     54 				}
     55 				if !ok {
     56 					t.Errorf("leaf %d: Verify() returned false for valid proof", i)
     57 				}
     58 
     59 				// 2. Negative Verification: Ensure other leaves are rejected by this proof.
     60 				for j := range data {
     61 					if i == j {
     62 						continue
     63 					}
     64 
     65 					ok, err := Verify(data[j], proof, root)
     66 					if err != nil {
     67 						t.Errorf("leaf %d with proof %d: Verify() unexpected error = %v",
     68 							j, i, err)
     69 						continue
     70 					}
     71 					if ok {
     72 						t.Errorf("leaf %d: Verify() returned true for proof for leaf %d", j, i)
     73 					}
     74 				}
     75 			}
     76 		})
     77 	}
     78 }
     79 
     80 // TestNew_InvalidInput ensures that the Merkle tree constructor
     81 // rejects empty or malformed input data according to protocol rules.
     82 func TestNew_InvalidInput(t *testing.T) {
     83 	t.Parallel()
     84 
     85 	tests := []struct {
     86 		name string
     87 		data [][]byte
     88 	}{
     89 		{
     90 			name: "nil input",
     91 			data: nil,
     92 		},
     93 		{
     94 			name: "empty input",
     95 			data: [][]byte{},
     96 		},
     97 		{
     98 			name: "contains nil leaf",
     99 			data: [][]byte{
    100 				[]byte("a"),
    101 				nil,
    102 			},
    103 		},
    104 	}
    105 
    106 	for _, tt := range tests {
    107 		t.Run(tt.name, func(t *testing.T) {
    108 			t.Parallel()
    109 
    110 			_, err := New(tt.data)
    111 			if err == nil {
    112 				t.Fatal("expected error, got nil")
    113 			}
    114 		})
    115 	}
    116 }
    117 
    118 // TestNew_RootHash manually calculates the expected root hash for
    119 // small tree sizes to verify the structural correctness of the tree
    120 // building algorithm.
    121 func TestNew_RootHash(t *testing.T) {
    122 	t.Parallel()
    123 
    124 	tests := []struct {
    125 		name string
    126 		data [][]byte
    127 		want func([][]byte) crypto.Hash
    128 	}{
    129 		{
    130 			name: "single leaf",
    131 			data: [][]byte{
    132 				[]byte("hello"),
    133 			},
    134 			want: func(data [][]byte) crypto.Hash {
    135 				return hashLeaf(data[0])
    136 			},
    137 		},
    138 		{
    139 			name: "two leaves",
    140 			data: [][]byte{
    141 				[]byte("certichain"),
    142 				[]byte("testing"),
    143 			},
    144 			want: func(data [][]byte) crypto.Hash {
    145 				left := hashLeaf(data[0])
    146 				right := hashLeaf(data[1])
    147 
    148 				return hashNode(left, right)
    149 			},
    150 		},
    151 		{
    152 			name: "odd leaf count (RFC 6962 promotion)",
    153 			data: [][]byte{
    154 				[]byte("a"),
    155 				[]byte("b"),
    156 				[]byte("c"),
    157 			},
    158 			want: func(data [][]byte) crypto.Hash {
    159 				a := hashLeaf(data[0])
    160 				b := hashLeaf(data[1])
    161 				c := hashLeaf(data[2])
    162 
    163 				// RFC 6962 split: k = 2 (largest power of 2 < 3)
    164 				// Root = hashNode(hashNode(a, b), c)
    165 				left := hashNode(a, b)
    166 
    167 				return hashNode(left, c)
    168 			},
    169 		},
    170 	}
    171 
    172 	for _, tt := range tests {
    173 		t.Run(tt.name, func(t *testing.T) {
    174 			t.Parallel()
    175 
    176 			tree, err := New(tt.data)
    177 			if err != nil {
    178 				t.Fatalf("New() error: %v", err)
    179 			}
    180 
    181 			want := tt.want(tt.data)
    182 			got := tree.root.hash
    183 
    184 			if got != want {
    185 				t.Fatalf(
    186 					"unexpected root hash: \ngot: %x\nwant: %x",
    187 					got,
    188 					want,
    189 				)
    190 			}
    191 		})
    192 	}
    193 }
    194 
    195 // FuzzVerify exercises the Verify function with arbitrary leaf data and roots
    196 // to ensure it is robust against crashes and correctly handles malformed inputs.
    197 func FuzzVerify(f *testing.F) {
    198 	// Seed corpus with a valid setup to give the fuzzer a starting point.
    199 	data := [][]byte{[]byte("fuzz1"), []byte("fuzz2")}
    200 	tree, _ := New(data)
    201 	root := tree.Root()
    202 	proof, _ := tree.GenerateProof(0)
    203 
    204 	f.Add([]byte("fuzz1"), root)
    205 	f.Add([]byte("garbage"), make([]byte, 32))
    206 
    207 	f.Fuzz(func(t *testing.T, leafData []byte, root []byte) {
    208 		ok, err := Verify(leafData, proof, root)
    209 
    210 		// If input data is valid (32 byte root), and it's the exact
    211 		// data we used to seed, then it must verify.
    212 		if bytes.Equal(leafData, []byte("fuzz1")) && bytes.Equal(root, tree.Root()) {
    213 			if !ok || err != nil {
    214 				t.Errorf("Failed to verify seed data: ok=%v, err=%v", ok, err)
    215 			}
    216 		}
    217 
    218 		// Basic sanity: if root is wrong size, it must return an error.
    219 		if len(root) != crypto.HashSize {
    220 			if err == nil {
    221 				t.Error("Verify accepted a root with invalid size")
    222 			}
    223 		}
    224 	})
    225 }