-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
EthereumAccount.js
292 lines (263 loc) · 9.26 KB
/
EthereumAccount.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/*
This file is part of web3.js.
web3.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
web3.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with web3.js. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file Account.js
* @author Samuel Furter <samuel@ethereum.org>, Fabian Vogelsteller <fabian@ethereum.org>
* @date 2019
*/
import scrypt from 'scrypt-shim';
import isString from 'lodash/isString';
import isObject from 'lodash/isObject';
import * as EthLibAccount from 'eth-lib/lib/account'; // TODO: Remove this dependency
import uuid from 'uuid';
import Hash from 'eth-lib/lib/hash';
import randomBytes from 'randombytes';
import {pbkdf2Sync} from 'pbkdf2';
import {createCipheriv, createDecipheriv} from 'browserify-cipher';
import {isHexStrict, hexToBytes, randomHex, keccak256} from 'web3-utils'; // TODO: Use the VO's of a web3-types module.
export default class Account {
/**
* @param {Object} options TODO: Pass a Address VO in the options
* @param {Accounts} accounts
*
* @constructor
*/
constructor(options, accounts = null) {
this.address = options.address;
this.privateKey = options.privateKey;
this.nonce = options.nonce;
this.accounts = accounts;
}
/**
* TODO: Add deprecation message, remove accounts dependency and extend the signTransaction method in the eth module.
* Signs a transaction object with the given privateKey
*
* @method signTransaction
*
* @param {Object} tx
*
* @returns {Promise<Object>}
*/
signTransaction(tx) {
return this.accounts.signTransaction(tx, this.privateKey);
}
/**
* This method does sign a given string with the current account.
*
* @method sign
*
* @param {String} data
*
* @returns {String}
*/
sign(data) {
if (isHexStrict(data)) {
data = hexToBytes(data);
}
const messageBuffer = Buffer.from(data);
const preamble = `\u0019Ethereum Signed Message:\n${data.length}`;
const preambleBuffer = Buffer.from(preamble);
const ethMessage = Buffer.concat([preambleBuffer, messageBuffer]);
const hash = Hash.keccak256s(ethMessage);
const signature = EthLibAccount.sign(hash, this.privateKey);
const vrs = EthLibAccount.decodeSignature(signature);
return {
message: data,
messageHash: hash,
v: vrs[0],
r: vrs[1],
s: vrs[2],
signature
};
}
/**
* This methods returns the EncryptedKeystoreV3Json object from the current account.
*
* @param {String} password
* @param {Object} options
*
* @returns {EncryptedKeystoreV3Json | {version, id, address, crypto}}
*/
encrypt(password, options) {
return Account.fromPrivateKey(this.privateKey, this.accounts).toV3Keystore(password, options);
}
/**
* This static methods gives us the possibility to create a new account.
*
* @param {String} entropy
* @param {Accounts} accounts
*
* @returns {Account}
*/
static from(entropy, accounts = {}) {
return new Account(EthLibAccount.create(entropy || randomHex(32)), accounts);
}
/**
* This static method gives us the possibility to create a Account object from a private key.
*
* @param {String} privateKey
* @param {Accounts} accounts
*
* @returns {Account}
*/
static fromPrivateKey(privateKey, accounts = {}) {
if (!privateKey.startsWith('0x')) {
privateKey = '0x' + privateKey;
}
// 64 hex characters + hex-prefix
if (privateKey.length !== 66) {
throw new Error('Private key must be 32 bytes long');
}
return new Account(EthLibAccount.fromPrivate(privateKey), accounts);
}
/**
* This method will map the current Account object to V3Keystore object.
*
* @method toV3Keystore
*
* @param {String} password
* @param {Object} options
*
* @returns {{version, id, address, crypto}}
*/
toV3Keystore(password, options) {
options = options || {};
const salt = options.salt || randomBytes(32);
const iv = options.iv || randomBytes(16);
let derivedKey;
const kdf = options.kdf || 'scrypt';
const kdfparams = {
dklen: options.dklen || 32,
salt: salt.toString('hex')
};
if (kdf === 'pbkdf2') {
kdfparams.c = options.c || 262144;
kdfparams.prf = 'hmac-sha256';
derivedKey = pbkdf2Sync(
Buffer.from(password),
Buffer.from(kdfparams.salt, 'hex'),
kdfparams.c,
kdfparams.dklen,
'sha256'
);
} else if (kdf === 'scrypt') {
// FIXME: support progress reporting callback
kdfparams.n = options.n || 8192; // 2048 4096 8192 16384
kdfparams.r = options.r || 8;
kdfparams.p = options.p || 1;
derivedKey = scrypt(
Buffer.from(password),
Buffer.from(kdfparams.salt, 'hex'),
kdfparams.n,
kdfparams.r,
kdfparams.p,
kdfparams.dklen
);
} else {
throw new Error('Unsupported kdf');
}
const cipher = createCipheriv(options.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
if (!cipher) {
throw new Error('Unsupported cipher');
}
const ciphertext = Buffer.concat([
cipher.update(Buffer.from(this.privateKey.replace('0x', ''), 'hex')),
cipher.final()
]);
const mac = keccak256(Buffer.concat([derivedKey.slice(16, 32), Buffer.from(ciphertext, 'hex')])).replace(
'0x',
''
);
return {
version: 3,
id: uuid.v4({random: options.uuid || randomBytes(16)}),
address: this.address.toLowerCase().replace('0x', ''),
crypto: {
ciphertext: ciphertext.toString('hex'),
cipherparams: {
iv: iv.toString('hex')
},
cipher: options.cipher || 'aes-128-ctr',
kdf,
kdfparams,
mac: mac.toString('hex')
}
};
}
/**
* TODO: Clean up this method
*
* Returns an Account object by the given V3Keystore object.
*
* Note: Taken from https://github.com/ethereumjs/ethereumjs-wallet
*
* @method fromV3Keystore
*
* @param {Object|String} v3Keystore
* @param {String} password
* @param {Boolean} nonStrict
* @param {Accounts} accounts
*
* @returns {Account}
*/
static fromV3Keystore(v3Keystore, password, nonStrict = false, accounts = {}) {
if (!isString(password)) {
throw new Error('No password given.');
}
const json = isObject(v3Keystore) ? v3Keystore : JSON.parse(nonStrict ? v3Keystore.toLowerCase() : v3Keystore);
if (json.version !== 3) {
throw new Error('Not a valid V3 wallet');
}
let derivedKey;
let kdfparams;
if (json.crypto.kdf === 'scrypt') {
kdfparams = json.crypto.kdfparams;
// FIXME: support progress reporting callback
derivedKey = scrypt(
Buffer.from(password),
Buffer.from(kdfparams.salt, 'hex'),
kdfparams.n,
kdfparams.r,
kdfparams.p,
kdfparams.dklen
);
} else if (json.crypto.kdf === 'pbkdf2') {
kdfparams = json.crypto.kdfparams;
if (kdfparams.prf !== 'hmac-sha256') {
throw new Error('Unsupported parameters to PBKDF2');
}
derivedKey = pbkdf2Sync(
Buffer.from(password),
Buffer.from(kdfparams.salt, 'hex'),
kdfparams.c,
kdfparams.dklen,
'sha256'
);
} else {
throw new Error('Unsupported key derivation scheme');
}
const ciphertext = Buffer.from(json.crypto.ciphertext, 'hex');
const mac = keccak256(Buffer.concat([derivedKey.slice(16, 32), ciphertext])).replace('0x', '');
if (mac !== json.crypto.mac) {
throw new Error('Key derivation failed - possibly wrong password');
}
const decipher = createDecipheriv(
json.crypto.cipher,
derivedKey.slice(0, 16),
Buffer.from(json.crypto.cipherparams.iv, 'hex')
);
const seed = `0x${Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('hex')}`;
return Account.fromPrivateKey(seed, accounts);
}
}