1 year ago

#373981

test-img

Patrick

Are the sign/recover function of web3js and solidity (not) interchangeable?

I'm trying to verify a signature created with web3js in Solidity, but do not get the correct signer.

In web3js:

var address = '0x5B38Da6a701c568545dCfcB03FcB875f56beddC4'; // == msg.sender
var signature = web3.eth.accounts.sign(address, PRIVATE_KEY);
// check:
var signer = web3.eth.accounts.recover(signature.message, signature.signature);
console.log(signer); // == PUBLIC_KEY

In Solidity:

function verify(bytes memory signature) public view returns (address) {
    bytes32 hash = keccak256(abi.encodePacked(msg.sender));
    bytes32 messageHash = hash.toEthSignedMessageHash();
    address signer = messageHash.recover(signature);
    return signer; // != PUBLIC_KEY
}

signer in Solidity has different value than PUBLIC_KEY in web3js.

Tested by creating simple contract in Remix and calling verify() with signature from web3js. Quick check I did was that web3.utils.keccak256(address) has same value as keccak256(abi.encodePacked(msg.sender)) so address (= message signed) in web3js is same as msg.sender after hashing.

solidity

sign

web3js

recover

0 Answers

Your Answer

Accepted video resources