Web3 Recover Address – common issues and fix

signatureweb3js

I am writing a test for a function in my smart contract which attempts to verify that a message comes from the signer. I'm currently using web3.eth.accounts.sign to sign my message with the sender account. I then use the response hash (signedMessage) to recover my address.

const sender = accounts[0]

const message = web3.utils.soliditySha3('hello-world')
const signedMessage = await web3.eth.accounts.sign(message, sender)

const {signature, messageHash, v, r, s} = signedMessage

const recoveredAddress = await web3.eth.accounts.recover({
  messageHash: messageHash,
  v: v,
  r: r,
  s: s
})

console.log("sender: ", sender)
console.log("recoveredAddress: ", recoveredAddress)

This is what the terminal is outputting for my console.log:

sender:  0x627306090abaB3A6e1400e9345bC60c78a8BEf57
recoveredAddress:  0x170e85941BAeE85CFEA0cAd2EDf798DC5C287AA1

Why is the recovered address different from the sender address?

EDIT: The issue I was having was that I was using the public key to sign my message. I should have been using a private key.

Best Answer

The issue I was having was that I was using the public key to sign my message. I should have been using a private key.

Since you can't get a private key from a public key, I searched online for a private key/public key pair and hardcoded the value for my test.

Related Topic