generated from flashbots/flashbots-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 9
/
bls.go
106 lines (86 loc) · 2.47 KB
/
bls.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
package bls
import (
"crypto/rand"
"errors"
blst "github.com/supranational/blst/bindings/go"
)
// From https://github.com/supranational/blst/tree/master/bindings/go
var dst = []byte("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_")
const BLSPublicKeyLength int = 48
const BLSSecretKeyLength int = 32
const BLSSignatureLength int = 96
type PublicKey = blst.P1Affine
type SecretKey = blst.SecretKey
type Signature = blst.P2Affine
func PublicKeyFromBytes(pkBytes []byte) (*PublicKey, error) {
if len(pkBytes) != BLSPublicKeyLength {
return nil, errors.New("invalid pubkey length")
}
pk := new(PublicKey).Uncompress(pkBytes)
if pk == nil {
return nil, errors.New("could not uncompress public key from bytes")
}
if !pk.KeyValidate() {
return nil, errors.New("invalid pubkey")
}
return pk, nil
}
func PublicKeyFromSecretKey(sk *SecretKey) *PublicKey {
return new(PublicKey).From(sk)
}
func SecretKeyFromBytes(skBytes []byte) (*SecretKey, error) {
if len(skBytes) != BLSSecretKeyLength {
return nil, errors.New("invalid secret key length")
}
secretKey := new(SecretKey).Deserialize(skBytes)
if secretKey == nil {
return nil, errors.New("could not deserialize secret key from bytes")
}
return secretKey, nil
}
func GenerateRandomSecretKey() (*SecretKey, error) {
var ikm [BLSSecretKeyLength]byte
_, err := rand.Read(ikm[:])
if err != nil {
return nil, err
}
sk := blst.KeyGen(ikm[:])
return sk, nil
}
func GenerateNewKeypair() (*SecretKey, *PublicKey, error) {
sk, err := GenerateRandomSecretKey()
if err != nil {
return nil, nil, err
}
return sk, PublicKeyFromSecretKey(sk), nil
}
func Sign(sk *SecretKey, msg []byte) *Signature {
return new(Signature).Sign(sk, msg, dst)
}
func SignatureFromBytes(sigBytes []byte) (*Signature, error) {
if len(sigBytes) != BLSSignatureLength {
return nil, errors.New("invalid signature length")
}
sig := new(Signature).Uncompress(sigBytes)
if sig == nil {
return nil, errors.New("could not uncompress signature from bytes")
}
if !sig.SigValidate(false) {
return nil, errors.New("invalid signature")
}
return sig, nil
}
func VerifySignature(sig *Signature, pk *PublicKey, msg []byte) bool {
return sig.Verify(false, pk, false, msg, dst)
}
func VerifySignatureBytes(msg, sigBytes, pkBytes []byte) (bool, error) {
sig, err := SignatureFromBytes(sigBytes)
if err != nil {
return false, err
}
pubkey, err := PublicKeyFromBytes(pkBytes)
if err != nil {
return false, err
}
return VerifySignature(sig, pubkey, msg[:]), nil
}