-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
140 lines (126 loc) · 2.35 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"os"
"github.com/shopspring/decimal"
)
type Pos string
var (
Left Pos = "left"
Right Pos = "right"
)
type Balance map[string]decimal.Decimal
func (b Balance) Format() string {
v, _ := json.Marshal(b) // ASCII code asc, no indent
return string(v)
}
func (b Balance) Add(other Balance) Balance {
r := make(Balance)
for k, v := range b {
r[k] = v
}
for k, v := range other {
vv, ok := r[k]
if ok {
r[k] = v.Add(vv)
} else {
r[k] = v
}
}
return r
}
func (b Balance) Equal(other Balance) bool {
if len(b) != len(other) {
return false
}
for k, v := range b {
vv, ok := other[k]
if !ok {
return false
}
if !v.Equal(vv) {
return false
}
}
return true
}
func hash(v string) string {
h := sha256.New()
h.Write([]byte(v))
b := h.Sum(nil)
return hex.EncodeToString(b)
}
type MerkleProof struct {
Root struct {
Balances Balance
Hash string
}
Self struct {
Balances Balance
Nonce string
}
Path []struct {
Balances Balance
Hash string
Pos Pos
}
}
func (m *MerkleProof) Validate() bool {
h := hash(m.Self.Nonce + m.Self.Balances.Format())
b := m.Self.Balances
for _, path := range m.Path {
if path.Hash == "" { // no right node
h = hash(h + h + b.Format())
} else {
b = b.Add(path.Balances)
if path.Pos == Left {
h = hash(path.Hash + h + b.Format())
} else {
h = hash(h + path.Hash + b.Format())
}
}
}
fmt.Printf("proofed hash: %s\n", h)
fmt.Printf("root hash: %s\n", m.Root.Hash)
if h != m.Root.Hash {
return false
}
fmt.Printf("proofed balances: %s\n", b.Format())
fmt.Printf("root balances: %s\n", m.Root.Balances.Format())
if !b.Equal(m.Root.Balances) {
return false
}
return true
}
func main() {
var f string
flag.StringVar(&f, "f", "", "merkle proof file")
flag.Parse()
if f == "" {
flag.Usage()
return
}
b, err := os.ReadFile(f)
if err != nil {
fmt.Println("invalid merkle proof file", err)
return
}
var m MerkleProof
if err := json.Unmarshal(b, &m); err != nil {
fmt.Println("invalid merkle proof file", err)
return
}
if m.Root.Hash == "" || len(m.Path) == 0 {
fmt.Println("empty merkle proof file")
return
}
if m.Validate() {
fmt.Println("Merkle tree path validation passed")
} else {
fmt.Println("Merkle tree path validation failed.")
}
}