Debian Codegraph @

tree_test.go

raw symbols SCIP
1 package merkletree
2
3 import (
4 "bytes"
5 "crypto/rand"
6 "crypto/sha256"
7 "math/big"
8 "strconv"
9 "testing"
10
11 "github.com/NebulousLabs/errors"
12 "github.com/NebulousLabs/fastrand"
13 )
14
15 // A MerkleTester contains data types that can be filled out manually to
16 // compare against function results.
17 type MerkleTester struct {
18 // data is the raw data of the Merkle tree.
19 data [][]byte
20
21 // leaves is the hashes of the data, and should be the same length.
22 leaves [][]byte
23
24 // roots contains the root hashes of Merkle trees of various heights using
25 // the data for input.
26 roots map[int][]byte
27
28 // proofSets contains proofs that certain data is in a Merkle tree. The
29 // first map is the number of leaves in the tree that the proof is for. The
30 // root of that tree can be found in roots. The second map is the
31 // proofIndex that was used when building the proof.
32 proofSets map[int]map[int][][]byte
33 *testing.T
34 }
35
36 // join returns the sha256 hash of 0x01 || a || b.
37 func (mt *MerkleTester) join(a, b []byte) []byte {
38 return sum(sha256.New(), append(append([]byte{1}, a...), b...))
39 }
40
41 // CreateMerkleTester creates a Merkle tester and manually fills out many of
42 // the expected values for constructing Merkle tree roots and Merkle tree
43 // proofs. These manual values can then be compared against the values that the
44 // Tree creates.
45 func CreateMerkleTester(t *testing.T) (mt *MerkleTester) {
46 mt = &MerkleTester{
47 roots: make(map[int][]byte),
48 proofSets: make(map[int]map[int][][]byte),
49 }
50 mt.T = t
51
52 // Fill out the data and leaves values.
53 size := 16
54 for i := 0; i < size; i++ {
55 mt.data = append(mt.data, []byte{byte(i)})
56 }
57 for i := 0; i < size; i++ {
58 mt.leaves = append(mt.leaves, sum(sha256.New(), append([]byte{0}, mt.data[i]...)))
59 }
60
61 // Manually build out expected Merkle root values.
62 mt.roots[0] = nil
63 mt.roots[1] = mt.leaves[0]
64 mt.roots[2] = mt.join(mt.leaves[0], mt.leaves[1])
65 mt.roots[3] = mt.join(
66 mt.roots[2],
67 mt.leaves[2],
68 )
69 mt.roots[4] = mt.join(
70 mt.roots[2],
71 mt.join(mt.leaves[2], mt.leaves[3]),
72 )
73 mt.roots[5] = mt.join(
74 mt.roots[4],
75 mt.leaves[4],
76 )
77
78 mt.roots[6] = mt.join(
79 mt.roots[4],
80 mt.join(
81 mt.leaves[4],
82 mt.leaves[5],
83 ),
84 )
85
86 mt.roots[7] = mt.join(
87 mt.roots[4],
88 mt.join(
89 mt.join(mt.leaves[4], mt.leaves[5]),
90 mt.leaves[6],
91 ),
92 )
93
94 mt.roots[8] = mt.join(
95 mt.roots[4],
96 mt.join(
97 mt.join(mt.leaves[4], mt.leaves[5]),
98 mt.join(mt.leaves[6], mt.leaves[7]),
99 ),
100 )
101
102 mt.roots[15] = mt.join(
103 mt.roots[8],
104 mt.join(
105 mt.join(
106 mt.join(mt.leaves[8], mt.leaves[9]),
107 mt.join(mt.leaves[10], mt.leaves[11]),
108 ),
109 mt.join(
110 mt.join(mt.leaves[12], mt.leaves[13]),
111 mt.leaves[14],
112 ),
113 ),
114 )
115
116 // Manually build out some proof sets that should should match what the
117 // Tree creates for the same values.
118 mt.proofSets[1] = make(map[int][][]byte)
119 mt.proofSets[1][0] = [][]byte{mt.data[0]}
120
121 mt.proofSets[2] = make(map[int][][]byte)
122 mt.proofSets[2][0] = [][]byte{
123 mt.data[0],
124 mt.leaves[1],
125 }
126
127 mt.proofSets[2][1] = [][]byte{
128 mt.data[1],
129 mt.leaves[0],
130 }
131
132 mt.proofSets[5] = make(map[int][][]byte)
133 mt.proofSets[5][4] = [][]byte{
134 mt.data[4],
135 mt.roots[4],
136 }
137
138 mt.proofSets[6] = make(map[int][][]byte)
139 mt.proofSets[6][0] = [][]byte{
140 mt.data[0],
141 mt.leaves[1],
142 mt.join(
143 mt.leaves[2],
144 mt.leaves[3],
145 ),
146 mt.join(
147 mt.leaves[4],
148 mt.leaves[5],
149 ),
150 }
151
152 mt.proofSets[6][2] = [][]byte{
153 mt.data[2],
154 mt.leaves[3],
155 mt.roots[2],
156 mt.join(
157 mt.leaves[4],
158 mt.leaves[5],
159 ),
160 }
161
162 mt.proofSets[6][4] = [][]byte{
163 mt.data[4],
164 mt.leaves[5],
165 mt.roots[4],
166 }
167
168 mt.proofSets[6][5] = [][]byte{
169 mt.data[5],
170 mt.leaves[4],
171 mt.roots[4],
172 }
173
174 mt.proofSets[7] = make(map[int][][]byte)
175 mt.proofSets[7][5] = [][]byte{
176 mt.data[5],
177 mt.leaves[4],
178 mt.leaves[6],
179 mt.roots[4],
180 }
181
182 mt.proofSets[15] = make(map[int][][]byte)
183 mt.proofSets[15][3] = [][]byte{
184 mt.data[3],
185 mt.leaves[2],
186 mt.roots[2],
187 mt.join(
188 mt.join(mt.leaves[4], mt.leaves[5]),
189 mt.join(mt.leaves[6], mt.leaves[7]),
190 ),
191 mt.join(
192 mt.join(
193 mt.join(mt.leaves[8], mt.leaves[9]),
194 mt.join(mt.leaves[10], mt.leaves[11]),
195 ),
196 mt.join(
197 mt.join(mt.leaves[12], mt.leaves[13]),
198 mt.leaves[14],
199 ),
200 ),
201 }
202
203 mt.proofSets[15][10] = [][]byte{
204 mt.data[10],
205 mt.leaves[11],
206 mt.join(
207 mt.leaves[8],
208 mt.leaves[9],
209 ),
210 mt.join(
211 mt.join(mt.leaves[12], mt.leaves[13]),
212 mt.leaves[14],
213 ),
214 mt.roots[8],
215 }
216
217 mt.proofSets[15][13] = [][]byte{
218 mt.data[13],
219 mt.leaves[12],
220 mt.leaves[14],
221 mt.join(
222 mt.join(mt.leaves[8], mt.leaves[9]),
223 mt.join(mt.leaves[10], mt.leaves[11]),
224 ),
225 mt.roots[8],
226 }
227
228 return
229 }
230
231 // TestBuildRoot checks that the root returned by Tree matches the manually
232 // created roots for all of the manually created roots.
233 func TestBuildRoot(t *testing.T) {
234 mt := CreateMerkleTester(t)
235
236 // Compare the results of calling Root against all of the manually
237 // constructed Merkle trees.
238 var tree *Tree
239 for i, root := range mt.roots {
240 // Fill out the tree.
241 tree = New(sha256.New())
242 for j := 0; j < i; j++ {
243 tree.Push(mt.data[j])
244 }
245
246 // Get the root and compare to the manually constructed root.
247 treeRoot := tree.Root()
248 if !bytes.Equal(root, treeRoot) {
249 t.Error("tree root doesn't match manual root for index", i)
250 }
251 }
252 }
253
254 // TestBuildAndVerifyProof builds a proof using a tree for every single
255 // manually created proof in the MerkleTester. Then it checks that the proof
256 // matches the manually created proof, and that the proof is verified by
257 // VerifyProof. Then it checks that the proof fails for all other indices,
258 // which should happen if all of the leaves are unique.
259 func TestBuildAndVerifyProof(t *testing.T) {
260 mt := CreateMerkleTester(t)
261
262 // Compare the results of building a Merkle proof to all of the manually
263 // constructed proofs.
264 tree := New(sha256.New())
265 for i, manualProveSets := range mt.proofSets {
266 for j, expectedProveSet := range manualProveSets {
267 // Build out the tree.
268 tree = New(sha256.New())
269 err := tree.SetIndex(uint64(j))
270 if err != nil {
271 t.Fatal(err)
272 }
273 for k := 0; k < i; k++ {
274 tree.Push(mt.data[k])
275 }
276
277 // Get the proof and check all values.
278 merkleRoot, proofSet, proofIndex, numSegments := tree.Prove()
279 if !bytes.Equal(merkleRoot, mt.roots[i]) {
280 t.Error("incorrect Merkle root returned by Tree for indices", i, j)
281 }
282 if len(proofSet) != len(expectedProveSet) {
283 t.Error("proof set is wrong length for indices", i, j)
284 continue
285 }
286 if proofIndex != uint64(j) {
287 t.Error("incorrect proofIndex returned for indices", i, j)
288 }
289 if numSegments != uint64(i) {
290 t.Error("incorrect numSegments returned for indices", i, j)
291 }
292 for k := range proofSet {
293 if !bytes.Equal(proofSet[k], expectedProveSet[k]) {
294 t.Error("proof set does not match expected proof set for indices", i, j, k)
295 }
296 }
297
298 // Check that verification works on for the desired proof index but
299 // fails for all other indices.
300 if !VerifyProof(sha256.New(), merkleRoot, proofSet, proofIndex, numSegments) {
301 t.Error("proof set does not verify for indices", i, j)
302 }
303 for k := uint64(0); k < uint64(i); k++ {
304 if k == proofIndex {
305 continue
306 }
307 if VerifyProof(sha256.New(), merkleRoot, proofSet, k, numSegments) {
308 t.Error("proof set verifies for wrong index at indices", i, j, k)
309 }
310 }
311
312 // Check that calling Prove a second time results in the same
313 // values.
314 merkleRoot2, proofSet2, proofIndex2, numSegments2 := tree.Prove()
315 if !bytes.Equal(merkleRoot, merkleRoot2) {
316 t.Error("tree returned different merkle roots after calling Prove twice for indices", i, j)
317 }
318 if len(proofSet) != len(proofSet2) {
319 t.Error("tree returned different proof sets after calling Prove twice for indices", i, j)
320 }
321 for k := range proofSet {
322 if !bytes.Equal(proofSet[k], proofSet2[k]) {
323 t.Error("tree returned different proof sets after calling Prove twice for indices", i, j)
324 }
325 }
326 if proofIndex != proofIndex2 {
327 t.Error("tree returned different proof indexes after calling Prove twice for indices", i, j)
328 }
329 if numSegments != numSegments2 {
330 t.Error("tree returned different segment count after calling Prove twice for indices", i, j)
331 }
332 }
333 }
334 }
335
336 // TestBadInputs provides malicious inputs to the functions of the package,
337 // trying to trigger panics or unexpected behavior.
338 func TestBadInputs(t *testing.T) {
339 // Get the root and proof of an empty tree.
340 tree := New(sha256.New())
341 if err := tree.SetIndex(0); err != nil {
342 t.Fatal(err)
343 }
344 root := tree.Root()
345 if root != nil {
346 t.Error("root of empty tree should be nil")
347 }
348 _, proof, _, _ := tree.Prove()
349 if proof != nil {
350 t.Error("proof of empty tree should be nil")
351 }
352
353 // Get the proof of a tree that hasn't reached it's index.
354 err := tree.SetIndex(3)
355 if err != nil {
356 t.Fatal(err)
357 }
358 tree.Push([]byte{1})
359 _, proof, _, _ = tree.Prove()
360 if proof != nil {
361 t.Fatal(err)
362 }
363 err = tree.SetIndex(2)
364 if err == nil {
365 t.Error("expecting error, shouldn't be able to reset a tree after pushing")
366 }
367
368 // Try nil values in VerifyProof.
369 mt := CreateMerkleTester(t)
370 if VerifyProof(sha256.New(), nil, mt.proofSets[1][0], 0, 1) {
371 t.Error("VerifyProof should return false for nil merkle root")
372 }
373 if VerifyProof(sha256.New(), []byte{1}, nil, 0, 1) {
374 t.Error("VerifyProof should return false for nil proof set")
375 }
376 if VerifyProof(sha256.New(), mt.roots[15], mt.proofSets[15][3][1:], 3, 15) {
377 t.Error("VerifyProof should return false for too-short proof set")
378 }
379 if VerifyProof(sha256.New(), mt.roots[15], mt.proofSets[15][10][1:], 10, 15) {
380 t.Error("VerifyProof should return false for too-short proof set")
381 }
382 if VerifyProof(sha256.New(), mt.roots[15], mt.proofSets[15][10], 15, 0) {
383 t.Error("VerifyProof should return false when numLeaves is 0")
384 }
385 }
386
387 // TestCompatibility runs BuildProof for a large set of trees, and checks that
388 // verify affirms each proof, while rejecting for all other indexes (this
389 // second half requires that all input data be unique). The test checks that
390 // build and verify are internally consistent, but doesn't check for actual
391 // correctness.
392 func TestCompatibility(t *testing.T) {
393 if testing.Short() {
394 t.SkipNow()
395 }
396
397 // Brute force all trees up to size 'max'. Running time for this test is max^3.
398 max := uint64(129)
399 tree := New(sha256.New())
400 for i := uint64(1); i < max; i++ {
401 // Try with proof at every possible index.
402 for j := uint64(0); j < i; j++ {
403 // Push unique data into the tree.
404 tree = New(sha256.New())
405 err := tree.SetIndex(j)
406 if err != nil {
407 t.Fatal(err)
408 }
409 for k := uint64(0); k < i; k++ {
410 tree.Push([]byte{byte(k)})
411 }
412
413 // Build the proof for the tree and run it through verify.
414 merkleRoot, proofSet, proofIndex, numLeaves := tree.Prove()
415 if !VerifyProof(sha256.New(), merkleRoot, proofSet, proofIndex, numLeaves) {
416 t.Error("proof didn't verify for indices", i, j)
417 }
418
419 // Check that verification fails for all other indices.
420 for k := uint64(0); k < i; k++ {
421 if k == j {
422 continue
423 }
424 if VerifyProof(sha256.New(), merkleRoot, proofSet, k, numLeaves) {
425 t.Error("proof verified for indices", i, j, k)
426 }
427 }
428 }
429 }
430
431 // Check that proofs on larger trees are consistent.
432 for i := 0; i < 25; i++ {
433 // Determine a random size for the tree up to 64M elements.
434 sizeI, err := rand.Int(rand.Reader, big.NewInt(256e3))
435 if err != nil {
436 t.Fatal(err)
437 }
438 size := uint64(sizeI.Int64())
439
440 proofIndexI, err := rand.Int(rand.Reader, sizeI)
441 if err != nil {
442 t.Fatal(err)
443 }
444 proofIndex := uint64(proofIndexI.Int64())
445
446 // Prepare the tree.
447 tree = New(sha256.New())
448 err = tree.SetIndex(proofIndex)
449 if err != nil {
450 t.Fatal(err)
451 }
452
453 // Insert 'size' unique elements.
454 for j := 0; j < int(size); j++ {
455 elem := []byte(strconv.Itoa(j))
456 tree.Push(elem)
457 }
458
459 // Get the proof for the tree and run it through verify.
460 merkleRoot, proofSet, proofIndex, numLeaves := tree.Prove()
461 if !VerifyProof(sha256.New(), merkleRoot, proofSet, proofIndex, numLeaves) {
462 t.Error("proof didn't verify in long test", size, proofIndex)
463 }
464 }
465 }
466
467 // TestLeafCounts checks that the number of leaves in the tree are being
468 // reported correctly.
469 func TestLeafCounts(t *testing.T) {
470 tree := New(sha256.New())
471 err := tree.SetIndex(0)
472 if err != nil {
473 t.Fatal(err)
474 }
475 _, _, _, leaves := tree.Prove()
476 if leaves != 0 {
477 t.Error("bad reporting of leaf count")
478 }
479
480 tree = New(sha256.New())
481 err = tree.SetIndex(0)
482 if err != nil {
483 t.Fatal(err)
484 }
485 tree.Push([]byte{})
486 _, _, _, leaves = tree.Prove()
487 if leaves != 1 {
488 t.Error("bad reporting on leaf count")
489 }
490 }
491
492 // TestPushSubTreeCorrectRoot creates data for 4 leaves, combines them in
493 // different ways and makes sure that the root is always the same.
494 func TestPushSubTreeCorrectRoot(t *testing.T) {
495 hash := sha256.New()
496
497 // Create the data for 4 leaves.
498 leaf1Data := fastrand.Bytes(64)
499 leaf2Data := fastrand.Bytes(64)
500 leaf3Data := fastrand.Bytes(64)
501 leaf4Data := fastrand.Bytes(64)
502
503 // Push the leaves into a tree and get the root.
504 tree := New(hash)
505 tree.Push(leaf1Data)
506 tree.Push(leaf2Data)
507 tree.Push(leaf3Data)
508 tree.Push(leaf4Data)
509 expectedRoot := tree.Root()
510
511 // Create 4 height 0 subtrees and combine them. The root should be the
512 // same.
513 tree2 := New(hash)
514 leaf1Hash := leafSum(hash, leaf1Data)
515 leaf2Hash := leafSum(hash, leaf2Data)
516 leaf3Hash := leafSum(hash, leaf3Data)
517 leaf4Hash := leafSum(hash, leaf4Data)
518 err1 := tree2.PushSubTree(0, leaf1Hash)
519 err2 := tree2.PushSubTree(0, leaf2Hash)
520 err3 := tree2.PushSubTree(0, leaf3Hash)
521 err4 := tree2.PushSubTree(0, leaf4Hash)
522 if err := errors.Compose(err1, err2, err3, err4); err != nil {
523 t.Fatal(err)
524 }
525 if !bytes.Equal(tree2.Root(), expectedRoot) {
526 t.Fatal("root doesn't match expected root")
527 }
528
529 // Create 2 height 1 subtrees and combine them. The root should be the
530 // same.
531 tree3 := New(hash)
532 node12Hash := nodeSum(hash, leaf1Hash, leaf2Hash)
533 node34Hash := nodeSum(hash, leaf3Hash, leaf4Hash)
534 err1 = tree3.PushSubTree(1, node12Hash)
535 err2 = tree3.PushSubTree(1, node34Hash)
536 if err := errors.Compose(err1, err2); err != nil {
537 t.Fatal(err)
538 }
539 if !bytes.Equal(tree3.Root(), expectedRoot) {
540 t.Fatal("root doesn't match expected root")
541 }
542
543 // Create 1 height 2 subtree and add it to the tree. The root should be the
544 // same.
545 tree4 := New(hash)
546 node1234Hash := nodeSum(hash, node12Hash, node34Hash)
547 if err := tree4.PushSubTree(2, node1234Hash); err != nil {
548 t.Fatal(err)
549 }
550 if !bytes.Equal(tree4.Root(), expectedRoot) {
551 t.Fatal("root doesn't match expected root")
552 }
553
554 // Create 1 height 1 tree and add 2 height 0 trees. The root should be the
555 // same.
556 tree5 := New(hash)
557 err1 = tree5.PushSubTree(1, node12Hash)
558 err2 = tree5.PushSubTree(0, leaf3Hash)
559 err3 = tree5.PushSubTree(0, leaf4Hash)
560 if err := errors.Compose(err1, err2, err3); err != nil {
561 t.Fatal(err)
562 }
563 if !bytes.Equal(tree5.Root(), expectedRoot) {
564 t.Fatal("root doesn't match expected root")
565 }
566
567 // Create 1 height 1 tree and add 2 leaves. The root should be the same.
568 tree6 := New(hash)
569 if err := tree6.PushSubTree(1, node12Hash); err != nil {
570 t.Fatal(err)
571 }
572 tree6.Push(leaf3Data)
573 tree6.Push(leaf4Data)
574 if !bytes.Equal(tree6.Root(), expectedRoot) {
575 t.Fatal("root doesn't match expected root")
576 }
577
578 // Create 2 height 0 trees and add 1 height 1 tree. The root should be the
579 // same.
580 tree7 := New(hash)
581 err1 = tree7.PushSubTree(0, leaf1Hash)
582 err2 = tree7.PushSubTree(0, leaf2Hash)
583 err3 = tree7.PushSubTree(1, node34Hash)
584 if err := errors.Compose(err1, err2, err3); err != nil {
585 t.Fatal(err)
586 }
587 if !bytes.Equal(tree7.Root(), expectedRoot) {
588 t.Fatal("root doesn't match expected root")
589 }
590
591 // Create 2 leaves and add 1 height 1 tree. The root should be the same.
592 tree8 := New(hash)
593 tree8.Push(leaf1Data)
594 tree8.Push(leaf2Data)
595 if err := tree8.PushSubTree(1, node34Hash); err != nil {
596 t.Fatal(err)
597 }
598 if !bytes.Equal(tree8.Root(), expectedRoot) {
599 t.Fatal("root doesn't match expected root")
600 }
601 }
602
603 // TestPushSubTreeCorrectRootWithProof creates data for 4 leaves, combines them
604 // in different ways and makes sure that the root is always the same. It also
605 // creates a proof for them.
606 func TestPushSubTreeCorrectRootWithProof(t *testing.T) {
607 hash := sha256.New()
608
609 // Create the data for 4 leaves.
610 leaf1Data := fastrand.Bytes(64)
611 leaf2Data := fastrand.Bytes(64)
612 leaf3Data := fastrand.Bytes(64)
613 leaf4Data := fastrand.Bytes(64)
614
615 // Push the leaves into a tree and get the root.
616 tree := New(hash)
617 proofIndex := uint64(fastrand.Intn(4))
618 if err := tree.SetIndex(proofIndex); err != nil {
619 t.Fatal(err)
620 }
621 tree.Push(leaf1Data)
622 tree.Push(leaf2Data)
623 tree.Push(leaf3Data)
624 tree.Push(leaf4Data)
625 expectedRoot := tree.Root()
626
627 // Create 1 height 1 tree and add 2 leaves. The root should be the same.
628 tree2 := New(hash)
629 proofIndex = uint64(2 + fastrand.Intn(2))
630 leaf1Hash := leafSum(hash, leaf1Data)
631 leaf2Hash := leafSum(hash, leaf2Data)
632 node12Hash := nodeSum(hash, leaf1Hash, leaf2Hash)
633 if err := tree2.SetIndex(proofIndex); err != nil {
634 t.Fatal(err)
635 }
636 if err := tree2.PushSubTree(1, node12Hash); err != nil {
637 t.Fatal(err)
638 }
639 tree2.Push(leaf3Data)
640 tree2.Push(leaf4Data)
641 if !bytes.Equal(tree2.Root(), expectedRoot) {
642 t.Fatal("root doesn't match expected root")
643 }
644
645 // Create 2 leaves and add 1 height 1 tree. The root should be the same.
646 tree3 := New(hash)
647 proofIndex = uint64(fastrand.Intn(2))
648 leaf3Hash := leafSum(hash, leaf3Data)
649 leaf4Hash := leafSum(hash, leaf4Data)
650 if err := tree3.SetIndex(proofIndex); err != nil {
651 t.Fatal(err)
652 }
653 node34Hash := nodeSum(hash, leaf3Hash, leaf4Hash)
654 tree3.Push(leaf1Data)
655 tree3.Push(leaf2Data)
656 if err := tree3.PushSubTree(1, node34Hash); err != nil {
657 t.Fatal(err)
658 }
659 if !bytes.Equal(tree3.Root(), expectedRoot) {
660 t.Fatal("root doesn't match expected root")
661 }
662
663 // Test the proofs for all the trees.
664 merkleRoot, proofSet, index, numLeaves := tree.Prove()
665 if !VerifyProof(sha256.New(), merkleRoot, proofSet, index, numLeaves) {
666 t.Fatal("failed to verify proof for tree")
667 }
668 merkleRoot, proofSet, index, numLeaves = tree2.Prove()
669 if !VerifyProof(sha256.New(), merkleRoot, proofSet, index, numLeaves) {
670 t.Fatal("failed to verify proof for tree2")
671 }
672 merkleRoot, proofSet, index, numLeaves = tree3.Prove()
673 if !VerifyProof(sha256.New(), merkleRoot, proofSet, index, numLeaves) {
674 t.Fatal("failed to verify proof for tree3")
675 }
676 }
677
678 // TestPushSubTreeSimple tests pushing some valid and invalid subTrees to the
679 // tree.
680 func TestPushSubTreeSimple(t *testing.T) {
681 tree := New(sha256.New())
682
683 // Add a subTree of height 5 to the empty tree.
684 if err := tree.PushSubTree(5, []byte{}); err != nil {
685 t.Fatal(err)
686 }
687 if tree.Root() == nil {
688 t.Fatal("root should not be nil after adding a subTree")
689 }
690 // Add a subTree of a height >5 to the tree. This should not be possible.
691 if err := tree.PushSubTree(6, []byte{}); err == nil {
692 t.Fatal("pushing a subTree with a larger height than the smallest subTree should fail")
693 }
694 // The current index should be 2^5
695 expectedIndex := uint64(1 << 5)
696 if tree.currentIndex != expectedIndex {
697 t.Errorf("expected index %v but was %v", expectedIndex, tree.currentIndex)
698 }
699 // Add a subTree of the same height as the smallest subTree in the merkle
700 // tree and check again.
701 if err := tree.PushSubTree(5, []byte{}); err != nil {
702 t.Fatal(err)
703 }
704 expectedIndex *= 2
705 if tree.currentIndex != expectedIndex {
706 t.Errorf("expected index %v but was %v", expectedIndex, tree.currentIndex)
707 }
708 // Push some data equal to height 2 and make sure the expectedIndex is correct.
709 for i := 0; i < 4; i++ {
710 tree.Push([]byte{})
711 expectedIndex++
712 if tree.currentIndex != expectedIndex {
713 t.Errorf("expected index %v but was %v", expectedIndex, tree.currentIndex)
714 }
715 }
716 // Add a subTree of height 2 and check the index again.
717 if err := tree.PushSubTree(2, []byte{}); err != nil {
718 t.Fatal(err)
719 }
720 expectedIndex += 4
721 if tree.currentIndex != expectedIndex {
722 t.Errorf("expected index %v but was %v", expectedIndex, tree.currentIndex)
723 }
724
725 // Create a new tree and set the proof index to 1. Afterwards we push twice
726 // to create a subTree of height 1 that contains the proof index.
727 tree2 := New(sha256.New())
728 if err := tree2.SetIndex(1); err != nil {
729 t.Fatal(err)
730 }
731 tree2.Push([]byte{})
732 tree2.Push([]byte{})
733 // Push a subTree of height 1. That should be fine.
734 if err := tree2.PushSubTree(1, []byte{}); err != nil {
735 t.Fatal(err)
736 }
737 // Create a new tree and set the proof index to 3. Afterwards we push twice
738 // to create a subTree of height 1.
739 tree3 := New(sha256.New())
740 if err := tree3.SetIndex(2); err != nil {
741 t.Fatal(err)
742 }
743 tree3.Push([]byte{})
744 tree3.Push([]byte{})
745 // Push a subTree of height 1. That shouldn't work since the subTree can't
746 // contain the piece for the proof.
747 if err := tree3.PushSubTree(1, []byte{}); err == nil {
748 t.Fatal("we shouldn't be able to push a subTree that contains the proof index")
749 }
750 // Create a new tree and set the proof index to 4. Afterwards we push twice
751 // to create a subTree of height 1.
752 tree4 := New(sha256.New())
753 if err := tree4.SetIndex(3); err != nil {
754 t.Fatal(err)
755 }
756 tree4.Push([]byte{})
757 tree4.Push([]byte{})
758 // Push a subTree of height 1. That shouldn't work since the subTree can't
759 // contain the piece for the proof.
760 if err := tree4.PushSubTree(1, []byte{}); err == nil {
761 t.Fatal("we shouldn't be able to push a subTree that contains the proof index")
762 }
763 }
764
765 // BenchmarkSha256_4MB uses sha256 to hash 4mb of data.
766 func BenchmarkSha256_4MB(b *testing.B) {
767 data := make([]byte, 4*1024*1024)
768 _, err := rand.Read(data)
769 if err != nil {
770 b.Fatal(err)
771 }
772
773 b.ResetTimer()
774 for i := 0; i < b.N; i++ {
775 sha256.Sum256(data)
776 }
777 }
778
779 // BenchmarkTree64_4MB creates a Merkle tree out of 4MB using a segment size of
780 // 64 bytes, using sha256.
781 func BenchmarkTree64_4MB(b *testing.B) {
782 data := make([]byte, 4*1024*1024)
783 _, err := rand.Read(data)
784 if err != nil {
785 b.Fatal(err)
786 }
787 segmentSize := 64
788
789 b.ResetTimer()
790 tree := New(sha256.New())
791 for i := 0; i < b.N; i++ {
792 for j := 0; j < len(data)/segmentSize; j++ {
793 tree.Push(data[j*segmentSize : (j+1)*segmentSize])
794 }
795 tree.Root()
796 }
797 }
798
799 // BenchmarkTree4k_4MB creates a Merkle tree out of 4MB using a segment size of
800 // 4096 bytes, using sha256.
801 func BenchmarkTree4k_4MB(b *testing.B) {
802 data := make([]byte, 4*1024*1024)
803 _, err := rand.Read(data)
804 if err != nil {
805 b.Fatal(err)
806 }
807 segmentSize := 4096
808
809 b.ResetTimer()
810 tree := New(sha256.New())
811 for i := 0; i < b.N; i++ {
812 for j := 0; j < len(data)/segmentSize; j++ {
813 tree.Push(data[j*segmentSize : (j+1)*segmentSize])
814 }
815 tree.Root()
816 }
817 }