aboutsummaryrefslogtreecommitdiff
path: root/internal/merkle/tree_test.go
blob: b2546a8493e7d63ddcfa67cd17aa211c9c5bd8cb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package merkle

import (
	"encoding/hex"
	"fmt"
	"testing"
)

func TestRootAndProof(t *testing.T) {
	inputs := [][]byte{HashLeaf([]byte("a")), HashLeaf([]byte("b")), HashLeaf([]byte("c"))}
	root := Root(inputs)

	if len(root) == 0 {
		t.Fatalf("expected root")
	}

	for i := range inputs {
		proof := BuildProof(inputs, i)

		if !VerifyProof(inputs[i], proof, root) {
			t.Fatalf("proof verification failed for index %d", i)
		}
	}
}

func TestRootEmpty(t *testing.T) {
	r := Root(nil)

	if got := hex.EncodeToString(r); got != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
		t.Fatalf("unexpected empty root: %s", got)
	}
}

func TestAccumulatorRootMatchesRoot(t *testing.T) {
	for n := 1; n <= 128; n++ {
		leaves := make([][]byte, 0, n)
		acc := NewAccumulator()

		for i := 0; i < n; i++ {
			leaf := HashLeaf([]byte(fmt.Sprintf("leaf-%d", i)))
			leaves = append(leaves, leaf)

			acc.AddLeafHash(leaf)
		}

		want := hex.EncodeToString(Root(leaves))
		got := hex.EncodeToString(acc.RootDuplicateLast())

		if got != want {
			t.Fatalf("root mismatch n=%d got=%s want=%s", n, got, want)
		}
	}
}