Skip to content

Instantly share code, notes, and snippets.

@kennethhutw
Last active July 19, 2021 10:26
Show Gist options
  • Save kennethhutw/d085a261c7f5a84351621d765754cd01 to your computer and use it in GitHub Desktop.
Save kennethhutw/d085a261c7f5a84351621d765754cd01 to your computer and use it in GitHub Desktop.
recover
const sigUtil = require('eth-sig-util');
var messageHashx = new Buffer(delegationHash)
const msgParams = { data: messageHashx }
const _signature = sigUtil.personalSign(new Buffer(tokenholder.pk, "hex"),msgParams);
console.log("_signature", _signature);
msgParams.sig = _signature
console.log("recovered address ",sigUtil.recoverPersonalSignature(msgParams));
delegatedTransferOperator.methods.recover(delegationHash, _signature).call((error, result) => {
console.log("_recoverAddress", result);
});
/**
* @notice Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 0x20))
s := mload(add(sig, 0x40))
v := byte(0, mload(add(sig, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment