certichain

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

helper_test.go (1946B)


      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 // mustTree is a test helper function that creates a
     26 // RFC 6962 Merkle tree.
     27 func mustTree(t *testing.T, data [][]byte) *Tree {
     28 	t.Helper()
     29 
     30 	tree, err := New(data)
     31 	if err != nil {
     32 		t.Fatalf("New() error = %v", err)
     33 	}
     34 
     35 	return tree
     36 }
     37 
     38 // mustProof generates an inclusion proof for leaf index.
     39 func mustProof(t *testing.T, tree *Tree, leafIndex int) *Proof {
     40 	t.Helper()
     41 
     42 	proof, err := tree.GenerateProof(leafIndex)
     43 	if err != nil {
     44 		t.Fatalf("GenerateProof(%d) error = %v", leafIndex, err)
     45 	}
     46 
     47 	return proof
     48 }
     49 
     50 // makeLeaves generates n deterministic, unique leaf byte slice.
     51 func makeLeaves(n int) [][]byte {
     52 	out := make([][]byte, n)
     53 
     54 	for i := range out {
     55 		out[i] = []byte(strconv.Itoa(i))
     56 	}
     57 
     58 	return out
     59 }
     60 
     61 // flipBytes returns a copy of the data with the byte at the pos
     62 // XOR-flipped.
     63 func flipBytes(data []byte, pos int) []byte {
     64 	out := bytes.Clone(data)
     65 	out[pos] ^= 0xff
     66 
     67 	return out
     68 }
     69 
     70 // flipHashByte returns a copy of the hash (h) with the byte at
     71 // the pos XOR-flipped.
     72 func flipHashByte(h crypto.Hash, pos int) crypto.Hash {
     73 	h[pos] ^= 0xff
     74 	return h
     75 }
     76 
     77 // cloneSteps returns a deep copy of a ProofStep slice.
     78 func cloneSteps(steps []ProofStep) []ProofStep {
     79 	out := make([]ProofStep, len(steps))
     80 	copy(out, steps)
     81 
     82 	return out
     83 }