forked from ethereumjs/ethereumjs-wallet
-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
400 lines (323 loc) · 12.5 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
var ethUtil = require('ethereumjs-util')
var crypto = require('crypto')
var scryptsy = require('scrypt.js')
var uuid = require('uuid')
var bs58check = require('bs58check')
function assert (val, msg) {
if (!val) {
throw new Error(msg || 'Assertion failed')
}
}
function decipherBuffer (decipher, data) {
return Buffer.concat([ decipher.update(data), decipher.final() ])
}
var Wallet = function (priv, pub) {
if (priv && pub) {
throw new Error('Cannot supply both a private and a public key to the constructor')
}
if (priv && !ethUtil.isValidPrivate(priv)) {
throw new Error('Private key does not satisfy the curve requirements (ie. it is invalid)')
}
if (pub && !ethUtil.isValidPublic(pub)) {
throw new Error('Invalid public key')
}
this._privKey = priv
this._pubKey = pub
}
Object.defineProperty(Wallet.prototype, 'privKey', {
get: function () {
assert(this._privKey, 'This is a public key only wallet')
return this._privKey
}
})
Object.defineProperty(Wallet.prototype, 'pubKey', {
get: function () {
if (!this._pubKey) {
this._pubKey = ethUtil.privateToPublic(this.privKey)
}
return this._pubKey
}
})
Wallet.generate = async function (icapDirect) {
if (icapDirect) {
while (true) {
var privKey = await window.randomBytes(32)
if (ethUtil.privateToAddress(privKey)[0] === 0) {
return new Wallet(privKey)
}
}
} else {
return new Wallet(await window.randomBytes(32))
}
}
Wallet.generateVanityAddress = async function (pattern) {
if (typeof pattern !== 'object') {
pattern = new RegExp(pattern)
}
while (true) {
var privKey = await window.randomBytes(32)
var address = ethUtil.privateToAddress(privKey)
if (pattern.test(address.toString('hex'))) {
return new Wallet(privKey)
}
}
}
Wallet.prototype.getPrivateKey = function () {
return this.privKey
}
Wallet.prototype.getPrivateKeyString = function () {
return ethUtil.bufferToHex(this.getPrivateKey())
}
Wallet.prototype.getPublicKey = function () {
return this.pubKey
}
Wallet.prototype.getPublicKeyString = function () {
return ethUtil.bufferToHex(this.getPublicKey())
}
Wallet.prototype.getAddress = function () {
return ethUtil.publicToAddress(this.pubKey)
}
Wallet.prototype.getAddressString = function () {
return ethUtil.bufferToHex(this.getAddress())
}
Wallet.prototype.getChecksumAddressString = function () {
return ethUtil.toChecksumAddress(this.getAddressString())
}
// https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition
Wallet.prototype.toV3 = async function (password, opts) {
assert(this._privKey, 'This is a public key only wallet')
opts = opts || {}
var salt = opts.salt || await window.randomBytes(32)
var iv = opts.iv || await window.randomBytes(16)
var derivedKey
var kdf = opts.kdf || 'scrypt'
var kdfparams = {
dklen: opts.dklen || 32,
salt: salt.toString('hex')
}
if (kdf === 'pbkdf2') {
kdfparams.c = opts.c || 262144
kdfparams.prf = 'hmac-sha256'
derivedKey = crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256')
} else if (kdf === 'scrypt') {
// FIXME: support progress reporting callback
kdfparams.n = opts.n || 262144
kdfparams.r = opts.r || 8
kdfparams.p = opts.p || 1
derivedKey = Buffer.from(await window.scryptsy(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen))
} else {
throw new Error('Unsupported kdf')
}
var cipher = crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv)
if (!cipher) {
throw new Error('Unsupported cipher')
}
var ciphertext = Buffer.concat([ cipher.update(this.privKey), cipher.final() ])
var mac = ethUtil.sha3(Buffer.concat([ derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex') ]))
return {
version: 3,
id: uuid.v4({ random: opts.uuid || await window.randomBytes(16) }),
address: this.getAddress().toString('hex'),
crypto: {
ciphertext: ciphertext.toString('hex'),
cipherparams: {
iv: iv.toString('hex')
},
cipher: opts.cipher || 'aes-128-ctr',
kdf: kdf,
kdfparams: kdfparams,
mac: mac.toString('hex')
}
}
}
Wallet.toCryptoMemCode = async function (code, password, opts) {
opts = opts || {}
var salt = opts.salt || await window.randomBytes(32)
var iv = opts.iv || await window.randomBytes(16)
var derivedKey
var kdf = opts.kdf || 'scrypt'
var kdfparams = {
dklen: opts.dklen || 32,
salt: salt.toString('hex')
}
if (kdf === 'pbkdf2') {
kdfparams.c = opts.c || 262144
kdfparams.prf = 'hmac-sha256'
derivedKey = crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256')
} else if (kdf === 'scrypt') {
// FIXME: support progress reporting callback
kdfparams.n = opts.n || 262144
kdfparams.r = opts.r || 8
kdfparams.p = opts.p || 1
derivedKey = Buffer.from(await window.scryptsy(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen))
} else {
throw new Error('Unsupported kdf')
}
var cipher = crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv)
if (!cipher) {
throw new Error('Unsupported cipher')
}
var ciphertext = Buffer.concat([ cipher.update(code), cipher.final() ])
var mac = ethUtil.sha3(Buffer.concat([ derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex') ]))
return {
version: 3,
id: uuid.v4({ random: opts.uuid || await window.randomBytes(16) }),
crypto: {
ciphertext: ciphertext.toString('hex'),
cipherparams: {
iv: iv.toString('hex')
},
cipher: opts.cipher || 'aes-128-ctr',
kdf: kdf,
kdfparams: kdfparams,
mac: mac.toString('hex')
}
}
}
Wallet.prototype.getV3Filename = function (timestamp) {
/*
* We want a timestamp like 2016-03-15T17-11-33.007598288Z. Date formatting
* is a pain in Javascript, everbody knows that. We could use moment.js,
* but decide to do it manually in order to save space.
*
* toJSON() returns a pretty close version, so let's use it. It is not UTC though,
* but does it really matter?
*
* Alternative manual way with padding and Date fields: http://stackoverflow.com/a/7244288/4964819
*
*/
var ts = timestamp ? new Date(timestamp) : new Date()
return [
'UTC--',
ts.toJSON().replace(/:/g, '-'),
'--',
this.getAddress().toString('hex')
].join('')
}
Wallet.prototype.toV3String = function (password, opts) {
return JSON.stringify(this.toV3(password, opts))
}
Wallet.fromPublicKey = function (pub, nonStrict) {
if (nonStrict) {
pub = ethUtil.importPublic(pub)
}
return new Wallet(null, pub)
}
Wallet.fromExtendedPublicKey = function (pub) {
assert(pub.slice(0, 4) === 'xpub', 'Not an extended public key')
pub = bs58check.decode(pub).slice(45)
// Convert to an Ethereum public key
return Wallet.fromPublicKey(pub, true)
}
Wallet.fromPrivateKey = function (priv) {
return new Wallet(priv)
}
Wallet.fromExtendedPrivateKey = function (priv) {
assert(priv.slice(0, 4) === 'xprv', 'Not an extended private key')
var tmp = bs58check.decode(priv)
assert(tmp[45] === 0, 'Invalid extended private key')
return Wallet.fromPrivateKey(tmp.slice(46))
}
// https://github.com/ethereum/go-ethereum/wiki/Passphrase-protected-key-store-spec
Wallet.fromV1 = async function (input, password) {
assert(typeof password === 'string')
var json = (typeof input === 'object') ? input : JSON.parse(input)
if (json.Version !== '1') {
throw new Error('Not a V1 wallet')
}
if (json.Crypto.KeyHeader.Kdf !== 'scrypt') {
throw new Error('Unsupported key derivation scheme')
}
var kdfparams = json.Crypto.KeyHeader.KdfParams
var derivedKey = Buffer.from(await window.scryptsy(new Buffer(password), new Buffer(json.Crypto.Salt, 'hex'), kdfparams.N, kdfparams.R, kdfparams.P, kdfparams.DkLen))
var ciphertext = new Buffer(json.Crypto.CipherText, 'hex')
var mac = ethUtil.sha3(Buffer.concat([ derivedKey.slice(16, 32), ciphertext ]))
if (mac.toString('hex') !== json.Crypto.MAC) {
throw new Error('Key derivation failed - possibly wrong passphrase')
}
var decipher = crypto.createDecipheriv('aes-128-cbc', ethUtil.sha3(derivedKey.slice(0, 16)).slice(0, 16), new Buffer(json.Crypto.IV, 'hex'))
var seed = decipherBuffer(decipher, ciphertext)
return new Wallet(seed)
}
Wallet.fromV3 = async function (input, password, nonStrict) {
assert(typeof password === 'string')
var json = (typeof input === 'object') ? input : JSON.parse(nonStrict ? input.toLowerCase() : input)
if (json.version !== 3) {
throw new Error('Not a V3 wallet')
}
var derivedKey
var kdfparams
if (json.crypto.kdf === 'scrypt') {
kdfparams = json.crypto.kdfparams
// FIXME: support progress reporting callback
derivedKey = Buffer.from(await window.scryptsy(new Buffer(password), new Buffer(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 = crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256')
} else {
throw new Error('Unsupported key derivation scheme')
}
var ciphertext = new Buffer(json.crypto.ciphertext, 'hex')
var mac = ethUtil.sha3(Buffer.concat([ derivedKey.slice(16, 32), ciphertext ]))
if (mac.toString('hex') !== json.crypto.mac) {
throw new Error('Key derivation failed - possibly wrong passphrase')
}
var decipher = crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'))
var seed = decipherBuffer(decipher, ciphertext, 'hex')
return new Wallet(seed)
}
Wallet.toDecryptedMemCode = async function (input, password, nonStrict) {
assert(typeof password === 'string')
var json = (typeof input === 'object') ? input : JSON.parse(nonStrict ? input.toLowerCase() : input)
if (json.version !== 3) {
throw new Error('Not a V3 wallet')
}
var derivedKey
var kdfparams
if (json.crypto.kdf === 'scrypt') {
kdfparams = json.crypto.kdfparams
// FIXME: support progress reporting callback
derivedKey = Buffer.from(await window.scryptsy(new Buffer(password), new Buffer(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 = crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256')
} else {
throw new Error('Unsupported key derivation scheme')
}
var ciphertext = new Buffer(json.crypto.ciphertext, 'hex')
var mac = ethUtil.sha3(Buffer.concat([ derivedKey.slice(16, 32), ciphertext ]))
if (mac.toString('hex') !== json.crypto.mac) {
throw new Error('Key derivation failed - possibly wrong passphrase')
}
var decipher = crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'))
var seed = decipherBuffer(decipher, ciphertext, 'hex')
return seed.toString()
}
/*
* Based on https://github.com/ethereum/pyethsaletool/blob/master/pyethsaletool.py
* JSON fields: encseed, ethaddr, btcaddr, email
*/
Wallet.fromEthSale = function (input, password) {
assert(typeof password === 'string')
var json = (typeof input === 'object') ? input : JSON.parse(input)
var encseed = new Buffer(json.encseed, 'hex')
// key derivation
var derivedKey = crypto.pbkdf2Sync(password, password, 2000, 32, 'sha256').slice(0, 16)
// seed decoding (IV is first 16 bytes)
// NOTE: crypto (derived from openssl) when used with aes-*-cbc will handle PKCS#7 padding internally
// see also http://stackoverflow.com/a/31614770/4964819
var decipher = crypto.createDecipheriv('aes-128-cbc', derivedKey, encseed.slice(0, 16))
var seed = decipherBuffer(decipher, encseed.slice(16))
var wallet = new Wallet(ethUtil.sha3(seed))
if (wallet.getAddress().toString('hex') !== json.ethaddr) {
throw new Error('Decoded key mismatch - possibly wrong passphrase')
}
return wallet
}
module.exports = Wallet