Skip to content

Instantly share code, notes, and snippets.

@tim-br
Last active July 14, 2018 16:26
Show Gist options
  • Save tim-br/dd87172fd7167bd11da5ef3743cc90b7 to your computer and use it in GitHub Desktop.
Save tim-br/dd87172fd7167bd11da5ef3743cc90b7 to your computer and use it in GitHub Desktop.
// requires ethereumjs-util and ethers, 3rd party npm packages.
/*
Ran on macbook with these results:
10000 ran with 0 errors.
real 0m28.769s
user 0m28.301s
sys 0m0.246s
*/
var ethUtil = require('ethereumjs-util')
var ethers = require('ethers')
var ecprivkey = Buffer.from('0123456789012345678901234567890123456789012345678901234567890123', 'hex')
var pubAddr = "0x14791697260E4c9A71f18484C9f997B308e59325"
var errors = 0
var numOfTests = 10000
for(i = 0; i < numOfTests; i++){
var testMsg = Math.random().toString(36).substring(7)
//console.log(testMsg)
var hash = ethUtil.keccak(ethUtil.toBuffer(testMsg))
var signed = ethUtil.ecsign(hash, ecprivkey)
signed.r = toHexString(signed.r)
signed.s = toHexString(signed.s)
// subtract 27 so v is either 0 or 1
signed.v = (signed.v - 27)
//console.log(signed)
var recoveredAddr = ethers.SigningKey.recover(hash, signed.r, signed.s, signed.v)
//console.log(recoveredAddr)
if(recoveredAddr != pubAddr) {
errors = errors + 1
console.log("ERROR: recovered address does not match the address of the signing private key")
}
}
console.log(numOfTests + " ran with " + errors + " errors.")
// https://stackoverflow.com/questions/34309988/byte-array-to-hex-string-conversion-in-javascript
function toHexString(byteArray) {
return "0x" + Array.from(byteArray, function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment