This repository has been archived by the owner on Apr 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 271
/
api.js
2628 lines (2191 loc) · 72.8 KB
/
api.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var util = require('util');
var async = require('async');
var events = require('events');
var Bitcore = require('bitcore-lib');
var Bitcore_ = {
btc: Bitcore,
bch: require('bitcore-lib-cash'),
};
var Mnemonic = require('bitcore-mnemonic');
var sjcl = require('sjcl');
var url = require('url');
var querystring = require('querystring');
var Stringify = require('json-stable-stringify');
var request = require('superagent');
var Common = require('./common');
var Constants = Common.Constants;
var Defaults = Common.Defaults;
var Utils = Common.Utils;
var PayPro = require('./paypro');
var log = require('./log');
var Credentials = require('./credentials');
var Verifier = require('./verifier');
var Package = require('../package.json');
var Errors = require('./errors');
var BASE_URL = 'http://localhost:3232/bws/api';
/**
* @desc ClientAPI constructor.
*
* @param {Object} opts
* @constructor
*/
function API(opts) {
opts = opts || {};
this.request = opts.request || request;
this.baseUrl = opts.baseUrl || BASE_URL;
this.payProHttp = null; // Only for testing
this.doNotVerifyPayPro = opts.doNotVerifyPayPro;
this.timeout = opts.timeout || 50000;
this.logLevel = opts.logLevel || 'silent';
this.supportStaffWalletId = opts.supportStaffWalletId;
log.setLevel(this.logLevel);
};
util.inherits(API, events.EventEmitter);
API.privateKeyEncryptionOpts = {
iter: 10000
};
API.prototype.initNotifications = function(cb) {
log.warn('DEPRECATED: use initialize() instead.');
this.initialize({}, cb);
};
API.prototype.initialize = function(opts, cb) {
$.checkState(this.credentials);
var self = this;
self.notificationIncludeOwn = !!opts.notificationIncludeOwn;
self._initNotifications(opts);
return cb();
};
API.prototype.dispose = function(cb) {
var self = this;
self._disposeNotifications();
self._logout(cb);
};
API.prototype._fetchLatestNotifications = function(interval, cb) {
var self = this;
cb = cb || function() {};
var opts = {
lastNotificationId: self.lastNotificationId,
includeOwn: self.notificationIncludeOwn,
};
if (!self.lastNotificationId) {
opts.timeSpan = interval + 1;
}
self.getNotifications(opts, function(err, notifications) {
if (err) {
log.warn('Error receiving notifications.');
log.debug(err);
return cb(err);
}
if (notifications.length > 0) {
self.lastNotificationId = _.last(notifications).id;
}
_.each(notifications, function(notification) {
self.emit('notification', notification);
});
return cb();
});
};
API.prototype._initNotifications = function(opts) {
var self = this;
opts = opts || {};
var interval = opts.notificationIntervalSeconds || 5;
self.notificationsIntervalId = setInterval(function() {
self._fetchLatestNotifications(interval, function(err) {
if (err) {
if (err instanceof Errors.NOT_FOUND || err instanceof Errors.NOT_AUTHORIZED) {
self._disposeNotifications();
}
}
});
}, interval * 1000);
};
API.prototype._disposeNotifications = function() {
var self = this;
if (self.notificationsIntervalId) {
clearInterval(self.notificationsIntervalId);
self.notificationsIntervalId = null;
}
};
/**
* Reset notification polling with new interval
* @param {Numeric} notificationIntervalSeconds - use 0 to pause notifications
*/
API.prototype.setNotificationsInterval = function(notificationIntervalSeconds) {
var self = this;
self._disposeNotifications();
if (notificationIntervalSeconds > 0) {
self._initNotifications({
notificationIntervalSeconds: notificationIntervalSeconds
});
}
};
/**
* Encrypt a message
* @private
* @static
* @memberof Client.API
* @param {String} message
* @param {String} encryptingKey
*/
API._encryptMessage = function(message, encryptingKey) {
if (!message) return null;
return Utils.encryptMessage(message, encryptingKey);
};
API.prototype._processTxNotes = function(notes) {
var self = this;
if (!notes) return;
var encryptingKey = self.credentials.sharedEncryptingKey;
_.each([].concat(notes), function(note) {
note.encryptedBody = note.body;
note.body = Utils.decryptMessageNoThrow(note.body, encryptingKey);
note.encryptedEditedByName = note.editedByName;
note.editedByName = Utils.decryptMessageNoThrow(note.editedByName, encryptingKey);
});
};
/**
* Decrypt text fields in transaction proposals
* @private
* @static
* @memberof Client.API
* @param {Array} txps
* @param {String} encryptingKey
*/
API.prototype._processTxps = function(txps) {
var self = this;
if (!txps) return;
var encryptingKey = self.credentials.sharedEncryptingKey;
_.each([].concat(txps), function(txp) {
txp.encryptedMessage = txp.message;
txp.message = Utils.decryptMessageNoThrow(txp.message, encryptingKey) || null;
txp.creatorName = Utils.decryptMessageNoThrow(txp.creatorName, encryptingKey);
_.each(txp.actions, function(action) {
// CopayerName encryption is optional (not available in older wallets)
action.copayerName = Utils.decryptMessageNoThrow(action.copayerName, encryptingKey);
action.comment = Utils.decryptMessageNoThrow(action.comment, encryptingKey);
// TODO get copayerName from Credentials -> copayerId to copayerName
// action.copayerName = null;
});
_.each(txp.outputs, function(output) {
output.encryptedMessage = output.message;
output.message = Utils.decryptMessageNoThrow(output.message, encryptingKey) || null;
});
txp.hasUnconfirmedInputs = _.some(txp.inputs, function(input) {
return input.confirmations == 0;
});
self._processTxNotes(txp.note);
});
};
/**
* Parse errors
* @private
* @static
* @memberof Client.API
* @param {Object} body
*/
API._parseError = function(body) {
if (!body) return;
if (_.isString(body)) {
try {
body = JSON.parse(body);
} catch (e) {
body = {
error: body
};
}
}
var ret;
if (body.code) {
if (Errors[body.code]) {
ret = new Errors[body.code];
if (body.message) ret.message = body.message;
} else {
ret = new Error(body.code + ': ' + body.message);
}
} else {
ret = new Error(body.error || JSON.stringify(body));
}
log.error(ret);
return ret;
};
/**
* Sign an HTTP request
* @private
* @static
* @memberof Client.API
* @param {String} method - The HTTP method
* @param {String} url - The URL for the request
* @param {Object} args - The arguments in case this is a POST/PUT request
* @param {String} privKey - Private key to sign the request
*/
API._signRequest = function(method, url, args, privKey) {
var message = [method.toLowerCase(), url, JSON.stringify(args)].join('|');
return Utils.signMessage(message, privKey);
};
/**
* Seed from random
*
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {String} opts.network - default 'livenet'
*/
API.prototype.seedFromRandom = function(opts) {
$.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.');
$.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.');
opts = opts || {};
this.credentials = Credentials.create(opts.coin || 'btc', opts.network || 'livenet');
};
var _deviceValidated;
/**
* Seed from random
*
* @param {Object} opts
* @param {String} opts.passphrase
* @param {Boolean} opts.skipDeviceValidation
*/
API.prototype.validateKeyDerivation = function(opts, cb) {
var self = this;
opts = opts || {};
var c = self.credentials;
function testMessageSigning(xpriv, xpub) {
var nonHardenedPath = 'm/0/0';
var message = 'Lorem ipsum dolor sit amet, ne amet urbanitas percipitur vim, libris disputando his ne, et facer suavitate qui. Ei quidam laoreet sea. Cu pro dico aliquip gubergren, in mundi postea usu. Ad labitur posidonium interesset duo, est et doctus molestie adipiscing.';
var priv = xpriv.deriveChild(nonHardenedPath).privateKey;
var signature = Utils.signMessage(message, priv);
var pub = xpub.deriveChild(nonHardenedPath).publicKey;
return Utils.verifyMessage(message, signature, pub);
};
function testHardcodedKeys() {
var words = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
var xpriv = Mnemonic(words).toHDPrivateKey();
if (xpriv.toString() != 'xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu') return false;
xpriv = xpriv.deriveChild("m/44'/0'/0'");
if (xpriv.toString() != 'xprv9xpXFhFpqdQK3TmytPBqXtGSwS3DLjojFhTGht8gwAAii8py5X6pxeBnQ6ehJiyJ6nDjWGJfZ95WxByFXVkDxHXrqu53WCRGypk2ttuqncb') return false;
var xpub = Bitcore.HDPublicKey.fromString('xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj');
return testMessageSigning(xpriv, xpub);
};
function testLiveKeys() {
var words;
try {
words = c.getMnemonic();
} catch (ex) {}
var xpriv;
if (words && (!c.mnemonicHasPassphrase || opts.passphrase)) {
var m = new Mnemonic(words);
xpriv = m.toHDPrivateKey(opts.passphrase, c.network);
}
if (!xpriv) {
xpriv = new Bitcore.HDPrivateKey(c.xPrivKey);
}
xpriv = xpriv.deriveChild(c.getBaseAddressDerivationPath());
var xpub = new Bitcore.HDPublicKey(c.xPubKey);
return testMessageSigning(xpriv, xpub);
};
var hardcodedOk = true;
if (!_deviceValidated && !opts.skipDeviceValidation) {
hardcodedOk = testHardcodedKeys();
_deviceValidated = true;
}
var liveOk = (c.canSign() && !c.isPrivKeyEncrypted()) ? testLiveKeys() : true;
self.keyDerivationOk = hardcodedOk && liveOk;
return cb(null, self.keyDerivationOk);
};
/**
* Seed from random with mnemonic
*
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {String} opts.network - default 'livenet'
* @param {String} opts.passphrase
* @param {Number} opts.language - default 'en'
* @param {Number} opts.account - default 0
*/
API.prototype.seedFromRandomWithMnemonic = function(opts) {
$.checkArgument(arguments.length <= 1, 'DEPRECATED: only 1 argument accepted.');
$.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: argument should be an options object.');
opts = opts || {};
this.credentials = Credentials.createWithMnemonic(opts.coin || 'btc', opts.network || 'livenet', opts.passphrase, opts.language || 'en', opts.account || 0);
};
API.prototype.getMnemonic = function() {
return this.credentials.getMnemonic();
};
API.prototype.mnemonicHasPassphrase = function() {
return this.credentials.mnemonicHasPassphrase;
};
API.prototype.clearMnemonic = function() {
return this.credentials.clearMnemonic();
};
/**
* Seed from extended private key
*
* @param {String} xPrivKey
* @param {String} opts.coin - default 'btc'
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
*/
API.prototype.seedFromExtendedPrivateKey = function(xPrivKey, opts) {
opts = opts || {};
this.credentials = Credentials.fromExtendedPrivateKey(opts.coin || 'btc', xPrivKey, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44, opts);
};
/**
* Seed from Mnemonics (language autodetected)
* Can throw an error if mnemonic is invalid
*
* @param {String} BIP39 words
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {String} opts.network - default 'livenet'
* @param {String} opts.passphrase
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
*/
API.prototype.seedFromMnemonic = function(words, opts) {
$.checkArgument(_.isUndefined(opts) || _.isObject(opts), 'DEPRECATED: second argument should be an options object.');
opts = opts || {};
this.credentials = Credentials.fromMnemonic(opts.coin || 'btc', opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44, opts);
};
/**
* Seed from external wallet public key
*
* @param {String} xPubKey
* @param {String} source - A name identifying the source of the xPrivKey (e.g. ledger, TREZOR, ...)
* @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey.
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
*/
API.prototype.seedFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts) {
$.checkArgument(_.isUndefined(opts) || _.isObject(opts));
opts = opts || {};
this.credentials = Credentials.fromExtendedPublicKey(opts.coin || 'btc', xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44);
};
/**
* Export wallet
*
* @param {Object} opts
* @param {Boolean} opts.password
* @param {Boolean} opts.noSign
*/
API.prototype.export = function(opts) {
$.checkState(this.credentials);
opts = opts || {};
var output;
var c = Credentials.fromObj(this.credentials);
if (opts.noSign) {
c.setNoSign();
} else if (opts.password) {
c.decryptPrivateKey(opts.password);
}
output = JSON.stringify(c.toObj());
return output;
};
/**
* Import wallet
*
* @param {Object} str - The serialized JSON created with #export
*/
API.prototype.import = function(str) {
try {
var credentials = Credentials.fromObj(JSON.parse(str));
this.credentials = credentials;
} catch (ex) {
throw new Errors.INVALID_BACKUP;
}
};
API.prototype._import = function(cb) {
$.checkState(this.credentials);
var self = this;
// First option, grab wallet info from BWS.
self.openWallet(function(err, ret) {
// it worked?
if (!err) return cb(null, ret);
// Is the error other than "copayer was not found"? || or no priv key.
if (err instanceof Errors.NOT_AUTHORIZED || self.isPrivKeyExternal())
return cb(err);
//Second option, lets try to add an access
log.info('Copayer not found, trying to add access');
self.addAccess({}, function(err) {
if (err) {
return cb(new Errors.WALLET_DOES_NOT_EXIST);
}
self.openWallet(cb);
});
});
};
/**
* Import from Mnemonics (language autodetected)
* Can throw an error if mnemonic is invalid
*
* @param {String} BIP39 words
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {String} opts.network - default 'livenet'
* @param {String} opts.passphrase
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
* @param {String} opts.entropySourcePath - Only used if the wallet was created on a HW wallet, in which that private keys was not available for all the needed derivations
* @param {String} opts.walletPrivKey - if available, walletPrivKey for encrypting metadata
*/
API.prototype.importFromMnemonic = function(words, opts, cb) {
log.debug('Importing from 12 Words');
var self = this;
opts = opts || {};
function derive(nonCompliantDerivation) {
return Credentials.fromMnemonic(opts.coin || 'btc', opts.network || 'livenet', words, opts.passphrase, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44, {
nonCompliantDerivation: nonCompliantDerivation,
entropySourcePath: opts.entropySourcePath,
walletPrivKey: opts.walletPrivKey,
});
};
try {
self.credentials = derive(false);
} catch (e) {
log.info('Mnemonic error:', e);
return cb(new Errors.INVALID_BACKUP);
}
self._import(function(err, ret) {
if (!err) return cb(null, ret);
if (err instanceof Errors.INVALID_BACKUP) return cb(err);
if (err instanceof Errors.NOT_AUTHORIZED || err instanceof Errors.WALLET_DOES_NOT_EXIST) {
var altCredentials = derive(true);
if (altCredentials.xPubKey.toString() == self.credentials.xPubKey.toString()) return cb(err);
self.credentials = altCredentials;
return self._import(cb);
}
return cb(err);
});
};
/*
* Import from extended private key
*
* @param {String} xPrivKey
* @param {String} opts.coin - default 'btc'
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
* @param {String} opts.compliantDerivation - default 'true'
* @param {String} opts.walletPrivKey - if available, walletPrivKey for encrypting metadata
* @param {Callback} cb - The callback that handles the response. It returns a flag indicating that the wallet is imported.
*/
API.prototype.importFromExtendedPrivateKey = function(xPrivKey, opts, cb) {
log.debug('Importing from Extended Private Key');
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: importFromExtendedPrivateKey should receive 3 parameters.');
}
try {
this.credentials = Credentials.fromExtendedPrivateKey(opts.coin || 'btc', xPrivKey, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44, opts);
} catch (e) {
log.info('xPriv error:', e);
return cb(new Errors.INVALID_BACKUP);
};
this._import(cb);
};
/**
* Import from Extended Public Key
*
* @param {String} xPubKey
* @param {String} source - A name identifying the source of the xPrivKey
* @param {String} entropySourceHex - A HEX string containing pseudo-random data, that can be deterministically derived from the xPrivKey, and should not be derived from xPubKey.
* @param {Object} opts
* @param {String} opts.coin - default 'btc'
* @param {Number} opts.account - default 0
* @param {String} opts.derivationStrategy - default 'BIP44'
* @param {String} opts.compliantDerivation - default 'true'
*/
API.prototype.importFromExtendedPublicKey = function(xPubKey, source, entropySourceHex, opts, cb) {
$.checkArgument(arguments.length == 5, "DEPRECATED: should receive 5 arguments");
$.checkArgument(_.isUndefined(opts) || _.isObject(opts));
$.shouldBeFunction(cb);
opts = opts || {};
log.debug('Importing from Extended Private Key');
try {
this.credentials = Credentials.fromExtendedPublicKey(opts.coin || 'btc', xPubKey, source, entropySourceHex, opts.account || 0, opts.derivationStrategy || Constants.DERIVATION_STRATEGIES.BIP44, opts);
} catch (e) {
log.info('xPriv error:', e);
return cb(new Errors.INVALID_BACKUP);
};
this._import(cb);
};
API.prototype.decryptBIP38PrivateKey = function(encryptedPrivateKeyBase58, passphrase, opts, cb) {
var Bip38 = require('bip38');
var bip38 = new Bip38();
var privateKeyWif;
try {
privateKeyWif = bip38.decrypt(encryptedPrivateKeyBase58, passphrase);
} catch (ex) {
return cb(new Error('Could not decrypt BIP38 private key', ex));
}
var privateKey = new Bitcore.PrivateKey(privateKeyWif);
var address = privateKey.publicKey.toAddress().toString();
var addrBuff = new Buffer(address, 'ascii');
var actualChecksum = Bitcore.crypto.Hash.sha256sha256(addrBuff).toString('hex').substring(0, 8);
var expectedChecksum = Bitcore.encoding.Base58Check.decode(encryptedPrivateKeyBase58).toString('hex').substring(6, 14);
if (actualChecksum != expectedChecksum)
return cb(new Error('Incorrect passphrase'));
return cb(null, privateKeyWif);
};
API.prototype.getBalanceFromPrivateKey = function(privateKey, coin, cb) {
var self = this;
if (_.isFunction(coin)) {
cb = coin;
coin = 'btc';
}
var B = Bitcore_[coin];
var privateKey = new B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress();
self.getUtxos({
addresses: coin == 'bch' ? address.toLegacyAddress() : address.toString(),
}, function(err, utxos) {
if (err) return cb(err);
return cb(null, _.sumBy(utxos, 'satoshis'));
});
};
API.prototype.buildTxFromPrivateKey = function(privateKey, destinationAddress, opts, cb) {
var self = this;
opts = opts || {};
var coin = opts.coin || 'btc';
var B = Bitcore_[coin];
var privateKey = B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress();
async.waterfall([
function(next) {
self.getUtxos({
addresses: coin == 'bch' ? address.toLegacyAddress() : address.toString(),
}, function(err, utxos) {
return next(err, utxos);
});
},
function(utxos, next) {
if (!_.isArray(utxos) || utxos.length == 0) return next(new Error('No utxos found'));
var fee = opts.fee || 10000;
var amount = _.sumBy(utxos, 'satoshis') - fee;
if (amount <= 0) return next(new Errors.INSUFFICIENT_FUNDS);
var tx;
try {
var toAddress = B.Address.fromString(destinationAddress);
tx = new B.Transaction()
.from(utxos)
.to(toAddress, amount)
.fee(fee)
.sign(privateKey);
// Make sure the tx can be serialized
tx.serialize();
} catch (ex) {
log.error('Could not build transaction from private key', ex);
return next(new Errors.COULD_NOT_BUILD_TRANSACTION);
}
return next(null, tx);
}
], cb);
};
/**
* Open a wallet and try to complete the public key ring.
*
* @param {Callback} cb - The callback that handles the response. It returns a flag indicating that the wallet is complete.
* @fires API#walletCompleted
*/
API.prototype.openWallet = function(cb) {
$.checkState(this.credentials);
var self = this;
if (self.credentials.isComplete() && self.credentials.hasWalletInfo())
return cb(null, true);
self._doGetRequest('/v2/wallets/?includeExtendedInfo=1', function(err, ret) {
if (err) return cb(err);
var wallet = ret.wallet;
self._processStatus(ret);
if (!self.credentials.hasWalletInfo()) {
var me = _.find(wallet.copayers, {
id: self.credentials.copayerId
});
self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, me.name);
}
if (wallet.status != 'complete')
return cb();
if (self.credentials.walletPrivKey) {
if (!Verifier.checkCopayers(self.credentials, wallet.copayers)) {
return cb(new Errors.SERVER_COMPROMISED);
}
} else {
// this should only happen in AIR-GAPPED flows
log.warn('Could not verify copayers key (missing wallet Private Key)');
}
self.credentials.addPublicKeyRing(API._extractPublicKeyRing(wallet.copayers));
self.emit('walletCompleted', wallet);
return cb(null, ret);
});
};
API.prototype._getHeaders = function(method, url, args) {
var headers = {
'x-client-version': 'bwc-' + Package.version,
};
if (this.supportStaffWalletId) {
headers['x-wallet-id'] = this.supportStaffWalletId;
}
return headers;
};
/**
* Do an HTTP request
* @private
*
* @param {Object} method
* @param {String} url
* @param {Object} args
* @param {Callback} cb
*/
API.prototype._doRequest = function(method, url, args, useSession, cb) {
var self = this;
var headers = self._getHeaders(method, url, args);
if (self.credentials) {
headers['x-identity'] = self.credentials.copayerId;
if (useSession && self.session) {
headers['x-session'] = self.session;
} else {
var reqSignature;
var key = args._requestPrivKey || self.credentials.requestPrivKey;
if (key) {
delete args['_requestPrivKey'];
reqSignature = API._signRequest(method, url, args, key);
}
headers['x-signature'] = reqSignature;
}
}
var r = self.request[method](self.baseUrl + url);
r.accept('json');
_.each(headers, function(v, k) {
if (v) r.set(k, v);
});
if (args) {
if (method == 'post' || method == 'put') {
r.send(args);
} else {
r.query(args);
}
}
r.timeout(self.timeout);
r.end(function(err, res) {
if (!res) {
return cb(new Errors.CONNECTION_ERROR);
}
if (res.body)
log.debug(util.inspect(res.body, {
depth: 10
}));
if (res.status !== 200) {
if (res.status === 404)
return cb(new Errors.NOT_FOUND);
if (!res.status)
return cb(new Errors.CONNECTION_ERROR);
log.error('HTTP Error:' + res.status);
if (!res.body)
return cb(new Error(res.status));
return cb(API._parseError(res.body));
}
if (res.body === '{"error":"read ECONNRESET"}')
return cb(new Errors.ECONNRESET_ERROR(JSON.parse(res.body)));
return cb(null, res.body, res.header);
});
};
API.prototype._login = function(cb) {
this._doPostRequest('/v1/login', {}, cb);
};
API.prototype._logout = function(cb) {
this._doPostRequest('/v1/logout', {}, cb);
};
/**
* Do an HTTP request
* @private
*
* @param {Object} method
* @param {String} url
* @param {Object} args
* @param {Callback} cb
*/
API.prototype._doRequestWithLogin = function(method, url, args, cb) {
var self = this;
function doLogin(cb) {
self._login(function(err, s) {
if (err) return cb(err);
if (!s) return cb(new Errors.NOT_AUTHORIZED);
self.session = s;
cb();
});
};
async.waterfall([
function(next) {
if (self.session) return next();
doLogin(next);
},
function(next) {
self._doRequest(method, url, args, true, function(err, body, header) {
if (err && err instanceof Errors.NOT_AUTHORIZED) {
doLogin(function(err) {
if (err) return next(err);
return self._doRequest(method, url, args, true, next);
});
}
next(null, body, header);
});
},
], cb);
};
/**
* Do a POST request
* @private
*
* @param {String} url
* @param {Object} args
* @param {Callback} cb
*/
API.prototype._doPostRequest = function(url, args, cb) {
return this._doRequest('post', url, args, false, cb);
};
API.prototype._doPutRequest = function(url, args, cb) {
return this._doRequest('put', url, args, false, cb);
};
/**
* Do a GET request
* @private
*
* @param {String} url
* @param {Callback} cb
*/
API.prototype._doGetRequest = function(url, cb) {
url += url.indexOf('?') > 0 ? '&' : '?';
url += 'r=' + _.random(10000, 99999);
return this._doRequest('get', url, {}, false, cb);
};
API.prototype._doGetRequestWithLogin = function(url, cb) {
url += url.indexOf('?') > 0 ? '&' : '?';
url += 'r=' + _.random(10000, 99999);
return this._doRequestWithLogin('get', url, {}, cb);
};
/**
* Do a DELETE request
* @private
*
* @param {String} url
* @param {Callback} cb
*/
API.prototype._doDeleteRequest = function(url, cb) {
return this._doRequest('delete', url, {}, false, cb);
};
API._buildSecret = function(walletId, walletPrivKey, coin, network) {
if (_.isString(walletPrivKey)) {
walletPrivKey = Bitcore.PrivateKey.fromString(walletPrivKey);
}
var widHex = new Buffer(walletId.replace(/-/g, ''), 'hex');
var widBase58 = new Bitcore.encoding.Base58(widHex).toString();
return _.padEnd(widBase58, 22, '0') + walletPrivKey.toWIF() + (network == 'testnet' ? 'T' : 'L') + coin;
};
API.parseSecret = function(secret) {
$.checkArgument(secret);
function split(str, indexes) {
var parts = [];
indexes.push(str.length);
var i = 0;
while (i < indexes.length) {
parts.push(str.substring(i == 0 ? 0 : indexes[i - 1], indexes[i]));
i++;
};
return parts;
};
try {
var secretSplit = split(secret, [22, 74, 75]);
var widBase58 = secretSplit[0].replace(/0/g, '');
var widHex = Bitcore.encoding.Base58.decode(widBase58).toString('hex');
var walletId = split(widHex, [8, 12, 16, 20]).join('-');
var walletPrivKey = Bitcore.PrivateKey.fromString(secretSplit[1]);
var networkChar = secretSplit[2];
var coin = secretSplit[3] || 'btc';
return {
walletId: walletId,
walletPrivKey: walletPrivKey,
coin: coin,
network: networkChar == 'T' ? 'testnet' : 'livenet',
};
} catch (ex) {
throw new Error('Invalid secret');
}
};
API.getRawTx = function(txp) {
var t = Utils.buildTx(txp);
return t.uncheckedSerialize();
};
API.signTxp = function(txp, derivedXPrivKey) {
//Derive proper key to sign, for each input
var privs = [];
var derived = {};
var xpriv = new Bitcore.HDPrivateKey(derivedXPrivKey);
_.each(txp.inputs, function(i) {
$.checkState(i.path, "Input derivation path not available (signing transaction)")
if (!derived[i.path]) {