-
Notifications
You must be signed in to change notification settings - Fork 670
/
bls.go
109 lines (91 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
107
108
109
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package validator
import (
"encoding/json"
"errors"
"github.com/ava-labs/avalanchego/utils/crypto/bls"
"github.com/ava-labs/avalanchego/utils/formatting"
)
var (
_ Signer = &BLS{}
errInvalidProofOfPossession = errors.New("invalid proof of possession")
)
type BLS struct {
PublicKey [bls.PublicKeyLen]byte `serialize:"true" json:"publicKey"`
// BLS signature proving ownership of [PublicKey]. The signed message is the
// [PublicKey].
ProofOfPossession [bls.SignatureLen]byte `serialize:"true" json:"proofOfPossession"`
// publicKey is the parsed version of [PublicKey]. It is populated in
// [Verify].
publicKey *bls.PublicKey
}
func NewBLS(sk *bls.SecretKey) *BLS {
pk := bls.PublicFromSecretKey(sk)
pkBytes := bls.PublicKeyToBytes(pk)
sig := bls.SignProofOfPossession(sk, pkBytes)
sigBytes := bls.SignatureToBytes(sig)
bls := &BLS{
publicKey: pk,
}
copy(bls.PublicKey[:], pkBytes)
copy(bls.ProofOfPossession[:], sigBytes)
return bls
}
func (b *BLS) Verify() error {
publicKey, err := bls.PublicKeyFromBytes(b.PublicKey[:])
if err != nil {
return err
}
signature, err := bls.SignatureFromBytes(b.ProofOfPossession[:])
if err != nil {
return err
}
if !bls.VerifyProofOfPossession(publicKey, signature, b.PublicKey[:]) {
return errInvalidProofOfPossession
}
b.publicKey = publicKey
return nil
}
func (b *BLS) Key() *bls.PublicKey { return b.publicKey }
type jsonBLS struct {
PublicKey string `json:"publicKey"`
ProofOfPossession string `json:"proofOfPossession"`
}
func (b *BLS) MarshalJSON() ([]byte, error) {
pk, err := formatting.Encode(formatting.HexNC, b.PublicKey[:])
if err != nil {
return nil, err
}
pop, err := formatting.Encode(formatting.HexNC, b.ProofOfPossession[:])
if err != nil {
return nil, err
}
return json.Marshal(jsonBLS{
PublicKey: pk,
ProofOfPossession: pop,
})
}
func (b *BLS) UnmarshalJSON(bytes []byte) error {
jsonBLS := jsonBLS{}
err := json.Unmarshal(bytes, &jsonBLS)
if err != nil {
return err
}
pkBytes, err := formatting.Decode(formatting.HexNC, jsonBLS.PublicKey)
if err != nil {
return err
}
pk, err := bls.PublicKeyFromBytes(pkBytes)
if err != nil {
return err
}
popBytes, err := formatting.Decode(formatting.HexNC, jsonBLS.ProofOfPossession)
if err != nil {
return err
}
copy(b.PublicKey[:], pkBytes)
copy(b.ProofOfPossession[:], popBytes)
b.publicKey = pk
return nil
}