[Ethereum] How to create a local account from an external private key in Web3.py

dappsethereum-wallet-dappweb3.py

I've been using local_account = w3.eth.account.create(keys['private_key_1']) to create a local account offline. When I check the public key returned from local_account.address it does not match the existing public key. What should I do?

P.S. The key returned is a string & I've tried changing the private key format from "0x12345" to "12345". I think this is a solution but I can't figure out how to instantiate the class and call the from_key method.

Best Answer

That's because the attribute of the function w3.eth.account.create(...) is not the private key.

To generate an account from an external private key you must use the function w3.eth.account.privateKeyToAccount(...).

Example:

>>> private_key = "f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315"
>>> acct = w3.eth.account.privateKeyToAccount(private_key)
>>> acct.address
'0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9'

privateKeyToAccount will be deprecated for version 0.5 and replaced by w3.eth.account.from_key(...).

Example:

>>> private_key = 0xf8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315
>>> acct = Account.from_key(private_key)
>>> acct.address
'0x001d3F1ef827552Ae1114027BD3ECF1f086bA0F9'