Skip to content

Commit

Permalink
new account compatible with eth (#27)
Browse files Browse the repository at this point in the history
new account compatible with eth
  • Loading branch information
wangdayong228 authored Nov 2, 2020
1 parent d6ab015 commit 8708c4a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
22 changes: 22 additions & 0 deletions account.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
package sdk

import (
"crypto/ecdsa"
crand "crypto/rand"
"encoding/hex"
"errors"
"fmt"
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 6 additions & 0 deletions types/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 8708c4a

Please sign in to comment.