-
Notifications
You must be signed in to change notification settings - Fork 2
/
node.go
76 lines (61 loc) · 1.39 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
65
66
67
68
69
70
71
72
73
74
75
76
package merkletree
// TODO: Make a custom UnmashalJSON
import (
"crypto/sha256"
"encoding/json"
)
// Node is a node in a merkle tree
type Node struct {
Hash []byte `json:"hash"`
Left *Node `json:"left"`
Right *Node `json:"right"`
parent *Node
}
// NewNode create a leave node and hash its data
func NewNode(data []byte) *Node {
n := Node{
Hash: computeHash(data),
}
return &n
}
// FromJSON will construct the Node from parsed raw json
func (n *Node) FromJSON(raw []byte) error {
if err := json.Unmarshal(raw, n); err != nil {
return err
}
populateParent(n, n.Left)
populateParent(n, n.Right)
return nil
}
func populateParent(parent *Node, node *Node) {
if node != nil {
node.parent = parent
populateParent(node, node.Left)
populateParent(node, node.Right)
}
}
// NewParentNode construct a new parent node out of leave nodes
func NewParentNode(left *Node, right *Node) *Node {
n := Node{}
n.Left = left
n.Right = right
left.parent = &n
if right != nil {
right.parent = &n
}
n.Hash = computeConcatinatedHash(left, right)
return &n
}
func computeHash(data []byte) []byte {
hash := sha256.Sum256(data)
return hash[:]
}
func computeConcatinatedHash(left *Node, right *Node) []byte {
// Carry up left node if the tree has ood node
if right == nil {
return left.Hash
}
rightHash := right.Hash
hash := append(left.Hash, rightHash...)
return computeHash(hash)
}