[Ethereum] How to generate private, public and ethereum addresses using web3.py

addressesprivate-keypublic-keypythonweb3.py

I want to know the process of generating the keys for ethereum using web3.py. How to generate the keys if I install my ether node.

from web3 import Web3, HTTPProvider, IPCProvider
web3 = Web3(HTTPProvider('http://localhost:8545'))

I configured the node. Now, what is the method to get the keys (private, public and ether address)? Please explain.

Best Answer

You can use the web3.personal.newAccount(password) method:

Generates a new account in the node’s keychain encrypted with the given passphrase. Returns the address of the created account.

py>> web3.personal.newAccount('the-passphrase')
['0xd3cda913deb6f67967b99d67acdfa1712c293601']

Note that for security purposes, nodes do not expose the private key over the json-rpc api that web3 uses. I'm not aware of a way to access your public key either.

If you want local keys instead of hosted keys, then check out: How can I generate a wallet in python?


Edit: it seems you really want both things: a local key and a hosted key at the same time. To accomplish that, you could create the key in the node and then extract it. That involves finding the file and decrypting it.

Where your keyfile is kept depends on your choice of node, OS, and configuration. I'll assume the default geth keystore folder: ~/.ethereum/keystore/

You can decrypt the keyfile using the eth-account method decrypt():

from eth_account import Account

with open('~/.ethereum/keystore/<your_keyfile_name>') as keyfile:
    keyfile_json = keyfile.read()

private_key = Account.decrypt(keyfile_json, '<you-account-password>')

# get some extra info about the private_key, like the address:
acct = Account.privateKeyToAccount(private_key)

ether_address = acct.address

You also asked about the public key, which is not an often used part of Ethereum, so there's no great API for it. You can use this non-public API, but note that these variable names could change at any time:

acct._key_obj.public_key