ethereumjs / ethereumjs-util

Project is in active development and has been moved to the EthereumJS monorepo.
https://github.com/ethereumjs/ethereumjs-monorepo
Mozilla Public License 2.0
608 stars 274 forks source link

Recover wallet address at the server side after personal signing with metamask #107

Closed bestestlist closed 6 years ago

bestestlist commented 6 years ago

I would like to ask how to recover wallet address at the server side after personal signing with metamask. I am getting the wrong sender (wallet address) after running ecrecover. Thank you.

Client

    // Checking if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
      window.web3 = new Web3(window.web3.currentProvider);
      window.web3.eth.getAccounts().then(account_list => {
        if (account_list.length > 0) {
          const publicAddress = account_list[0];
          window.web3.eth.personal.sign('some_msg', account_list[0], '', this.postToServer);
        } else {
          console.log('no accounts');
        }
      }).catch(() => {
        console.log('err')
      })

Server

   var ethUtil = require('ethereumjs-util');

   // server receives message and signature

    let msgHash = ethUtil.hashPersonalMessage(Buffer.from(message))
    let sigParams = ethUtil.fromRpcSig(sig)
    let sender = ethUtil.ecrecover(msgHash, sigParams.v, sigParams.r, sigParams.s)

    console.log('sender: ', sender.toString());
kumavis commented 6 years ago

@bestestlist take a look at https://github.com/MetaMask/eth-sig-util

kumavis commented 6 years ago

@bestestlist is your message hex or string? if hex it may need: Buffer.from(message, 'hex')

bestestlist commented 6 years ago

Thanks @kumavis . You are the real mvp. I used that library and it worked.

var sigUtil = require('eth-sig-util')
...
const recovered = sigUtil.recoverPersonalSignature(msgParams)