/
init.go
61 lines (49 loc) · 1.58 KB
/
init.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
package bls
import (
"crypto/rand"
"fmt"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/crypto"
blst "github.com/supranational/blst/bindings/go"
"github.com/filecoin-project/lotus/lib/sigs"
)
const DST = string("BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_")
type SecretKey = blst.SecretKey
type PublicKey = blst.P1Affine
type Signature = blst.P2Affine
type AggregateSignature = blst.P2Aggregate
type blsSigner struct{}
func (blsSigner) GenPrivate() ([]byte, error) {
// Generate 32 bytes of randomness
var ikm [32]byte
_, err := rand.Read(ikm[:])
if err != nil {
return nil, fmt.Errorf("bls signature error generating random data")
}
// Note private keys seem to be serialized little-endian!
pk := blst.KeyGen(ikm[:]).ToLEndian()
return pk, nil
}
func (blsSigner) ToPublic(priv []byte) ([]byte, error) {
pk := new(SecretKey).FromLEndian(priv)
if pk == nil || !pk.Valid() {
return nil, fmt.Errorf("bls signature invalid private key")
}
return new(PublicKey).From(pk).Compress(), nil
}
func (blsSigner) Sign(p []byte, msg []byte) ([]byte, error) {
pk := new(SecretKey).FromLEndian(p)
if pk == nil || !pk.Valid() {
return nil, fmt.Errorf("bls signature invalid private key")
}
return new(Signature).Sign(pk, msg, []byte(DST)).Compress(), nil
}
func (blsSigner) Verify(sig []byte, a address.Address, msg []byte) error {
if !new(Signature).VerifyCompressed(sig, a.Payload()[:], msg, []byte(DST)) {
return fmt.Errorf("bls signature failed to verify")
}
return nil
}
func init() {
sigs.RegisterSignature(crypto.SigTypeBLS, blsSigner{})
}