Add CreateAccount RPC function (#1330) (#1334)

This commit is contained in:
Adam Babik 2018-12-28 12:37:22 +01:00 committed by GitHub
parent 30dbacdcca
commit fa97e6927d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 66 additions and 0 deletions

23
account/address.go Normal file
View File

@ -0,0 +1,23 @@
package account
import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
)
func CreateAddress() (address, pubKey, privKey string, err error) {
key, err := crypto.GenerateKey()
if err != nil {
return "", "", "", err
}
privKeyBytes := crypto.FromECDSA(key)
pubKeyBytes := crypto.FromECDSAPub(&key.PublicKey)
addressBytes := crypto.PubkeyToAddress(key.PublicKey)
privKey = hexutil.Encode(privKeyBytes)
pubKey = hexutil.Encode(pubKeyBytes)
address = addressBytes.Hex()
return
}

24
account/address_test.go Normal file
View File

@ -0,0 +1,24 @@
package account
import (
"testing"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/stretchr/testify/require"
)
func TestCreateAddress(t *testing.T) {
addr, pub, priv, err := CreateAddress()
require.NoError(t, err)
require.Equal(t, gethcommon.IsHexAddress(addr), true)
privECDSA, err := crypto.HexToECDSA(priv[2:])
require.NoError(t, err)
pubECDSA := privECDSA.PublicKey
expectedPubStr := hexutil.Encode(crypto.FromECDSAPub(&pubECDSA))
require.Equal(t, expectedPubStr, pub)
}

View File

@ -3,6 +3,9 @@ package status
import (
"context"
"errors"
"fmt"
"github.com/status-im/status-go/account"
)
// PublicAPI represents a set of APIs from the `web3.status` namespace.
@ -65,3 +68,19 @@ func (api *PublicAPI) Signup(context context.Context, req SignupRequest) (res Si
return
}
// CreateAddressResponse : json response returned by status_createaccount
type CreateAddressResponse struct {
Address string `json:"address"`
Pubkey string `json:"pubkey"`
Privkey string `json:"privkey"`
}
// CreateAddress is an implementation of `status_createaccount` or `web3.status.createaccount` API
func (api *PublicAPI) CreateAddress(context context.Context) (res CreateAddressResponse, err error) {
if res.Address, res.Pubkey, res.Privkey, err = account.CreateAddress(); err != nil {
err = fmt.Errorf("could not create an address: %v", err)
}
return
}