-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmerkle_test.go
86 lines (75 loc) · 1.89 KB
/
merkle_test.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package database
import (
"log"
"testing"
"github.com/si-co/vpir-code/lib/merkle"
"github.com/si-co/vpir-code/lib/utils"
"github.com/stretchr/testify/require"
)
func BenchmarkMerkleTree(b *testing.B) {
rng := utils.RandomPRG()
dbLen := 100000
numRows := 1
blockLen := 160
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
CreateRandomMerkle(rng, dbLen, numRows, blockLen)
}
}
func TestMerkleTree(t *testing.T) {
rng := utils.RandomPRG()
dbLen := 100000
numRows := 1
blockLen := 160
entries := make([][]byte, numRows)
numBlocks := dbLen / (8 * blockLen)
// generate random blocks
blocks := make([][]byte, numBlocks)
for i := range blocks {
// generate random block
b := make([]byte, blockLen)
if _, err := rng.Read(b); err != nil {
log.Fatal(err)
}
blocks[i] = b
}
// generate tree
tree, err := merkle.New(blocks)
if err != nil {
log.Fatalf("impossible to create Merkle tree: %v", err)
}
root := tree.Root()
// generate db
blocksPerRow := numBlocks / numRows
proofLen := 0
b := 0
for i := range entries {
e := make([]byte, 0)
for j := 0; j < blocksPerRow; j++ {
p, err := tree.GenerateProof(blocks[b])
require.NoError(t, err)
encodedProof := merkle.EncodeProof(p)
e = append(e, append(blocks[b], encodedProof...)...)
proofLen = len(encodedProof) // always same length
// first verification here
verified, err := merkle.VerifyProof(blocks[b], p, root)
require.NoError(t, err)
require.True(t, verified)
b++
}
entries[i] = e
}
// verify db
for i := range entries {
for j := 0; j < blocksPerRow-1; j++ {
entireBlock := entries[i][j*(blockLen+proofLen) : (j+1)*(blockLen+proofLen)]
data := entireBlock[:blockLen]
encodedProof := entireBlock[blockLen:]
proof := merkle.DecodeProof(encodedProof)
verified, err := merkle.VerifyProof(data, proof, root)
require.NoError(t, err)
require.True(t, verified)
}
}
}