-
Notifications
You must be signed in to change notification settings - Fork 6
/
crypto.go
75 lines (62 loc) · 1.57 KB
/
crypto.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
package main
import (
"crypto"
"crypto/rand"
"fmt"
"github.com/tinychain/algorand/common"
"github.com/tinychain/algorand/vrf"
"golang.org/x/crypto/ed25519"
)
type PublicKey struct {
pk ed25519.PublicKey
}
func (pub *PublicKey) Bytes() []byte {
return pub.pk
}
func (pub *PublicKey) Address() common.Address {
return common.BytesToAddress(pub.pk)
}
func (pub *PublicKey) VerifySign(m, sign []byte) error {
signature := sign[ed25519.PublicKeySize:]
if ok := ed25519.Verify(pub.pk, m, signature); !ok {
return fmt.Errorf("signature invalid")
}
return nil
}
func (pub *PublicKey) VerifyVRF(proof, m []byte) error {
vrf.ECVRF_verify(pub.pk, proof, m)
return nil
}
type PrivateKey struct {
sk ed25519.PrivateKey
}
func (priv *PrivateKey) PublicKey() *PublicKey {
return &PublicKey{priv.sk.Public().(ed25519.PublicKey)}
}
func (priv *PrivateKey) Sign(m []byte) ([]byte, error) {
sign, err := priv.sk.Sign(rand.Reader, m, crypto.Hash(0))
if err != nil {
return nil, err
}
pubkey := priv.sk.Public().(ed25519.PublicKey)
return append(pubkey, sign...), nil
}
func (priv *PrivateKey) Evaluate(m []byte) (value, proof []byte, err error) {
proof, err = vrf.ECVRF_prove(priv.PublicKey().pk, priv.sk, m)
if err != nil {
return
}
value = vrf.ECVRF_proof2hash(proof)
return
}
func NewKeyPair() (*PublicKey, *PrivateKey, error) {
pk, sk, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, nil, err
}
return &PublicKey{pk}, &PrivateKey{sk}, nil
}
func recoverPubkey(sign []byte) *PublicKey {
pubkey := sign[:ed25519.PublicKeySize]
return &PublicKey{pubkey}
}