2018-08-09 01:06:34 +00:00
|
|
|
package types
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2018-12-18 16:10:04 +00:00
|
|
|
"github.com/cosmos/ethermint/crypto"
|
2018-08-09 01:06:34 +00:00
|
|
|
ethcmn "github.com/ethereum/go-ethereum/common"
|
|
|
|
ethcrypto "github.com/ethereum/go-ethereum/crypto"
|
2018-11-28 22:19:22 +00:00
|
|
|
"github.com/ethereum/go-ethereum/rlp"
|
2018-08-09 01:06:34 +00:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2019-07-11 18:05:34 +00:00
|
|
|
"golang.org/x/crypto/sha3"
|
2018-08-09 01:06:34 +00:00
|
|
|
)
|
|
|
|
|
2019-07-02 19:36:22 +00:00
|
|
|
// GenerateEthAddress generates an Ethereum address.
|
2018-08-09 01:06:34 +00:00
|
|
|
func GenerateEthAddress() ethcmn.Address {
|
2018-12-18 16:10:04 +00:00
|
|
|
priv, err := crypto.GenerateKey()
|
2018-08-09 01:06:34 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2019-08-11 14:42:46 +00:00
|
|
|
return ethcrypto.PubkeyToAddress(priv.ToECDSA().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
|
|
|
|
2018-11-28 22:19:22 +00:00
|
|
|
func rlpHash(x interface{}) (hash ethcmn.Hash) {
|
2019-07-11 18:05:34 +00:00
|
|
|
hasher := sha3.NewLegacyKeccak256()
|
2018-11-28 22:19:22 +00:00
|
|
|
|
2019-07-02 19:36:22 +00:00
|
|
|
// nolint:errcheck
|
2018-11-28 22:19:22 +00:00
|
|
|
rlp.Encode(hasher, x)
|
|
|
|
hasher.Sum(hash[:0])
|
|
|
|
|
2019-07-11 18:05:34 +00:00
|
|
|
return hash
|
2018-08-24 15:29:10 +00:00
|
|
|
}
|