Addresses – How to Manually Derive Address from Public Key String Using web3.py

addressespublic-keyweb3.py

Let's say I need to derive the address from a public key string.
0xbb8250cc01a0afa7dcaee987b2adda8d1b0a0bb2f7cc427bd942a98c7837364d62e6ea4728a99db39fd55a6f7474a159ca88a96b40279044a1349a2280c8cd43

According to this reply here I need to:

  1. hash it:
    I used this online hash generator because the built in Web3.sha3() function doesn't seem to return the same value for some reason and I don't know how to specify the input for the soliditySha3() function.

So the hash is now:

>>> hash = a591d48139d1f97e701cc15cb42a35c0ba7abf1aa44cfc82cdba0033779719eb

  1. Cut the first 20 characters and add 0x prefix:

hash = "0x" + hash[24:]
=> 0xb42a35c0ba7abf1aa44cfc82cdba0033779719eb

Unfortunately this is not the correct address. The address should be 0xD4aD2c314d60089654bf292874AC0488F3ee77bA

So what's the correct way for dummies to derive the address from a public key string?

Best Answer

Take a look here: Mastering Ethereum - Keys and Addresses. This chapter walks step by step through the process for deriving the public key.

I think the main issue is that the online encoder is not expecting a hex input. Try using web3.js which seems to work perfectly:

key = "0xbb8250cc01a0afa7dcaee987b2adda8d1b0a0bb2f7cc427bd942a98c7837364d62e6ea4728a99db39fd55a6f7474a159ca88a96b40279044a1349a2280c8cd43"

"0xbb8250cc01a0afa7dcaee987b2adda8d1b0a0bb2f7cc427bd942a98c7837364d62e6ea4728a99db39fd55a6f7474a159ca88a96b40279044a1349a2280c8cd43"

hash = web3.utils.keccak256(key)

"0x31e2c58dcae613b45af300b1d4ad2c314d60089654bf292874ac0488f3ee77ba"

address = "0x" + hash.slice(24+2)

"0xd4ad2c314d60089654bf292874ac0488f3ee77ba"

EDIT: Web3.py works the same for me too

>>> key = "0xbb8250cc01a0afa7dcaee987b2adda8d1b0a0bb2f7cc427bd942a98c7837364d62e6ea4728a99db39fd55a6f7474a159ca88a96b40279044a1349a2280c8cd43"
>>> hash = Web3.sha3(hexstr=key)
>>> address = Web3.toHex(hash[-20:])
>>> address

'0xd4ad2c314d60089654bf292874ac0488f3ee77ba'

Related Topic