forked from sogoiii/ecrecover-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (52 loc) · 1.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
const contract = require('truffle-contract')
const Web3 = require('web3')
const provider = new Web3.providers.HttpProvider('http://localhost:8545')
const web3 = new Web3(provider)
const VerifierArtifact = require('./build/contracts/Verifier')
const Verifier = contract(VerifierArtifact)
Verifier.setProvider(provider)
function toHex(str) {
var hex = '';
for(var i=0;i<str.length;i++) {
hex += ''+str.charCodeAt(i).toString(16);
}
return hex;
}
const addr = web3.eth.accounts[0]
const msg = 'school bus'
const hex_msg = '0x' + toHex(msg)
let signature = web3.eth.sign(addr, hex_msg)
console.log(`address -----> ${addr}`)
console.log(`msg ---------> ${msg}`)
console.log(`hex(msg) ----> ${hex_msg}`)
console.log(`sig ---------> ${signature}`)
signature = signature.substr(2);
const r = '0x' + signature.slice(0, 64)
const s = '0x' + signature.slice(64, 128)
const v = '0x' + signature.slice(128, 130)
const v_decimal = web3.toDecimal(v)
console.log(`r -----------> ${r}`)
console.log(`s -----------> ${s}`)
console.log(`v -----------> ${v}`)
console.log(`vd ----------> ${v_decimal}`)
Verifier
.deployed()
.then(instance => {
const fixed_msg = `\x19Ethereum Signed Message:\n${msg.length}${msg}`
const fixed_msg_sha = web3.sha3(fixed_msg)
return instance.recoverAddr.call(
fixed_msg_sha,
v_decimal,
r,
s
)
})
.then(data => {
console.log('-----data------')
console.log(`input addr ==> ${addr}`)
console.log(`output addr => ${data}`)
})
.catch(e => {
console.log('i got an error')
console.log(e)
})