diff --git a/account.go b/account.go index 17f29eb..d366130 100644 --- a/account.go +++ b/account.go @@ -5,6 +5,8 @@ package sdk import ( + "crypto/ecdsa" + crand "crypto/rand" "encoding/hex" "errors" "fmt" @@ -56,6 +58,26 @@ func (m *AccountManager) Create(passphrase string) (types.Address, error) { return cfxAddress, nil } +// CreateEthCompatible creates a new account compatible with eth and puts the keystore file into keystore directory +func (m *AccountManager) CreateEthCompatible(passphrase string) (types.Address, error) { + for { + privateKeyECDSA, err := ecdsa.GenerateKey(crypto.S256(), crand.Reader) + if err != nil { + return "", err + } + + addr := crypto.PubkeyToAddress(privateKeyECDSA.PublicKey) + + if addr.Bytes()[0]&0xf0 == 0x10 { + account, err := m.ks.ImportECDSA(privateKeyECDSA, passphrase) + if err != nil { + return "", err + } + return *types.NewAddressFromCommon(account.Address), nil + } + } +} + // Import imports account from external key file to keystore directory. // Returns error if the account already exists. func (m *AccountManager) Import(keyFile, passphrase, newPassphrase string) (types.Address, error) { diff --git a/types/types.go b/types/types.go index 9fc3aa1..dfdcc86 100644 --- a/types/types.go +++ b/types/types.go @@ -21,6 +21,12 @@ func NewAddress(hexAddress string) *Address { return &addr } +// NewAddressFromCommon creates an address from common.Address +func NewAddressFromCommon(address common.Address) *Address { + hex := hexutil.Encode(address[:]) + return NewAddress(hex) +} + // String implements the interface stringer func (address *Address) String() string { return string(*address)