[Ethereum] Get address from public key in Solidity

addressesassemblypublic-key

The address is the last 20 bytes of sha3(publicKey)

In Solidity, using assembly if needed, how could I splice the first 12 bytes from sha3(publicKey) and get the address? What I came up with runs out of gas:

bytes32 b = sha3(publicKey)
address signer;
assembly {
signer := mload(add(b, 0x0c) // skip the first 12 bytes, 0c in hex = 12
}

MLOAD(0XAB) loads the word (32 byte) located at the memory address 0XAB. Does my function fail because it is trying to load 20 byte only? Can MLOAD load only 20 byte?

Best Answer

This works:

return address(keccak256(publicKey) & (2**(8*21)-1));

2**(8*21)-1 is just a trick to get 0xFFFFFF... (40 Fs) without typing it. :-)

EDIT

As pointed out by @schnorr, there's no need for the mask:

return address(keccak256(publicKey));
Related Topic