This repository has been archived by the owner on Feb 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
73 lines (64 loc) · 2.11 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
60
61
62
63
64
65
66
67
68
69
70
71
72
import ethUtil from 'ethereumjs-util';
import EthereumTx from 'ethereumjs-tx';
import HookedWalletSubprovider from 'web3-provider-engine/subproviders/hooked-wallet';
/*
* Ethereum wallet provider that user pustom private key server for signing
* No keys are stored client side
* @constructor
* @param {string} baseUrl - Base URL of the private key server
* @param {string} jwt - JSON Web Token used to authenticate user
*/
function ServerWalletProvider(baseUrl, jwt) {
return new HookedWalletSubprovider({
/*
* Fetches user ethereum account
*/
getAccounts: async (cb) => {
const address = await (await fetch(`${baseUrl}/api/address`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `JWT ${jwt}`,
},
})).text();
cb(null, [address]);
},
/*
* Signs transaction
* If chainId is provided - uses EIP155 pro prevent replay attacks
* If not - falls back to normal signature scheme
*/
signTransaction: async (txParams, cb) => {
const tx = new EthereumTx(txParams);
let txFields = tx.raw.slice(0, 6);
if (txParams.chainId) {
// EIP 155
txFields = txFields.concat([new Buffer([txParams.chainId]),
new Buffer([]),
new Buffer([])]);
}
const serializedUnsignedTx = ethUtil.rlp.encode(txFields).toString('hex');
const signed = await fetch(`${baseUrl}/api/sign`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `JWT ${jwt}`,
},
body: JSON.stringify({ message: serializedUnsignedTx }),
});
const body = await signed.json();
let v = parseInt(body.v, 16);
if (txParams.chainId) {
// EIP 155
v += (txParams.chainId * 2) + 8;
}
// Fill in signature fields
tx.v = new Buffer([v]);
tx.r = new Buffer(body.r, 'hex');
tx.s = new Buffer(body.s, 'hex');
// Return signed serialized tx
cb(null, `0x${tx.serialize().toString('hex')}`);
},
});
}
export default ServerWalletProvider;