| 1 |
|
| 2 |
|
| 3 |
package merkletree |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"crypto/sha256" |
| 8 |
"math" |
| 9 |
) |
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
func Fuzz(data []byte) int { |
| 14 |
|
| 15 |
if len(data) < 2 { |
| 16 |
return -1 |
| 17 |
} |
| 18 |
index := 256*uint64(data[0]) + uint64(data[1]) |
| 19 |
data = data[2:] |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
merkleRoot, proofSet, numLeaves, err := BuildReaderProof(bytes.NewReader(data), sha256.New(), 64, index) |
| 25 |
if err != nil { |
| 26 |
return 0 |
| 27 |
} |
| 28 |
if !VerifyProof(sha256.New(), merkleRoot, proofSet, index, numLeaves) { |
| 29 |
panic("verification failed!") |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
if uint64(len(data)) > 64*index { |
| 35 |
return 1 |
| 36 |
} |
| 37 |
return 0 |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
func FuzzReadSubTreesWithProof(data []byte) int { |
| 43 |
|
| 44 |
if len(data) < 3 { |
| 45 |
return -1 |
| 46 |
} |
| 47 |
index := 256*uint64(data[0]) + uint64(data[1]) |
| 48 |
data = data[2:] |
| 49 |
cachedTree, numLeaves := buildAndCompareTreesFromFuzz(data, index) |
| 50 |
|
| 51 |
|
| 52 |
merkleRoot, proofSet, _, numLeaves := cachedTree.Prove() |
| 53 |
if proofSet == nil { |
| 54 |
return 0 |
| 55 |
} |
| 56 |
if !VerifyProof(sha256.New(), merkleRoot, proofSet, index, numLeaves) { |
| 57 |
panic("verification failed!") |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
if numLeaves > index { |
| 63 |
return 1 |
| 64 |
} |
| 65 |
return 0 |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
func FuzzReadSubTreesNoProof(data []byte) int { |
| 71 |
buildAndCompareTreesFromFuzz(data, math.MaxUint64) |
| 72 |
if len(data) > 2 { |
| 73 |
return 1 |
| 74 |
} |
| 75 |
return 0 |
| 76 |
} |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
func buildAndCompareTreesFromFuzz(data []byte, proofIndex uint64) (cachedTree *Tree, numLeaves uint64) { |
| 81 |
hash := sha256.New() |
| 82 |
tree := New(hash) |
| 83 |
cachedTree = New(hash) |
| 84 |
if proofIndex != math.MaxUint64 { |
| 85 |
if err := cachedTree.SetIndex(proofIndex); err != nil { |
| 86 |
panic(err) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
for _, b := range data { |
| 91 |
b = b % 6 |
| 92 |
|
| 93 |
|
| 94 |
if b == 0 { |
| 95 |
data := hash.Sum([]byte{byte(numLeaves)}) |
| 96 |
tree.Push(data) |
| 97 |
cachedTree.Push(data) |
| 98 |
numLeaves++ |
| 99 |
continue |
| 100 |
} |
| 101 |
|
| 102 |
height := int(b - 1) |
| 103 |
subTree := New(hash) |
| 104 |
for i := uint64(0); i < 1<<uint64(height); i++ { |
| 105 |
data := hash.Sum([]byte{byte(numLeaves)}) |
| 106 |
tree.Push(data) |
| 107 |
subTree.Push(data) |
| 108 |
numLeaves++ |
| 109 |
} |
| 110 |
if err := cachedTree.PushSubTree(height, subTree.Root()); err != nil { |
| 111 |
return |
| 112 |
} |
| 113 |
} |
| 114 |
if !bytes.Equal(tree.Root(), cachedTree.Root()) { |
| 115 |
panic("tree roots don't match") |
| 116 |
} |
| 117 |
return |
| 118 |
} |