Last active
July 5, 2020 00:34
-
-
Save hewigovens/c3d54eaf0aa9f0b9d3998c25c92d84da to your computer and use it in GitHub Desktop.
Recover address from Ethereum message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const { utils } = require('ethers'); | |
const secp256k1 = require('secp256k1'); | |
function ethereumMessage(str) { | |
const data = Buffer.from(str, 'utf8'); | |
const prefix = Buffer.from( | |
`\u{19}Ethereum Signed Message:\n${data.length}`, | |
'utf8', | |
); | |
return Buffer.concat([prefix, data]); | |
} | |
function hexToBuffer(str) { | |
return Buffer.from(str.replace('0x', ''), 'hex'); | |
} | |
function bufferToHex(buf) { | |
return Buffer.from(buf).toString('hex'); | |
} | |
function ecRecoverTest() { | |
const data = "Some message"; | |
const message = ethereumMessage(data); | |
const hashStr = utils.keccak256(message); | |
// hash: 0x5a65edf40dec93b00ad4221fbe200e5c83006b6240f0fcf747be11b8de3d12ca | |
const hash = hexToBuffer(hashStr) | |
// signature(r,s,v) signed by Trust | |
const signatureStr = "648a6169ea6a6b164dbcd85966aa341da8f63f4df132b00345b999515c929bc22ff02224c4e6319af82921394c6e6a0c4e139ca78bdd39406aeaa2d0ca93d28e1c"; | |
const signature = hexToBuffer(signatureStr); | |
// recovery id - 27 for Ethereum | |
const recovered = secp256k1.ecdsaRecover(signature.slice(0,64), signature[64] - 27, hash, false); | |
console.log(bufferToHex(recovered)); | |
// uncompressed public key: 045ab29c3f44ee7a13302f42feff1f4f9527ddcbd0e9fb981cb9e70f8360c2b6a774959be65068c42f18cf4a921155b5c153e98892154c18f94ea36c9249d0b648 | |
const keyHash = utils.keccak256(Buffer.from(recovered).slice(1, 65)) | |
console.log(keyHash) | |
// keccak256 hash: 0x3357503474a66aac8ad61ac17d8bf18c7ce84b3e175b339c4ca93aed1dd166f1 | |
// last 20 bytes is address without checksum | |
const address = hexToBuffer(keyHash).slice(32 - 20, 32); | |
console.log('0x' + bufferToHex(address)); | |
// address: 0x7d8bf18c7ce84b3e175b339c4ca93aed1dd166f1 | |
} | |
ecRecoverTest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment