1

I've been using ecrecover and web3.eth.sign to authorize transactions, but when I run web3.eth.sign a second time on my server, the V part of the signature is wrong(or, at least, ecrecover thinks it's wrong). I read that it should be 27 or 28, but sign() is giving me 54 and 55. However, if I changes these to 27 and 28, respectively, ecrecover works again. What's going on????

exports.sign = async(signer, nonce, amount, forUser) => {
  // pack data into the message
  let ret = [];
  let data = (nonce * 2 ** 32) + amount;
  let hexData = web3.utils.toHex(data).slice(2);
  for(let i = hexData.length; i < 16; i++) {
    hexData = "0" + hexData
  }
  let message = "0x1337beef" + forUser.slice(2) + hexData;
  // sign the message
  let sig = (await web3.eth.sign(message, signer)).slice(2);
  let r = "0x" + sig.slice(0, 64);
  let s = "0x" + sig.slice(64, 128);
  let v = web3.utils.toDecimal('0x' + sig.slice(128, 130)) + 27;
  // THESE NEXT TWO LINES MAKE THINGS WORK BUT THEY
  // ARE STINKY AND I MUST KNOW WHY THEY ARE NEEDED!!
  if(v == 54) { v = 27;}
  if(v == 55) { v = 28;}
  ret.push(message);
  ret.push(v);
  ret.push(r);
  ret.push(s);
  return ret;
}

Thanks in advance!!

1

You have not provided many details of your setup. What backend node are you using? What signature is returned when you sign the message? Web3.js sign method just calls through to the nodes implementation.

As outlined in this answer, Geth previously did not return the v value in the appropriate format. You had to add 27.

I suspect from brief consideration that you are using a Parity node which returns the correct v value. You are then adding 27 unnecessarily.

Hence why your values are too high.. by 27.

  • Thanks man. This is truffle(so ganache) running on my dev machine. I didnt' realize sign() was hitting the node. The thing I should have made clearer is that this function works the first time(v = 0 + 27) and then when I run it again is when it fails(v = 27 + 27). If I restart my web server(not my node) it works again. – Clayton Rabenda Dec 21 '18 at 5:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.