eth-sig-util icon indicating copy to clipboard operation
eth-sig-util copied to clipboard

simple question: about signature

Open LuozhuZhang opened this issue 2 years ago • 0 comments

The signature of the metamask is done by personal_sign RPC?

Or do you implement a personal_sign yourself, and call this function when all users login dapps?

Why do I see that the front-end application is calling web3.js

var from = web3.eth.accounts[0];

var params = [from, msgParams];
var method = 'eth_signTypedData_v4';

web3.currentProvider.sendAsync(
  {
    method,
    params,
    from,
  },
  function (err, result) {
    const recovered = sigUtil.recoverTypedSignature_v4({
      data: JSON.parse(msgParams),
      sig: result.result,
    });

    if (
      ethUtil.toChecksumAddress(recovered) === ethUtil.toChecksumAddress(from)
    ) {
      alert('Successfully recovered signer as ' + from);
    } else {
      alert(
        'Failed to verify signer when comparing ' + result + ' to ' + from
      );
    }
  }
);

But in the eth-sig-util library, metamask itself implements the signature method

/**
 * Create an Ethereum-specific signature for a message.
 *
 * This function is equivalent to the `eth_sign` Ethereum JSON-RPC method as specified in EIP-1417,
 * as well as the MetaMask's `personal_sign` method.
 *
 * @param options - The personal sign options.
 * @param options.privateKey - The key to sign with.
 * @param options.data - The hex data to sign.
 * @returns The '0x'-prefixed hex encoded signature.
 */
export function personalSign({
  privateKey,
  data,
}: {
  privateKey: Buffer;
  data: unknown;
}): string {
  if (isNullish(data)) {
    throw new Error('Missing data parameter');
  } else if (isNullish(privateKey)) {
    throw new Error('Missing privateKey parameter');
  }

  const message = legacyToBuffer(data);
  const msgHash = hashPersonalMessage(message);
  const sig = ecsign(msgHash, privateKey);
  const serialized = concatSig(toBuffer(sig.v), sig.r, sig.s);
  return serialized;
}

LuozhuZhang avatar Jun 09 '22 11:06 LuozhuZhang