This repository has been archived by the owner on Oct 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
64 lines (55 loc) · 1.6 KB
/
node.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
package grug
import "crypto/sha256"
var (
HashPrefixInternalNode byte = 0
HashPrefixLeafNode byte = 1
ZeroHash Hash = Hash{}
)
// Node is a node is Grug's Merkle tree. It's an enum between either an internal
// or a leaf node.
type Node struct {
Internal *InternalNode `json:"internal,omitempty"`
Leaf *LeafNode `json:"leaf,omitempty"`
}
// InternalNode is an internal node in Grug's Merkle tree.
type InternalNode struct {
LeftHash *Hash `json:"left_hash,omitempty"`
RightHash *Hash `json:"right_hash,omitempty"`
}
// LeafNode is a leaf node in Grug's Merkle tree.
type LeafNode struct {
KeyHash Hash `json:"key_hash"`
ValueHash Hash `json:"value_hash"`
}
// Valiate performs basic validation on the node.
func (node Node) Validate() error {
// One and only one between `Internal` and `Leaf` should be nil.
if (node.Internal == nil) == (node.Leaf == nil) {
return ErrMalformedProof
}
return nil
}
// Hash produces the hash of the internal node.
func (internalNode InternalNode) Hash() Hash {
hasher := sha256.New()
hasher.Write([]byte{HashPrefixInternalNode})
if internalNode.LeftHash != nil {
hasher.Write(internalNode.LeftHash[:])
} else {
hasher.Write(ZeroHash[:])
}
if internalNode.RightHash != nil {
hasher.Write(internalNode.RightHash[:])
} else {
hasher.Write(ZeroHash[:])
}
return Hash(hasher.Sum(nil))
}
// Hash produces the hash of the leaf node.
func (leafNode LeafNode) Hash() Hash {
hasher := sha256.New()
hasher.Write([]byte{HashPrefixLeafNode})
hasher.Write(leafNode.KeyHash[:])
hasher.Write(leafNode.ValueHash[:])
return Hash(hasher.Sum(nil))
}