简体   繁体   中英

How can I create eth account via go-ethereum?

I'm running local ethereum node on my localhost on http://127.0.0.1:7545 (using ganache). I create a new account with keystore as below snippet. But, how can my local ethereum node can be aware of that new account? Normally, I can get balances, transactions etc... But I couldn't achieve to awareness of new account and managing them over my network via go-ethereum SDK.

func CreateAccount() {
    password := "secret"

    ks := keystore.NewKeyStore("./wallets", keystore.StandardScryptN, keystore.StandardScryptP)

    account, err := ks.NewAccount(password)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(account.Address.Hex())
}

In order to make go-ethereum talk to your Ganache client, you need to call Dial , which accepts a provider URL. In the case described, that would be done as follows:

client, err := ethclient.Dial("http://localhost:7545")
if err != nil {
  log.Fatal(err)
}

So all together, you would have something like this along with what you are trying to accomplish in creating a new account and having Ganache see it:

func main() {
    client, err := ethclient.Dial("http://localhost:7545")
    if err != nil {
        log.fatal(err)
    }

    fmt.Println("we have a connection")
}

func CreateAccount() {
    ks := keystore.NewKeyStore("./wallets", keystore.StandardScryptN, keystore.StandardScryptP)
    password := "secret"
    account, err := ks.NewAccount(password)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(account.Address.Hex())
}

A really great reference for all things go-ethereum is https://goethereumbook.org which walks through this and more step-by-step with full code examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM