forked from 0xPolygon/polygon-edge
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrypto.go
454 lines (357 loc) · 11 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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package crypto
import (
"bytes"
goCrypto "crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"math/big"
"github.com/0xPolygon/polygon-edge/helper/hex"
"github.com/0xPolygon/polygon-edge/helper/keystore"
"github.com/0xPolygon/polygon-edge/secrets"
"github.com/0xPolygon/polygon-edge/types"
"github.com/btcsuite/btcd/btcec"
"github.com/coinbase/kryptology/pkg/signatures/bls/bls_sig"
"github.com/umbracle/fastrlp"
"golang.org/x/crypto/sha3"
)
var (
big1 = big.NewInt(1)
)
// S256 is the secp256k1 elliptic curve
var S256 = btcec.S256()
var (
secp256k1N = hex.MustDecodeHex("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141")
one = []byte{0x01}
ErrInvalidBLSSignature = errors.New("invalid BLS Signature")
)
type KeyType string
const (
KeyECDSA KeyType = "ecdsa"
KeyBLS KeyType = "bls"
)
var (
errInvalidSignature = errors.New("invalid signature")
)
func trimLeftZeros(b []byte) []byte {
i := 0
for i = range b {
if b[i] != 0 {
break
}
}
return b[i:]
}
// ValidateSignatureValues checks if the signature values are correct
func ValidateSignatureValues(v byte, r, s *big.Int) bool {
// TODO: ECDSA malleability
if r == nil || s == nil {
return false
}
if v > 1 {
return false
}
rr := r.Bytes()
rr = trimLeftZeros(rr)
if bytes.Compare(rr, secp256k1N) >= 0 || bytes.Compare(rr, one) < 0 {
return false
}
ss := s.Bytes()
ss = trimLeftZeros(ss)
if bytes.Compare(ss, secp256k1N) >= 0 || bytes.Compare(ss, one) < 0 {
return false
}
return true
}
var addressPool fastrlp.ArenaPool
// CreateAddress creates an Ethereum address.
func CreateAddress(addr types.Address, nonce uint64) types.Address {
a := addressPool.Get()
defer addressPool.Put(a)
v := a.NewArray()
v.Set(a.NewBytes(addr.Bytes()))
v.Set(a.NewUint(nonce))
dst := v.MarshalTo(nil)
dst = Keccak256(dst)[12:]
return types.BytesToAddress(dst)
}
var create2Prefix = []byte{0xff}
// CreateAddress2 creates an Ethereum address following the CREATE2 Opcode.
func CreateAddress2(addr types.Address, salt [32]byte, inithash []byte) types.Address {
return types.BytesToAddress(Keccak256(create2Prefix, addr.Bytes(), salt[:], Keccak256(inithash))[12:])
}
func ParseECDSAPrivateKey(buf []byte) (*ecdsa.PrivateKey, error) {
prv, _ := btcec.PrivKeyFromBytes(S256, buf)
return prv.ToECDSA(), nil
}
// MarshalECDSAPrivateKey serializes the private key's D value to a []byte
func MarshalECDSAPrivateKey(priv *ecdsa.PrivateKey) ([]byte, error) {
return (*btcec.PrivateKey)(priv).Serialize(), nil
}
// GenerateECDSAKey generates a new key based on the secp256k1 elliptic curve.
func GenerateECDSAKey() (*ecdsa.PrivateKey, error) {
return ecdsa.GenerateKey(S256, rand.Reader)
}
// ParsePublicKey parses bytes into a public key on the secp256k1 elliptic curve.
func ParsePublicKey(buf []byte) (*ecdsa.PublicKey, error) {
x, y := elliptic.Unmarshal(S256, buf)
if x == nil || y == nil {
return nil, fmt.Errorf("cannot unmarshal")
}
return &ecdsa.PublicKey{Curve: S256, X: x, Y: y}, nil
}
// MarshalPublicKey marshals a public key on the secp256k1 elliptic curve.
func MarshalPublicKey(pub *ecdsa.PublicKey) []byte {
return elliptic.Marshal(S256, pub.X, pub.Y)
}
func Ecrecover(hash, sig []byte) ([]byte, error) {
pub, err := RecoverPubkey(sig, hash)
if err != nil {
return nil, err
}
return MarshalPublicKey(pub), nil
}
// RecoverPubkey verifies the compact signature "signature" of "hash" for the
// secp256k1 curve.
func RecoverPubkey(signature, hash []byte) (*ecdsa.PublicKey, error) {
size := len(signature)
term := byte(27)
// Make sure the signature is present
if signature == nil || size < 1 {
return nil, errInvalidSignature
}
if signature[size-1] == 1 {
term = 28
}
sig := append([]byte{term}, signature[:size-1]...)
pub, _, err := btcec.RecoverCompact(S256, sig, hash)
if err != nil {
return nil, err
}
return pub.ToECDSA(), nil
}
// Sign produces a compact signature of the data in hash with the given
// private key on the secp256k1 curve.
func Sign(priv *ecdsa.PrivateKey, hash []byte) ([]byte, error) {
sig, err := btcec.SignCompact(S256, (*btcec.PrivateKey)(priv), hash, false)
if err != nil {
return nil, err
}
term := byte(0)
if sig[0] == 28 {
term = 1
}
return append(sig, term)[1:], nil
}
// SignByBLS signs the given data by BLS
func SignByBLS(prv *bls_sig.SecretKey, msg []byte) ([]byte, error) {
signature, err := bls_sig.NewSigPop().Sign(prv, msg)
if err != nil {
return nil, err
}
return signature.MarshalBinary()
}
// VerifyBLSSignature verifies the given signature from Public Key and original message
func VerifyBLSSignature(pubkey *bls_sig.PublicKey, sig *bls_sig.Signature, message []byte) error {
ok, err := bls_sig.NewSigPop().Verify(pubkey, message, sig)
if err != nil {
return err
}
if !ok {
return ErrInvalidBLSSignature
}
return nil
}
// VerifyBLSSignatureFromBytes verifies BLS Signature from BLS PublicKey, signature, and original message in bytes
func VerifyBLSSignatureFromBytes(rawPubkey, rawSig, message []byte) error {
pubkey, err := UnmarshalBLSPublicKey(rawPubkey)
if err != nil {
return err
}
signature, err := UnmarshalBLSSignature(rawSig)
if err != nil {
return err
}
return VerifyBLSSignature(pubkey, signature, message)
}
// SigToPub returns the public key that created the given signature.
func SigToPub(hash, sig []byte) (*ecdsa.PublicKey, error) {
s, err := Ecrecover(hash, sig)
if err != nil {
return nil, err
}
x, y := elliptic.Unmarshal(S256, s)
return &ecdsa.PublicKey{Curve: S256, X: x, Y: y}, nil
}
// Keccak256 calculates the Keccak256
func Keccak256(v ...[]byte) []byte {
h := sha3.NewLegacyKeccak256()
for _, i := range v {
h.Write(i)
}
return h.Sum(nil)
}
// PubKeyToAddress returns the Ethereum address of a public key
func PubKeyToAddress(pub *ecdsa.PublicKey) types.Address {
buf := Keccak256(MarshalPublicKey(pub)[1:])[12:]
return types.BytesToAddress(buf)
}
// GetAddressFromKey extracts an address from the private key
func GetAddressFromKey(key goCrypto.PrivateKey) (types.Address, error) {
privateKeyConv, ok := key.(*ecdsa.PrivateKey)
if !ok {
return types.ZeroAddress, errors.New("unable to assert type")
}
publicKey := privateKeyConv.PublicKey
return PubKeyToAddress(&publicKey), nil
}
// generateECDSAKeyAndMarshal generates a new ECDSA private key and serializes it to a byte array
func generateECDSAKeyAndMarshal() ([]byte, error) {
key, err := GenerateECDSAKey()
if err != nil {
return nil, err
}
buf, err := MarshalECDSAPrivateKey(key)
if err != nil {
return nil, err
}
return buf, nil
}
// BytesToECDSAPrivateKey reads the input byte array and constructs a private key if possible
func BytesToECDSAPrivateKey(input []byte) (*ecdsa.PrivateKey, error) {
// The key file on disk should be encoded in Base64,
// so it must be decoded before it can be parsed by ParsePrivateKey
decoded, err := hex.DecodeString(string(input))
if err != nil {
return nil, err
}
// Make sure the key is properly formatted
if len(decoded) != 32 {
// Key must be exactly 64 chars (32B) long
return nil, fmt.Errorf("invalid key length (%dB), should be 32B", len(decoded))
}
// Convert decoded bytes to a private key
key, err := ParseECDSAPrivateKey(decoded)
if err != nil {
return nil, err
}
return key, nil
}
// GenerateBLSKey generates a new BLS key
func GenerateBLSKey() (*bls_sig.SecretKey, error) {
blsPop := bls_sig.NewSigPop()
_, sk, err := blsPop.Keygen()
if err != nil {
return nil, err
}
return sk, nil
}
// generateBLSKeyAndMarshal generates a new BLS secret key and serializes it to a byte array
func generateBLSKeyAndMarshal() ([]byte, error) {
key, err := GenerateBLSKey()
if err != nil {
return nil, err
}
buf, err := key.MarshalBinary()
if err != nil {
return nil, err
}
return buf, nil
}
// BytesToECDSAPrivateKey reads the input byte array and constructs a private key if possible
func BytesToBLSSecretKey(input []byte) (*bls_sig.SecretKey, error) {
// The key file on disk should be encoded in Base64,
// so it must be decoded before it can be parsed by ParsePrivateKey
decoded, err := hex.DecodeString(string(input))
if err != nil {
return nil, err
}
sk := &bls_sig.SecretKey{}
if err := sk.UnmarshalBinary(decoded); err != nil {
return nil, err
}
return sk, nil
}
// BLSSecretKeyToPubkeyBytes returns bytes of BLS Public Key corresponding to the given secret key
func BLSSecretKeyToPubkeyBytes(key *bls_sig.SecretKey) ([]byte, error) {
pubKey, err := key.GetPublicKey()
if err != nil {
return nil, err
}
marshalled, err := pubKey.MarshalBinary()
if err != nil {
return nil, err
}
return marshalled, nil
}
// BytesToBLSPublicKey decodes given hex string and returns BLS Public Key
func BytesToBLSPublicKey(input string) (*bls_sig.PublicKey, error) {
// The key file on disk should be encoded in Base64,
// so it must be decoded before it can be parsed by ParsePrivateKey
decoded, err := hex.DecodeString(input)
if err != nil {
return nil, err
}
return UnmarshalBLSPublicKey(decoded)
}
// UnmarshalBLSPublicKey unmarshal bytes data into BLS Public Key
func UnmarshalBLSPublicKey(input []byte) (*bls_sig.PublicKey, error) {
pk := &bls_sig.PublicKey{}
if err := pk.UnmarshalBinary(input); err != nil {
return nil, err
}
return pk, nil
}
// UnmarshalBLSSignature unmarshal bytes data into BLS Signature
func UnmarshalBLSSignature(input []byte) (*bls_sig.Signature, error) {
sig := &bls_sig.Signature{}
if err := sig.UnmarshalBinary(input); err != nil {
return nil, err
}
return sig, nil
}
// GenerateOrReadPrivateKey generates a private key at the specified path,
// or reads it if a key file is present
func GenerateOrReadPrivateKey(path string) (*ecdsa.PrivateKey, error) {
keyBuff, err := keystore.CreateIfNotExists(path, generateECDSAKeyAndMarshal)
if err != nil {
return nil, err
}
privateKey, err := BytesToECDSAPrivateKey(keyBuff)
if err != nil {
return nil, fmt.Errorf("unable to execute byte array -> private key conversion, %w", err)
}
return privateKey, nil
}
// GenerateAndEncodeECDSAPrivateKey returns a newly generated private key and the Base64 encoding of that private key
func GenerateAndEncodeECDSAPrivateKey() (*ecdsa.PrivateKey, []byte, error) {
keyBuff, err := keystore.CreatePrivateKey(generateECDSAKeyAndMarshal)
if err != nil {
return nil, nil, err
}
privateKey, err := BytesToECDSAPrivateKey(keyBuff)
if err != nil {
return nil, nil, fmt.Errorf("unable to execute byte array -> private key conversion, %w", err)
}
return privateKey, keyBuff, nil
}
func GenerateAndEncodeBLSSecretKey() (*bls_sig.SecretKey, []byte, error) {
keyBuff, err := keystore.CreatePrivateKey(generateBLSKeyAndMarshal)
if err != nil {
return nil, nil, err
}
secretKey, err := BytesToBLSSecretKey(keyBuff)
if err != nil {
return nil, nil, fmt.Errorf("unable to execute byte array -> private key conversion, %w", err)
}
return secretKey, keyBuff, nil
}
func ReadConsensusKey(manager secrets.SecretsManager) (*ecdsa.PrivateKey, error) {
validatorKey, err := manager.GetSecret(secrets.ValidatorKey)
if err != nil {
return nil, err
}
return BytesToECDSAPrivateKey(validatorKey)
}