github.com/amazechain/amc@v0.1.3/utils/crypto.go (about) 1 package utils 2 3 import ( 4 "crypto/ecdsa" 5 "github.com/btcsuite/btcd/btcec/v2" 6 "github.com/libp2p/go-libp2p/core/crypto" 7 "github.com/pkg/errors" 8 "math/big" 9 10 amc_crypto "github.com/amazechain/amc/common/crypto" 11 ) 12 13 func ConvertFromInterfacePrivKey(privkey crypto.PrivKey) (*ecdsa.PrivateKey, error) { 14 secpKey, ok := privkey.(*crypto.Secp256k1PrivateKey) 15 if !ok { 16 return nil, errors.New("could not cast to Secp256k1PrivateKey") 17 } 18 rawKey, err := secpKey.Raw() 19 if err != nil { 20 return nil, err 21 } 22 privKey := new(ecdsa.PrivateKey) 23 k := new(big.Int).SetBytes(rawKey) 24 privKey.D = k 25 privKey.Curve = amc_crypto.S256() // Temporary hack, so libp2p Secp256k1 is recognized as geth Secp256k1 in disc v5.1. 26 privKey.X, privKey.Y = amc_crypto.S256().ScalarBaseMult(rawKey) 27 return privKey, nil 28 } 29 30 func ConvertToInterfacePrivkey(privkey *ecdsa.PrivateKey) (crypto.PrivKey, error) { 31 privBytes := privkey.D.Bytes() 32 // In the event the number of bytes outputted by the big-int are less than 32, 33 // we append bytes to the start of the sequence for the missing most significant 34 // bytes. 35 if len(privBytes) < 32 { 36 privBytes = append(make([]byte, 32-len(privBytes)), privBytes...) 37 } 38 return crypto.UnmarshalSecp256k1PrivateKey(privBytes) 39 } 40 41 func ConvertToInterfacePubkey(pubkey *ecdsa.PublicKey) (crypto.PubKey, error) { 42 xVal, yVal := new(btcec.FieldVal), new(btcec.FieldVal) 43 if xVal.SetByteSlice(pubkey.X.Bytes()) { 44 return nil, errors.Errorf("X value overflows") 45 } 46 if yVal.SetByteSlice(pubkey.Y.Bytes()) { 47 return nil, errors.Errorf("Y value overflows") 48 } 49 newKey := crypto.PubKey((*crypto.Secp256k1PublicKey)(btcec.NewPublicKey(xVal, yVal))) 50 // Zero out temporary values. 51 xVal.Zero() 52 yVal.Zero() 53 return newKey, nil 54 }