-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerkle_tree.go
65 lines (50 loc) · 1.09 KB
/
merkle_tree.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
package main
import (
"crypto/sha256"
"log"
)
type MerkleTree struct {
RootNode *MerkleNode
}
type MerkleNode struct {
Left *MerkleNode
Right *MerkleNode
Data []byte
}
func NewMerkleTree(data [][]byte) *MerkleTree {
var nodes []MerkleNode
for _, datum := range data {
node := NewMerkleNode(nil, nil, datum)
nodes = append(nodes, *node)
}
if len(nodes) == 0 {
log.Panic("No merkel nodes")
}
for len(nodes) > 1 {
if len(nodes)%2 != 0 {
nodes = append(nodes, nodes[len(nodes)-1])
}
var newLevel []MerkleNode
for i := 0; i < len(nodes); i += 2 {
node := NewMerkleNode(&nodes[i], &nodes[i+1], nil)
newLevel = append(newLevel, *node)
}
nodes = newLevel
}
mTree := MerkleTree{&nodes[0]}
return &mTree
}
func NewMerkleNode(left, right *MerkleNode, data []byte) *MerkleNode {
mNode := MerkleNode{}
if left == nil && right == nil {
hash := sha256.Sum256(data)
mNode.Data = hash[:]
} else {
prevHashes := append(left.Data, right.Data...)
hash := sha256.Sum256(prevHashes)
mNode.Data = hash[:]
}
mNode.Left = left
mNode.Right = right
return &mNode
}