This repository has been archived by the owner on Feb 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
treehasher.go
78 lines (60 loc) · 1.77 KB
/
treehasher.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
package smt
import (
"bytes"
"hash"
)
var leafPrefix = []byte{0}
var nodePrefix = []byte{1}
type treeHasher struct {
hasher hash.Hash
zeroValue []byte
}
func newTreeHasher(hasher hash.Hash) *treeHasher {
th := treeHasher{hasher: hasher}
th.zeroValue = make([]byte, th.pathSize())
return &th
}
func (th *treeHasher) digest(data []byte) []byte {
th.hasher.Write(data)
sum := th.hasher.Sum(nil)
th.hasher.Reset()
return sum
}
func (th *treeHasher) path(key []byte) []byte {
return th.digest(key)
}
func (th *treeHasher) digestLeaf(path []byte, leafData []byte) ([]byte, []byte) {
value := make([]byte, 0, len(leafPrefix)+len(path)+len(leafData))
value = append(value, leafPrefix...)
value = append(value, path...)
value = append(value, leafData...)
th.hasher.Write(value)
sum := th.hasher.Sum(nil)
th.hasher.Reset()
return sum, value
}
func (th *treeHasher) parseLeaf(data []byte) ([]byte, []byte) {
return data[len(leafPrefix) : th.pathSize()+len(leafPrefix)], data[len(leafPrefix)+th.pathSize():]
}
func (th *treeHasher) isLeaf(data []byte) bool {
return bytes.Equal(data[:len(leafPrefix)], leafPrefix)
}
func (th *treeHasher) digestNode(leftData []byte, rightData []byte) ([]byte, []byte) {
value := make([]byte, 0, len(nodePrefix)+len(leftData)+len(rightData))
value = append(value, nodePrefix...)
value = append(value, leftData...)
value = append(value, rightData...)
th.hasher.Write(value)
sum := th.hasher.Sum(nil)
th.hasher.Reset()
return sum, value
}
func (th *treeHasher) parseNode(data []byte) ([]byte, []byte) {
return data[len(nodePrefix) : th.pathSize()+len(nodePrefix)], data[len(nodePrefix)+th.pathSize():]
}
func (th *treeHasher) pathSize() int {
return th.hasher.Size()
}
func (th *treeHasher) placeholder() []byte {
return th.zeroValue
}