2018-08-09 01:06:34 +00:00
|
|
|
package types
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/ecdsa"
|
2018-08-24 15:29:10 +00:00
|
|
|
"crypto/sha256"
|
2018-08-09 01:06:34 +00:00
|
|
|
"fmt"
|
|
|
|
|
2018-08-24 15:29:10 +00:00
|
|
|
sdk "github.com/cosmos/cosmos-sdk/types"
|
|
|
|
"github.com/cosmos/cosmos-sdk/x/auth"
|
2018-08-09 01:06:34 +00:00
|
|
|
ethcmn "github.com/ethereum/go-ethereum/common"
|
|
|
|
ethcrypto "github.com/ethereum/go-ethereum/crypto"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
// GenerateAddress generates an Ethereum address.
|
|
|
|
func GenerateEthAddress() ethcmn.Address {
|
|
|
|
priv, err := ethcrypto.GenerateKey()
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return PrivKeyToEthAddress(priv)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PrivKeyToEthAddress generates an Ethereum address given an ECDSA private key.
|
|
|
|
func PrivKeyToEthAddress(p *ecdsa.PrivateKey) ethcmn.Address {
|
2018-10-24 14:53:23 +00:00
|
|
|
return ethcrypto.PubkeyToAddress(p.PublicKey)
|
2018-08-09 01:06:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateSigner attempts to validate a signer for a given slice of bytes over
|
|
|
|
// which a signature and signer is given. An error is returned if address
|
|
|
|
// derived from the signature and bytes signed does not match the given signer.
|
|
|
|
func ValidateSigner(signBytes, sig []byte, signer ethcmn.Address) error {
|
|
|
|
pk, err := ethcrypto.SigToPub(signBytes, sig)
|
|
|
|
|
|
|
|
if err != nil {
|
2018-08-30 21:36:14 +00:00
|
|
|
return errors.Wrap(err, "failed to derive public key from signature")
|
2018-08-09 01:06:34 +00:00
|
|
|
} else if ethcrypto.PubkeyToAddress(*pk) != signer {
|
|
|
|
return fmt.Errorf("invalid signature for signer: %s", signer)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2018-08-24 15:29:10 +00:00
|
|
|
|
|
|
|
// GetStdTxSignBytes returns the signature bytes for an auth.StdTx transaction
|
|
|
|
// that is compatible with Ethereum's signature mechanism.
|
|
|
|
func GetStdTxSignBytes(chainID string, accNum int64, seq int64, fee auth.StdFee, msgs []sdk.Msg, memo string) []byte {
|
|
|
|
signBytes := auth.StdSignBytes(chainID, accNum, seq, fee, msgs, "")
|
|
|
|
hash := sha256.Sum256(signBytes)
|
|
|
|
return hash[:]
|
|
|
|
}
|