-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
83 lines (71 loc) · 1.55 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
package merkle_signing
import (
"crypto"
"crypto/sha512"
"github.com/oasisprotocol/ed25519"
)
type MerkleSig struct {
Pub ed25519.PublicKey
RootSig []byte
Path [][]byte
Indexes []bool
}
func SignMerkle(priv *ed25519.PrivateKey, pub ed25519.PublicKey, hashes [][]byte) []MerkleSig {
t, err := NewTreeWithHashStrategy(hashes, sha512.New)
if err != nil {
panic(err)
}
root := t.MerkleRoot()
opts := ed25519.Options{
Hash: crypto.SHA512,
}
rootSig, err := priv.Sign(nil, root, &opts)
if err != nil {
panic(err)
}
sigs := make([]MerkleSig, len(hashes))
for i, item := range hashes {
path, indexesInt64, err := t.GetMerklePath(item)
if err != nil {
panic(err)
}
indexes := make([]bool, len(indexesInt64))
for j, index := range indexesInt64 {
indexes[j] = index == 1
}
sigs[i] = MerkleSig{
Pub: pub,
RootSig: rootSig,
Path: path,
Indexes: indexes,
}
}
return sigs
}
func VerifyMerkle(hash []byte, sig MerkleSig) (bool, error) {
// calculate master
current := hash
for i := range sig.Path {
h := sha512.New()
hash := sig.Path[i]
index := sig.Indexes[i]
var msg []byte
if index == false {
// hash is left
msg = append(hash, current...)
} else {
// hash is right
msg = append(current, hash...)
}
if _, err := h.Write(msg); err != nil {
return false, err
}
current = h.Sum(nil)
}
// `current` should now be the merkle root.
opts := ed25519.Options{
Hash: crypto.SHA512,
}
valid := ed25519.VerifyWithOptions(sig.Pub, current, sig.RootSig, &opts)
return valid, nil
}