forked from bitpay/bitcore-wallet-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
credentials.js
470 lines (380 loc) · 13.3 KB
/
credentials.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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
'use strict';
var $ = require('preconditions').singleton();
var _ = require('lodash');
var Bitcore = require('bitcore-lib');
var Mnemonic = require('bitcore-mnemonic');
var sjcl = require('sjcl');
var Common = require('./common');
var Constants = Common.Constants;
var Utils = Common.Utils;
var FIELDS = [
'network',
'xPrivKey',
'xPrivKeyEncrypted',
'xPubKey',
'requestPrivKey',
'requestPubKey',
'copayerId',
'publicKeyRing',
'walletId',
'walletName',
'm',
'n',
'walletPrivKey',
'personalEncryptingKey',
'sharedEncryptingKey',
'copayerName',
'externalSource',
'mnemonic',
'mnemonicEncrypted',
'entropySource',
'mnemonicHasPassphrase',
'derivationStrategy',
'account',
'compliantDerivation',
'addressType',
'hwInfo',
];
function Credentials() {
this.version = '1.0.0';
this.derivationStrategy = Constants.DERIVATION_STRATEGIES.BIP44;
this.account = 0;
};
function _checkNetwork(network) {
if (!_.includes(['livenet', 'testnet'], network)) throw new Error('Invalid network');
};
Credentials.create = function(network) {
_checkNetwork(network);
var x = new Credentials();
x.network = network;
x.xPrivKey = (new Bitcore.HDPrivateKey(network)).toString();
x.compliantDerivation = true;
x._expand();
return x;
};
var wordsForLang = {
'en': Mnemonic.Words.ENGLISH,
'es': Mnemonic.Words.SPANISH,
'ja': Mnemonic.Words.JAPANESE,
'zh': Mnemonic.Words.CHINESE,
'fr': Mnemonic.Words.FRENCH,
'it': Mnemonic.Words.ITALIAN,
};
Credentials.createWithMnemonic = function(network, passphrase, language, account, opts) {
_checkNetwork(network);
if (!wordsForLang[language]) throw new Error('Unsupported language');
$.shouldBeNumber(account);
opts = opts || {};
var m = new Mnemonic(wordsForLang[language]);
while (!Mnemonic.isValid(m.toString())) {
m = new Mnemonic(wordsForLang[language])
};
var x = new Credentials();
x.network = network;
x.account = account;
x.xPrivKey = m.toHDPrivateKey(passphrase, network).toString();
x.compliantDerivation = true;
x._expand();
x.mnemonic = m.phrase;
x.mnemonicHasPassphrase = !!passphrase;
return x;
};
Credentials.fromExtendedPrivateKey = function(xPrivKey, account, derivationStrategy, opts) {
$.shouldBeNumber(account);
$.checkArgument(_.includes(_.values(Constants.DERIVATION_STRATEGIES), derivationStrategy));
opts = opts || {};
var x = new Credentials();
x.xPrivKey = xPrivKey;
x.account = account;
x.derivationStrategy = derivationStrategy;
x.compliantDerivation = !opts.nonCompliantDerivation;
x._expand();
return x;
};
// note that mnemonic / passphrase is NOT stored
Credentials.fromMnemonic = function(network, words, passphrase, account, derivationStrategy, opts) {
_checkNetwork(network);
$.shouldBeNumber(account);
$.checkArgument(_.includes(_.values(Constants.DERIVATION_STRATEGIES), derivationStrategy));
opts = opts || {};
var m = new Mnemonic(words);
var x = new Credentials();
x.xPrivKey = m.toHDPrivateKey(passphrase, network).toString();
x.mnemonic = words;
x.mnemonicHasPassphrase = !!passphrase;
x.account = account;
x.derivationStrategy = derivationStrategy;
x.compliantDerivation = !opts.nonCompliantDerivation;
x._expand();
return x;
};
/*
* BWC uses
* xPrivKey -> m/44'/network'/account' -> Base Address Key
* so, xPubKey is PublicKeyHD(xPrivKey.deriveChild("m/44'/network'/account'").
*
* For external sources, this derivation should be done before
* call fromExtendedPublicKey
*
* entropySource should be a HEX string containing pseudo-random data, that can
* be deterministically derived from the xPrivKey, and should not be derived from xPubKey
*/
Credentials.fromExtendedPublicKey = function(xPubKey, source, entropySourceHex, account, derivationStrategy, opts) {
$.checkArgument(entropySourceHex);
$.shouldBeNumber(account);
$.checkArgument(_.includes(_.values(Constants.DERIVATION_STRATEGIES), derivationStrategy));
opts = opts || {};
var entropyBuffer = new Buffer(entropySourceHex, 'hex');
//require at least 112 bits of entropy
$.checkArgument(entropyBuffer.length >= 14, 'At least 112 bits of entropy are needed')
var x = new Credentials();
x.xPubKey = xPubKey;
x.entropySource = Bitcore.crypto.Hash.sha256sha256(entropyBuffer).toString('hex');
x.account = account;
x.derivationStrategy = derivationStrategy;
x.externalSource = source;
x.compliantDerivation = true;
x._expand();
return x;
};
// Get network from extended private key or extended public key
Credentials._getNetworkFromExtendedKey = function(xKey) {
$.checkArgument(xKey && _.isString(xKey));
return xKey.charAt(0) == 't' ? 'testnet' : 'livenet';
};
Credentials._xPubToCopayerId = function(xpub) {
var hash = sjcl.hash.sha256.hash(xpub);
return sjcl.codec.hex.fromBits(hash);
};
Credentials.prototype._hashFromEntropy = function(prefix, length) {
$.checkState(prefix);
var b = new Buffer(this.entropySource, 'hex');
var b2 = Bitcore.crypto.Hash.sha256hmac(b, new Buffer(prefix));
return b2.slice(0, length);
};
Credentials.prototype._expand = function() {
$.checkState(this.xPrivKey || (this.xPubKey && this.entropySource));
var network = Credentials._getNetworkFromExtendedKey(this.xPrivKey || this.xPubKey);
if (this.network) {
$.checkState(this.network == network);
} else {
this.network = network;
}
if (this.xPrivKey) {
var xPrivKey = new Bitcore.HDPrivateKey.fromString(this.xPrivKey);
var deriveFn = this.compliantDerivation ? _.bind(xPrivKey.deriveChild, xPrivKey) : _.bind(xPrivKey.deriveNonCompliantChild, xPrivKey);
var derivedXPrivKey = deriveFn(this.getBaseAddressDerivationPath());
// this is the xPubKey shared with the server.
this.xPubKey = derivedXPrivKey.hdPublicKey.toString();
var requestDerivation = deriveFn(Constants.PATHS.REQUEST_KEY);
this.requestPrivKey = requestDerivation.privateKey.toString();
var pubKey = requestDerivation.publicKey;
this.requestPubKey = pubKey.toString();
this.entropySource = Bitcore.crypto.Hash.sha256(requestDerivation.privateKey.toBuffer()).toString('hex');
} else {
var seed = this._hashFromEntropy('reqPrivKey', 32);
var privKey = new Bitcore.PrivateKey(seed.toString('hex'), network);
this.requestPrivKey = privKey.toString();
this.requestPubKey = privKey.toPublicKey().toString();
}
this.personalEncryptingKey = this._hashFromEntropy('personalKey', 16).toString('base64');
this.copayerId = Credentials._xPubToCopayerId(this.xPubKey);
this.publicKeyRing = [{
xPubKey: this.xPubKey,
requestPubKey: this.requestPubKey,
}];
};
Credentials.fromObj = function(obj) {
var x = new Credentials();
_.each(FIELDS, function(k) {
x[k] = obj[k];
});
x.derivationStrategy = x.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP45;
x.addressType = x.addressType || Constants.SCRIPT_TYPES.P2SH;
x.account = x.account || 0;
$.checkState(x.xPrivKey || x.xPubKey || x.xPrivKeyEncrypted, "invalid input");
return x;
};
Credentials.prototype.toObj = function() {
var self = this;
var x = {};
_.each(FIELDS, function(k) {
x[k] = self[k];
});
return x;
};
Credentials.prototype.getBaseAddressDerivationPath = function() {
var purpose;
switch (this.derivationStrategy) {
case Constants.DERIVATION_STRATEGIES.BIP45:
return "m/45'";
case Constants.DERIVATION_STRATEGIES.BIP44:
purpose = '44';
break;
case Constants.DERIVATION_STRATEGIES.BIP48:
purpose = '48';
break;
}
var coin = (this.network == 'livenet' ? "0" : "1");
return "m/" + purpose + "'/" + coin + "'/" + this.account + "'";
};
Credentials.prototype.getDerivedXPrivKey = function(password) {
var path = this.getBaseAddressDerivationPath();
var xPrivKey = new Bitcore.HDPrivateKey(this.getKeys(password).xPrivKey, this.network);
var deriveFn = !!this.compliantDerivation ? _.bind(xPrivKey.deriveChild, xPrivKey) : _.bind(xPrivKey.deriveNonCompliantChild, xPrivKey);
return deriveFn(path);
};
Credentials.prototype.addWalletPrivateKey = function(walletPrivKey) {
this.walletPrivKey = walletPrivKey;
this.sharedEncryptingKey = Utils.privateKeyToAESKey(walletPrivKey);
};
Credentials.prototype.addWalletInfo = function(walletId, walletName, m, n, copayerName) {
this.walletId = walletId;
this.walletName = walletName;
this.m = m;
this.n = n;
if (copayerName)
this.copayerName = copayerName;
if (this.derivationStrategy == 'BIP44' && n == 1)
this.addressType = Constants.SCRIPT_TYPES.P2PKH;
else
this.addressType = Constants.SCRIPT_TYPES.P2SH;
// Use m/48' for multisig hardware wallets
if (!this.xPrivKey && this.externalSource && n > 1) {
this.derivationStrategy = Constants.DERIVATION_STRATEGIES.BIP48;
}
if (n == 1) {
this.addPublicKeyRing([{
xPubKey: this.xPubKey,
requestPubKey: this.requestPubKey,
}]);
}
};
Credentials.prototype.hasWalletInfo = function() {
return !!this.walletId;
};
Credentials.prototype.isPrivKeyEncrypted = function() {
return (!!this.xPrivKeyEncrypted) && !this.xPrivKey;
};
Credentials.prototype.encryptPrivateKey = function(password, opts) {
if (this.xPrivKeyEncrypted)
throw new Error('Private key already encrypted');
if (!this.xPrivKey)
throw new Error('No private key to encrypt');
this.xPrivKeyEncrypted = sjcl.encrypt(password, this.xPrivKey, opts);
if (!this.xPrivKeyEncrypted)
throw new Error('Could not encrypt');
if (this.mnemonic)
this.mnemonicEncrypted = sjcl.encrypt(password, this.mnemonic, opts);
delete this.xPrivKey;
delete this.mnemonic;
};
Credentials.prototype.decryptPrivateKey = function(password) {
if (!this.xPrivKeyEncrypted)
throw new Error('Private key is not encrypted');
try {
this.xPrivKey = sjcl.decrypt(password, this.xPrivKeyEncrypted);
if (this.mnemonicEncrypted) {
this.mnemonic = sjcl.decrypt(password, this.mnemonicEncrypted);
}
delete this.xPrivKeyEncrypted;
delete this.mnemonicEncrypted;
} catch (ex) {
throw new Error('Could not decrypt');
}
};
Credentials.prototype.getKeys = function(password) {
var keys = {};
if (this.isPrivKeyEncrypted()) {
$.checkArgument(password, 'Private keys are encrypted, a password is needed');
try {
keys.xPrivKey = sjcl.decrypt(password, this.xPrivKeyEncrypted);
if (this.mnemonicEncrypted) {
keys.mnemonic = sjcl.decrypt(password, this.mnemonicEncrypted);
}
} catch (ex) {
throw new Error('Could not decrypt');
}
} else {
keys.xPrivKey = this.xPrivKey;
keys.mnemonic = this.mnemonic;
}
return keys;
};
Credentials.prototype.addPublicKeyRing = function(publicKeyRing) {
this.publicKeyRing = _.clone(publicKeyRing);
};
Credentials.prototype.canSign = function() {
return (!!this.xPrivKey || !!this.xPrivKeyEncrypted);
};
Credentials.prototype.setNoSign = function() {
delete this.xPrivKey;
delete this.xPrivKeyEncrypted;
delete this.mnemonic;
delete this.mnemonicEncrypted;
};
Credentials.prototype.isComplete = function() {
if (!this.m || !this.n) return false;
if (!this.publicKeyRing || this.publicKeyRing.length != this.n) return false;
return true;
};
Credentials.prototype.hasExternalSource = function() {
return (typeof this.externalSource == "string");
};
Credentials.prototype.getExternalSourceName = function() {
return this.externalSource;
};
Credentials.prototype.getMnemonic = function() {
if (this.mnemonicEncrypted && !this.mnemonic) {
throw new Error('Credentials are encrypted');
}
return this.mnemonic;
};
Credentials.prototype.clearMnemonic = function() {
delete this.mnemonic;
delete this.mnemonicEncrypted;
};
Credentials.fromOldCopayWallet = function(w) {
function walletPrivKeyFromOldCopayWallet(w) {
// IN BWS, the master Pub Keys are not sent to the server,
// so it is safe to use them as seed for wallet's shared secret.
var seed = w.publicKeyRing.copayersExtPubKeys.sort().join('');
var seedBuf = new Buffer(seed);
var privKey = new Bitcore.PrivateKey.fromBuffer(Bitcore.crypto.Hash.sha256(seedBuf));
return privKey.toString();
};
var credentials = new Credentials();
credentials.derivationStrategy = Constants.DERIVATION_STRATEGIES.BIP45;
credentials.xPrivKey = w.privateKey.extendedPrivateKeyString;
credentials._expand();
credentials.addWalletPrivateKey(walletPrivKeyFromOldCopayWallet(w));
credentials.addWalletInfo(w.opts.id, w.opts.name, w.opts.requiredCopayers, w.opts.totalCopayers)
var pkr = _.map(w.publicKeyRing.copayersExtPubKeys, function(xPubStr) {
var isMe = xPubStr === credentials.xPubKey;
var requestDerivation;
if (isMe) {
var path = Constants.PATHS.REQUEST_KEY;
requestDerivation = (new Bitcore.HDPrivateKey(credentials.xPrivKey))
.deriveChild(path).hdPublicKey;
} else {
// this
var path = Constants.PATHS.REQUEST_KEY_AUTH;
requestDerivation = (new Bitcore.HDPublicKey(xPubStr)).deriveChild(path);
}
// Grab Copayer Name
var hd = new Bitcore.HDPublicKey(xPubStr).deriveChild('m/2147483646/0/0');
var pubKey = hd.publicKey.toString('hex');
var copayerName = w.publicKeyRing.nicknameFor[pubKey];
if (isMe) {
credentials.copayerName = copayerName;
}
return {
xPubKey: xPubStr,
requestPubKey: requestDerivation.publicKey.toString(),
copayerName: copayerName,
};
});
credentials.addPublicKeyRing(pkr);
return credentials;
};
module.exports = Credentials;