-
Notifications
You must be signed in to change notification settings - Fork 193
/
bls.go
266 lines (222 loc) · 7.86 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package blscrypto
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"errors"
"fmt"
"math/big"
"reflect"
"github.com/celo-org/celo-blockchain/common"
"github.com/celo-org/celo-blockchain/common/hexutil"
"github.com/celo-org/celo-blockchain/crypto"
"github.com/celo-org/celo-bls-go/bls"
)
const (
PUBLICKEYBYTES = bls.PUBLICKEYBYTES
SIGNATUREBYTES = bls.SIGNATUREBYTES
EPOCHENTROPYBYTES = bls.EPOCHENTROPYBYTES
)
var (
serializedPublicKeyT = reflect.TypeOf(SerializedPublicKey{})
serializedSignatureT = reflect.TypeOf(SerializedSignature{})
)
type SerializedPublicKey [PUBLICKEYBYTES]byte
// EpochEntropyFromHash truncates the given hash to the length of epoch SNARK entropy.
func EpochEntropyFromHash(hash common.Hash) bls.EpochEntropy {
var entropy bls.EpochEntropy
copy(entropy[:], hash[:EPOCHENTROPYBYTES])
return entropy
}
// MarshalText returns the hex representation of pk.
func (pk SerializedPublicKey) MarshalText() ([]byte, error) {
return hexutil.Bytes(pk[:]).MarshalText()
}
// UnmarshalText parses a BLS public key in hex syntax.
func (pk *SerializedPublicKey) UnmarshalText(input []byte) error {
return hexutil.UnmarshalFixedText("SerializedPublicKey", input, pk[:])
}
// UnmarshalJSON parses a BLS public key in hex syntax.
func (pk *SerializedPublicKey) UnmarshalJSON(input []byte) error {
return hexutil.UnmarshalFixedJSON(serializedPublicKeyT, input, pk[:])
}
type SerializedSignature [SIGNATUREBYTES]byte
// MarshalText returns the hex representation of sig.
func (sig SerializedSignature) MarshalText() ([]byte, error) {
return hexutil.Bytes(sig[:]).MarshalText()
}
// UnmarshalText parses a BLS signature in hex syntax.
func (sig *SerializedSignature) UnmarshalText(input []byte) error {
return hexutil.UnmarshalFixedText("SerializedSignature", input, sig[:])
}
// UnmarshalJSON parses a BLS signature in hex syntax.
func (sig *SerializedSignature) UnmarshalJSON(input []byte) error {
return hexutil.UnmarshalFixedJSON(serializedSignatureT, input, sig[:])
}
func ECDSAToBLS(privateKeyECDSA *ecdsa.PrivateKey) ([]byte, error) {
for i := 0; i < 256; i++ {
modulus := big.NewInt(0)
modulus, ok := modulus.SetString(bls.MODULUS377, 10)
if !ok {
return nil, errors.New("can't parse modulus")
}
privateKeyECDSABytes := crypto.FromECDSA(privateKeyECDSA)
keyBytes := []byte("ecdsatobls")
keyBytes = append(keyBytes, uint8(i))
keyBytes = append(keyBytes, privateKeyECDSABytes...)
privateKeyBLSBytes := crypto.Keccak256(keyBytes)
privateKeyBLSBytes[0] &= bls.MODULUSMASK
privateKeyBLSBig := big.NewInt(0)
privateKeyBLSBig.SetBytes(privateKeyBLSBytes)
if privateKeyBLSBig.Cmp(modulus) >= 0 {
continue
}
privateKeyBytes := privateKeyBLSBig.Bytes()
for len(privateKeyBytes) < len(privateKeyBLSBytes) {
privateKeyBytes = append([]byte{0x00}, privateKeyBytes...)
}
if !bytes.Equal(privateKeyBLSBytes, privateKeyBytes) {
return nil, fmt.Errorf("private key bytes should have been the same: %s, %s", hex.EncodeToString(privateKeyBLSBytes), hex.EncodeToString(privateKeyBytes))
}
// reverse order, as the BLS library expects little endian
for i := len(privateKeyBytes)/2 - 1; i >= 0; i-- {
opp := len(privateKeyBytes) - 1 - i
privateKeyBytes[i], privateKeyBytes[opp] = privateKeyBytes[opp], privateKeyBytes[i]
}
privateKeyBLS, err := bls.DeserializePrivateKey(privateKeyBytes)
if err != nil {
return nil, err
}
defer privateKeyBLS.Destroy()
privateKeyBLSBytesFromLib, err := privateKeyBLS.Serialize()
if err != nil {
return nil, err
}
if !bytes.Equal(privateKeyBytes, privateKeyBLSBytesFromLib) {
return nil, errors.New("private key bytes from library should have been the same")
}
return privateKeyBLSBytesFromLib, nil
}
return nil, errors.New("couldn't derive a BLS key from an ECDSA key")
}
func PrivateToPublic(privateKeyBytes []byte) (SerializedPublicKey, error) {
privateKey, err := bls.DeserializePrivateKey(privateKeyBytes)
if err != nil {
return SerializedPublicKey{}, err
}
defer privateKey.Destroy()
publicKey, err := privateKey.ToPublic()
if err != nil {
return SerializedPublicKey{}, err
}
defer publicKey.Destroy()
pubKeyBytes, err := publicKey.Serialize()
if err != nil {
return SerializedPublicKey{}, err
}
pubKeyBytesFixed := SerializedPublicKey{}
copy(pubKeyBytesFixed[:], pubKeyBytes)
return pubKeyBytesFixed, nil
}
func VerifyAggregatedSignature(publicKeys []SerializedPublicKey, message []byte, extraData []byte, signature []byte, shouldUseCompositeHasher, cip22 bool) error {
publicKeyObjs := []*bls.PublicKey{}
for _, publicKey := range publicKeys {
publicKeyObj, err := bls.DeserializePublicKeyCached(publicKey[:])
if err != nil {
return err
}
defer publicKeyObj.Destroy()
publicKeyObjs = append(publicKeyObjs, publicKeyObj)
}
apk, err := bls.AggregatePublicKeys(publicKeyObjs)
if err != nil {
return err
}
defer apk.Destroy()
signatureObj, err := bls.DeserializeSignature(signature)
if err != nil {
return err
}
defer signatureObj.Destroy()
err = apk.VerifySignature(message, extraData, signatureObj, shouldUseCompositeHasher, cip22)
return err
}
func AggregateSignatures(signatures [][]byte) ([]byte, error) {
signatureObjs := []*bls.Signature{}
for _, signature := range signatures {
signatureObj, err := bls.DeserializeSignature(signature)
if err != nil {
return nil, err
}
defer signatureObj.Destroy()
signatureObjs = append(signatureObjs, signatureObj)
}
asig, err := bls.AggregateSignatures(signatureObjs)
if err != nil {
return nil, err
}
defer asig.Destroy()
asigBytes, err := asig.Serialize()
if err != nil {
return nil, err
}
return asigBytes, nil
}
func VerifySignature(publicKey SerializedPublicKey, message []byte, extraData []byte, signature []byte, shouldUseCompositeHasher, cip22 bool) error {
publicKeyObj, err := bls.DeserializePublicKeyCached(publicKey[:])
if err != nil {
return err
}
defer publicKeyObj.Destroy()
signatureObj, err := bls.DeserializeSignature(signature)
if err != nil {
return err
}
defer signatureObj.Destroy()
err = publicKeyObj.VerifySignature(message, extraData, signatureObj, shouldUseCompositeHasher, cip22)
return err
}
func EncodeEpochSnarkData(newValSet []SerializedPublicKey, maximumNonSigners uint32, epochIndex uint16) ([]byte, []byte, error) {
pubKeys := []*bls.PublicKey{}
for _, pubKey := range newValSet {
publicKeyObj, err := bls.DeserializePublicKeyCached(pubKey[:])
if err != nil {
return nil, nil, err
}
defer publicKeyObj.Destroy()
pubKeys = append(pubKeys, publicKeyObj)
}
message, err := bls.EncodeEpochToBytes(epochIndex, maximumNonSigners, pubKeys)
return message, nil, err
}
func EncodeEpochSnarkDataCIP22(newValSet []SerializedPublicKey, maximumNonSigners, maxValidators uint32, epochIndex uint16, round uint8, blockHash, parentHash bls.EpochEntropy) ([]byte, []byte, error) {
pubKeys := []*bls.PublicKey{}
for _, pubKey := range newValSet {
publicKeyObj, err := bls.DeserializePublicKeyCached(pubKey[:])
if err != nil {
return nil, nil, err
}
defer publicKeyObj.Destroy()
pubKeys = append(pubKeys, publicKeyObj)
}
return bls.EncodeEpochToBytesCIP22(epochIndex, round, blockHash, parentHash, maximumNonSigners, maxValidators, pubKeys)
}
func SerializedSignatureFromBytes(serializedSignature []byte) (SerializedSignature, error) {
if len(serializedSignature) != SIGNATUREBYTES {
return SerializedSignature{}, fmt.Errorf("wrong length for serialized signature: expected %d, got %d", SIGNATUREBYTES, len(serializedSignature))
}
signatureBytesFixed := SerializedSignature{}
copy(signatureBytesFixed[:], serializedSignature)
return signatureBytesFixed, nil
}
func UncompressKey(serialized SerializedPublicKey) ([]byte, error) {
publicKey, err := bls.DeserializePublicKeyCached(serialized[:])
if err != nil {
return nil, err
}
uncompressedBytes, err := publicKey.SerializeUncompressed()
if err != nil {
return nil, err
}
return uncompressedBytes, nil
}