-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
80 lines (62 loc) · 1.35 KB
/
util.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
79
80
package merkletree
import "fmt"
func buildIntermediate(nl []*Node, tree *MerkleTree) (*Node, error) {
var nodes []*Node
for i := 0; i < len(nl); i += 2 {
h := tree.hashStrategy()
var left, right = i, i + 1
if i+1 == len(nl) {
right = i
}
calculatedHash := append(nl[left].Hash, nl[right].Hash...)
if _, err := h.Write(calculatedHash); err != nil {
return nil, err
}
n := &Node{
Tree: tree,
Left: nl[left],
Right: nl[right],
Hash: h.Sum(nil),
}
nodes = append(nodes, n)
nl[left].Parent = n
nl[right].Parent = n
if len(nl) == 2 {
return n, nil
}
}
return buildIntermediate(nodes, tree)
}
func buildWithContent(contents []Content, tree *MerkleTree) (*Node, []*Node, error) {
if len(contents) == 0 {
return nil, nil, fmt.Errorf("cannot construct the tree with empty contents")
}
var leafs []*Node
for _, c := range contents {
hash, err := c.CalculateHash()
if err != nil {
return nil, nil, err
}
leafs = append(leafs, &Node{
Tree: tree,
Hash: hash,
C: c,
leaf: true,
})
}
if len(leafs)%2 == 1 {
dup := &Node{
Tree: tree,
Hash: leafs[len(leafs)-1].Hash,
C: leafs[len(leafs)-1].C,
leaf: true,
dup: true,
}
leafs = append(leafs, dup)
}
root, err := buildIntermediate(leafs, tree)
if err != nil {
return nil, nil, err
}
return root, leafs, nil
}