This repository was archived by the owner on Jan 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathbgcl.js
More file actions
executable file
·3273 lines (2976 loc) · 97.6 KB
/
bgcl.js
File metadata and controls
executable file
·3273 lines (2976 loc) · 97.6 KB
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
#!/usr/bin/env node
var ArgumentParser = require('argparse').ArgumentParser;
var bitcoin = require('bitcoinjs-lib');
var Transaction = require('bitcoinjs-lib/src/transaction');
var Script = require('bitcoinjs-lib/src/script');
var bitgo = require('bitgo');
var bs58check = require('bs58check');
var crypto = require('crypto');
var Q = require('q');
var fs = require('fs');
var moment = require('moment');
var read = require('read');
var readline = require('readline');
var secrets = require('secrets.js');
var sjcl = require('sjcl');
var qr = require('qr-image');
var open = require('open');
var util = require('util');
var _ = require('lodash');
_.string = require('underscore.string');
var pjson = require('../package.json');
var CLI_VERSION = pjson.version;
var request = require('superagent');
require('superagent-as-promised')(request);
// Enable for better debugging
// Q.longStackSupport = true;
var permsToRole = {};
permsToRole['admin,spend,view'] = 'admin';
permsToRole['spend,view'] = 'spender';
permsToRole['view'] = 'viewer';
function getUserHome() {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
var BITGO_DIR = getUserHome() + '/.bitgo';
function jsonFilename(name) {
return BITGO_DIR + '/' + name + '.json';
}
function loadJSON(name) {
try {
data = fs.readFileSync(jsonFilename(name), {encoding: 'utf8'});
return JSON.parse(data);
} catch (e) {
return undefined;
}
}
function saveJSON(name, data) {
if (!fs.existsSync(BITGO_DIR)) {
fs.mkdirSync(BITGO_DIR, 0700);
}
data = JSON.stringify(data, null, 2);
fs.writeFileSync(jsonFilename(name), data, {encoding: 'utf8', mode: 0600});
}
var UserInput = function(args) {
_.assign(this, args);
};
// Prompt the user for input
UserInput.prototype.prompt = function(question, required) {
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var deferred = Q.defer();
rl.setPrompt(question);
rl.prompt();
rl.on('line', function(line) {
line = line.trim();
if (line || !required) {
deferred.resolve(line);
rl.close();
} else {
rl.prompt();
}
});
return deferred.promise;
};
// Prompt the user for password input
UserInput.prototype.promptPassword = function(question, allowBlank) {
var self = this;
var internalPromptPassword = function() {
var answer = "";
var deferred = Q.defer();
read({prompt: question, silent:true, replace: '*'}, function(err, result) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(result);
}
});
return deferred.promise;
};
// Ensure password not blank
return internalPromptPassword()
.then(function(password) {
if (password || allowBlank) {
return password;
}
return self.promptPassword(question);
});
};
// Get input from user into variable, with question as prompt
UserInput.prototype.getVariable = function(name, question, required, defaultValue) {
var self = this;
return function() {
return Q().then(function() {
if (self[name]) {
return;
}
return Q().then(function() {
if (name == 'password' || name == 'passcode') {
return self.promptPassword(question);
} else {
return self.prompt(question, required);
}
})
.then(function(value) {
if (!value && defaultValue) {
value = defaultValue;
}
self[name] = value;
});
});
};
};
UserInput.prototype.getPassword = function(name, question, confirm) {
var self = this;
var password;
return function() {
return Q().then(function() {
if (self[name]) {
return;
}
return self.promptPassword(question)
.then(function(value) {
password = value;
if (confirm) {
return self.promptPassword('Confirm ' + question, true);
}
})
.then(function(confirmation) {
if (confirm && confirmation !== password) {
console.log("passwords don't match -- try again");
return self.getPassword(name, question, confirm)();
} else {
self[name] = password;
}
});
});
};
};
UserInput.prototype.getIntVariable = function(name, question, required, min, max) {
var self = this;
return function() {
return self.getVariable(name, question, required)()
.then(function() {
var value = parseInt(self[name]);
if (value != self[name]) {
throw new Error('integer value required');
}
if (value < min) {
throw new Error('value must be at least ' + min);
}
if (value > max) {
throw new Error('value must be at most ' + max);
}
self[name] = value;
})
.catch(function(err) {
console.log(err.message);
delete self[name];
if (required) {
return self.getIntVariable(name, question, required, min, max)();
}
});
};
};
var Shell = function(bgcl) {
this.bgcl = bgcl;
};
Shell.prototype.prompt = function() {
var bgcl = this.bgcl;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var deferred = Q.defer();
var prompt = '[bitgo';
if (bgcl.session && bgcl.session.wallet) {
prompt = prompt + ' @ ' + bgcl.session.wallet.label();
}
prompt = prompt + ']\u0243 ';
rl.setPrompt(prompt);
rl.on('line', function(line) {
line = line.trim();
if (line) {
deferred.resolve(line);
rl.close();
} else {
rl.prompt();
}
});
rl.prompt();
return deferred.promise;
};
var Session = function(bitgo) {
this.bitgo = bitgo;
this.wallet = undefined;
this.wallets = {};
this.labels = {};
};
Session.prototype.load = function() {
var session = loadJSON(this.bitgo.getEnv());
if (session) {
if (session.bitgo) {
this.bitgo.fromJSON(session.bitgo);
}
if (session.wallet) {
this.wallet = this.bitgo.newWalletObject(session.wallet);
}
this.wallets = session.wallets;
this.labels = session.labels;
}
};
Session.prototype.toJSON = function() {
return {
bitgo: this.bitgo,
wallet: this.wallet,
wallets: this.wallets,
labels: this.labels
};
};
Session.prototype.save = function() {
saveJSON(this.bitgo.getEnv(), this);
};
Session.prototype.labelForWallet = function(walletId) {
return this.wallets && this.wallets[walletId] && this.wallets[walletId].label;
};
Session.prototype.labelForAddress = function(address) {
var wallet = this.wallet;
var labels = this.labels && this.labels[address];
if (!labels || labels.length === 0) {
return undefined;
}
if (labels.length === 1) {
return labels[0].label;
}
var foundLabel;
labels.forEach(function(label) {
if (label.walletId === wallet.id()) {
foundLabel = label.label;
return false; // break out
}
});
if (foundLabel) { return foundLabel; }
return labels[0].label; // found multiple, return first one
};
var BGCL = function() {
};
BGCL.prototype.createArgumentParser = function() {
var parser = new ArgumentParser({
version: CLI_VERSION,
addHelp:true,
description: 'BitGo Command-Line'
});
parser.addArgument(
['-e', '--env'], {
help: 'BitGo environment to use: prod (default) or test. Can also be set with the BITGO_ENV environment variable.'
}
);
parser.addArgument(['-j', '--json'], { action: 'storeTrue', help: 'output JSON (if available)' });
var subparsers = parser.addSubparsers({
title:'subcommands',
dest:"cmd"
});
this.subparsers = subparsers;
// login
var login = subparsers.addParser('login', {
addHelp: true,
help: 'Sign in to BitGo'
});
login.addArgument(['-u', '--username'], {help: 'the account email'});
login.addArgument(['-p', '--password'], {help: 'the account password'});
login.addArgument(['-o', '--otp'], {help: 'the 2-step verification code'});
// logout
var logout = subparsers.addParser('logout', {
addHelp: true,
help: 'Sign out of BitGo'
});
// token
var token = subparsers.addParser('token', {
addHelp: true,
help: 'Get or set the current auth token'
});
token.addArgument(['token'], {nargs: '?', help: 'the token to set'});
// status
var status = subparsers.addParser('status', {
addHelp: true,
help: 'Show current status'
});
/**
* OTP Commands
*/
var otp = subparsers.addParser('otp', { help: 'OTP commands (use otp -h to see commands)' });
var otpCommands = otp.addSubparsers({
title:'otp commands',
dest:"cmd2",
});
// otp list
var otpList = otpCommands.addParser('list', { help: 'List OTP methods' });
// otp remove
var otpRemove = otpCommands.addParser('remove', { help: 'Remove OTP device' });
otpRemove.addArgument(['deviceId'], { help: 'the device id to remove' });
// otp add
var otpAdd = otpCommands.addParser('add', { help: 'Add an OTP device' });
otpAdd.addArgument(['type'], { choices: ['totp', 'yubikey', 'authy'], help: 'Type of device to add' });
// wallets
var wallets = subparsers.addParser('wallets', {
addHelp: true,
help: 'Get list of available wallets'
});
// wallet
var wallet = subparsers.addParser('wallet', {
addHelp: true,
help: 'Set or get the current wallet'
});
wallet.addArgument(['wallet'], {nargs: '?', help: 'the index, id, or name of the wallet to set as current'});
// balance
var balance = subparsers.addParser('balance', {
addHelp: true,
help: 'Get current wallet balance'
});
balance.addArgument(['-c', '--confirmed'], { action: 'storeTrue', help: 'Exclude unconfirmed transactions' });
balance.addArgument(['-u', '--unit'], { help: 'select units: satoshi | bits | btc [default]'});
// labels
var labels = subparsers.addParser('labels', {
addHelp: true,
help: 'Show labels'
});
labels.addArgument(['-a', '--all'], {
help: 'show labels on all wallets, not just current',
nargs: 0,
action: 'storeTrue'
});
// setlabel
var setLabel = subparsers.addParser('setlabel', {
addHelp: true,
help: 'Set a label on any address (in curr. wallet context)'
});
setLabel.addArgument(['address'], { help: 'the address to label'});
setLabel.addArgument(['label'], { help: 'the label' });
// removelabel
var removeLabel = subparsers.addParser('removelabel', {
addHelp: true,
help: 'Remove a label on an address (in curr. wallet context)'
});
removeLabel.addArgument(['address'], { help: 'the address from which to remove the label'});
// addresses
var addresses = subparsers.addParser('addresses', {
addHelp: true,
help: 'List addresses for the current wallet'
});
addresses.addArgument(['-c', '--change'], {action: 'storeTrue', help: 'include change addresses'});
// newaddress
var newAddress = subparsers.addParser('newaddress', {
addHelp: true,
help: 'Create a new receive address for the current wallet'
});
newAddress.addArgument(['-c', '--change'], { action: 'storeTrue', help: 'create a change address' });
newAddress.addArgument(['-l', '--label'], { help: 'optional label'});
// unspents
var unspents = subparsers.addParser('unspents', {
aliases: ['unspent'],
addHelp: true,
help: 'Show unspents in the wallet'
});
unspents.addArgument(['-c', '--minconf'], {help: 'show only unspents with at least MINCONF confirms'});
// unspents consolidation
var consolidateUnspents = subparsers.addParser('consolidate', {
addHelp: true,
help: 'Consolidate unspents in a wallet'
});
consolidateUnspents.addArgument(['-t', '--target'], { type: 'int', help: 'consolidate unspents until only TARGET number of unspents is left (defaults to 1)' });
consolidateUnspents.addArgument(['-i', '--inputCount'], { type: 'int', help: 'use up to that many inputs in a consolidation batch (defaults to 85)' });
consolidateUnspents.addArgument(['-f', '--feeRate'], { type: 'int', help: 'set fee rate in satoshis per KB'});
consolidateUnspents.addArgument(['-c', '--confirmTarget'], { type: 'int', help: 'set fee based on estimates for getting confirmed within this number of blocks'});
// unspents fanout
var fanoutUnspents = subparsers.addParser('fanout', {
addHelp: true,
help: 'Fan out unspents in a wallet'
});
fanoutUnspents.addArgument(['-t', '--target'], { type: 'int', required: true, help: 'fan out up to TARGET number of unspents' });
// txlist
var txList = subparsers.addParser('tx', {
addHelp: true,
help: 'List transactions on the current wallet'
});
txList.addArgument(['-n'], { help: 'number of transactions to show' });
// unlock
var unlock = subparsers.addParser('unlock', {
addHelp: true,
help: 'Unlock the session to allow transacting'
});
unlock.addArgument(['otp'], {nargs: '?', help: 'the 2-step verification code'});
// lock
var lock = subparsers.addParser('lock', {
addHelp: true,
help: 'Re-lock the session'
});
// sendtoaddress
var sendToAddress = subparsers.addParser('sendtoaddress', {
addHelp: true,
help: 'Create and send a transaction'
});
sendToAddress.addArgument(['-d', '--dest'], {help: 'the destination address'});
sendToAddress.addArgument(['-a', '--amount'], {help: 'the amount in BTC'});
sendToAddress.addArgument(['-p', '--password'], {help: 'the wallet password'});
sendToAddress.addArgument(['-o', '--otp'], {help: 'the 2-step verification code'});
sendToAddress.addArgument(['-c', '--comment'], {help: 'optional private comment'});
sendToAddress.addArgument(['-u', '--unconfirmed'], { nargs: 0, help: 'allow spending unconfirmed external inputs'});
sendToAddress.addArgument(['--confirm'], {action: 'storeConst', constant: 'go', help: 'skip interactive confirm step -- be careful!'});
// freezewallet
var freezeWallet = subparsers.addParser('freezewallet', {
addHelp: true,
help: 'Freeze (time-lock) the current wallet'
});
freezeWallet.addArgument(['-d', '--duration'], { help: 'the duration in seconds for which to freeze the wallet' });
// removewallet
var removeWallet = subparsers.addParser('removewallet', {
addHelp: true,
help: 'Remove a wallet from your account'
});
removeWallet.addArgument(['wallet'], { nargs: '?', help: 'the wallet ID of the wallet (default: current)'});
// sharewallet
var shareWallet = subparsers.addParser('sharewallet', {
// addHelp: true,
// help: 'Share the current wallet with another user'
});
shareWallet.addArgument(['-e', '--email'], {help: "email address of the recipient's BitGo account"});
shareWallet.addArgument(['-r', '--role'], {
help: 'role for the recipient on this wallet',
choices: ['admin', 'spender', 'viewer']
});
shareWallet.addArgument(['-p', '--password'], {help: "the wallet password"});
shareWallet.addArgument(['-o', '--otp'], {help: 'the 2-step verification code'});
shareWallet.addArgument(['-c', '--comment'], {help: 'a message for the recipient'});
shareWallet.addArgument(['wallet'], { nargs: '?', help: 'the wallet id to share (default: current)'});
// shares
var shares = subparsers.addParser('shares', {
// addHelp: true,
// help: 'List outstanding wallet shares (incoming and outgoing)'
});
// acceptshare
var acceptShare = subparsers.addParser('acceptshare', {
// addHelp: true,
// help: 'Accept a wallet share invite'
});
acceptShare.addArgument(['share'], {help: 'the share id'});
// cancelshare
var cancelShare = subparsers.addParser('cancelshare', {
// addHelp: true,
// help: 'Cancel or decline a wallet share invite'
});
cancelShare.addArgument(['share'], {help: 'the share id'});
// newkey
var newKey = subparsers.addParser('newkey', {
addHelp: true,
help: 'Create a new BIP32 keychain (client-side only)'
});
newKey.addArgument(['entropy'], {nargs: '?', help: 'optional additional entropy'});
// newwallet
var newWallet = subparsers.addParser('newwallet', {
addHelp: true,
help: 'Create a new Multi-Sig HD wallet'
});
newWallet.addArgument(['-n', '--name'], {help: 'name for the wallet'});
newWallet.addArgument(['-u', '--userkey'], {help: 'xprv for the user keychain'});
newWallet.addArgument(['-b', '--backupkey'], {help: 'xpub for the backup keychain'});
var splitKeys = subparsers.addParser('splitkeys', {
addHelp: true,
help: 'Create set of BIP32 keys, split into encrypted shares.'
});
splitKeys.addArgument(['-m'], { help: 'number of shares required to reconstruct a key' });
splitKeys.addArgument(['-n'], { help: 'total number of shares per key' });
splitKeys.addArgument(['-N', '--nkeys'], { help: 'total number of keys to generate' });
splitKeys.addArgument(['-p', '--prefix'], { help: 'output file prefix' });
splitKeys.addArgument(['-e', '--entropy'], { help: 'additional user-supplied entropy'});
var verifySplitKeys = subparsers.addParser('verifysplitkeys', {
addHelp: true,
help: "Verify xpubs from an output file of 'splitkeys' (does not show xprvs)"
});
verifySplitKeys.addArgument(['-f', '--file'], { help: 'the input file (JSON format)'});
verifySplitKeys.addArgument(['-k', '--keys'], { help: 'comma-separated list of key indices to recover' });
var recoverKeys = subparsers.addParser('recoverkeys', {
addHelp: true,
help: "Recover key(s) from an output file of 'splitkeys' (xprvs are shown)"
});
recoverKeys.addArgument(['-v', '--verifyonly'], {action: 'storeConst', constant: 'true', help: 'verify only (do not show xprvs)'});
recoverKeys.addArgument(['-f', '--file'], { help: 'the input file (JSON format)'});
recoverKeys.addArgument(['-k', '--keys'], { help: 'comma-separated list of key indices to recover' });
var updateSplitKey = subparsers.addParser('updatesplitkey', {
addHelp: true,
help: "Update key passwords/schema from an output file of 'splitkeys'"
});
updateSplitKey.addArgument(['-m'], { help: 'new number of shares required to reconstruct a key' });
updateSplitKey.addArgument(['-n'], { help: 'new total number of shares per key' });
updateSplitKey.addArgument(['-f', '--file'], { help: 'the input file (JSON format)'});
updateSplitKey.addArgument(['-k', '--key'], { help: 'key index to update' });
var dumpWalletUserKey = subparsers.addParser('dumpwalletuserkey', {
addHelp: true,
help: "Dumps the user's private key (first key in the 3 multi-sig keys) to the output"
});
dumpWalletUserKey.addArgument(['-p', '--password'], {help: 'the wallet password'});
dumpWalletUserKey.addArgument(['--confirm'], {action: 'storeConst', constant: 'go', help: 'skip interactive confirm step -- be careful!'});
var createTx = subparsers.addParser('createtx', {
addHelp: true,
help: "Create an unsigned transaction (online) for signing (the signing can be done offline)"
});
createTx.addArgument(['-d', '--dest'], {help: 'the destination address'});
createTx.addArgument(['-a', '--amount'], {help: 'the amount in BTC'});
createTx.addArgument(['-f', '--fee'], {help: 'fee to pay for transaction'});
createTx.addArgument(['-c', '--comment'], {help: 'optional private comment'});
createTx.addArgument(['-p', '--prefix'], { help: 'output file prefix' });
createTx.addArgument(['-u', '--unconfirmed'], { nargs: 0, help: 'allow spending unconfirmed external inputs'});
var createTxFromJson = subparsers.addParser('createtxfromjson', {
addHelp: true,
help: "Create unsigned transaction (online) to many addresses using json form {str addr: int value_in_satoshis, ...}"
});
createTxFromJson.addArgument(['-j', '--json'], {help: 'json string {str addr: int value_in_satoshis, ...}'});
createTxFromJson.addArgument(['-f', '--fee'], {help:'fee to pay for transaction'});
createTxFromJson.addArgument(['-c', '--comment'], {help: 'optional private comment'});
createTxFromJson.addArgument(['-p', '--prefix'], { help: 'output file prefix' });
createTxFromJson.addArgument(['-u', '--unconfirmed'], { nargs: 0, help: 'allow spending unconfirmed external inputs'});
var signTx = subparsers.addParser('signtx', {
addHelp: true,
help: 'Sign a transaction (can be used offline) with an input transaction JSON file'
});
signTx.addArgument(['-f', '--file'], { help: 'the input transaction file (JSON format)'});
signTx.addArgument(['--confirm'], {action: 'storeConst', constant: 'go', help: 'skip interactive confirm step -- be careful!'});
signTx.addArgument(['-k', '--key'], {help: 'xprv (private key) for signing'});
signTx.addArgument(['-p', '--prefix'], { nargs: '?', help: 'optional output file prefix' });
var sendTransaction = subparsers.addParser('sendtx', {
addHelp: true,
help: 'Send a transaction for co-signing to BitGo'
});
sendTransaction.addArgument(['-t', '--txhex'], { help: 'the transaction hex to send'});
sendTransaction.addArgument(['-f', '--file'], { nargs: '?', help: 'optional input file containing the tx hex' });
// shell
var shell = subparsers.addParser('shell', {
addHelp: true,
help: 'Run the BitGo command shell'
});
// listWebhooks
var listWebhooks = subparsers.addParser('listWebhooks', {
addHelp: true,
help: 'Show webhooks for the current wallet'
});
// addWebhook
var addWebhook = subparsers.addParser('addWebhook', {
addHelp: true,
help: 'Add a webhook for the current wallet'
});
addWebhook.addArgument(['-u', '--url'], {help: 'URL of new webhook'});
addWebhook.addArgument(['-n', '--numConfirmations'], {help: 'Number of confirmations before calling webhook', defaultValue: 0});
addWebhook.addArgument(['-t', '--type'], {help: 'Type of webhook: e.g. transaction', defaultValue: 'transaction'});
// removeWebhook
var removeWebhook = subparsers.addParser('removeWebhook', {
addHelp: true,
help: 'Remove a webhook for the current wallet'
});
removeWebhook.addArgument(['-u', '--url'], {help: 'URL of webhook to remove'});
removeWebhook.addArgument(['-t', '--type'], {help: 'Type of webhook: e.g. transaction', defaultValue: 'transaction'});
var util = subparsers.addParser('util', {
addHelp: true,
help: 'Utilities for BitGo wallets'
});
var utilParser = util.addSubparsers({
title: 'Utility commands',
dest: 'utilCmd'
});
// recoverLitecoin
var recoverLitecoin = utilParser.addParser('recoverlitecoin', {
addHelp: true,
help: 'Helper tool to craft transaction to recover Litecoin mistakenly sent to BitGo Bitcoin multisig addresses on the Litecoin network'
});
recoverLitecoin.addArgument(['-i', '--inputaddresses'], {help: 'JSON array of input addresses to obtain litecoin from'});
recoverLitecoin.addArgument(['-r', '--recipients'], {help: 'JSON dictionary of recipients in { addr1: satoshis }'});
recoverLitecoin.addArgument(['-p', '--prefix'], { help: 'optional output file prefix' });
// help
var help = subparsers.addParser('help', {
addHelp: true,
help: 'Display help'
});
help.addArgument(['command'], {nargs: '?'});
return parser;
};
BGCL.prototype.handleUtil = function() {
switch (this.args.utilCmd) {
case 'recoverlitecoin':
return this.handleRecoverLitecoin();
default:
throw new Error('unknown command');
}
};
BGCL.prototype.doPost = function(url, data, field) {
data = data || {};
return this.bitgo.post(this.bitgo.url(url)).send(data).result(field);
};
BGCL.prototype.doPut = function(url, data, field) {
data = data || {};
return this.bitgo.put(this.bitgo.url(url)).send(data).result(field);
};
BGCL.prototype.doGet = function(url, data, field) {
data = data || {};
return this.bitgo.get(this.bitgo.url(url)).query(data).result(field);
};
BGCL.prototype.doDelete = function(url, data, field) {
data = data || {};
return this.bitgo.del(this.bitgo.url(url)).send(data).result(field);
};
BGCL.prototype.toBTC = function(satoshis, decimals) {
if (satoshis === 0) {
return '0';
}
if (typeof(decimals) == 'undefined') {
decimals = 4;
}
return (satoshis * 1e-8).toFixed(decimals);
};
BGCL.prototype.toBits = function(satoshis, decimals) {
if (satoshis === 0) {
return '0';
}
if (typeof(decimals) == 'undefined') {
decimals = 2;
}
return (satoshis * 1e-2).toFixed(decimals);
};
BGCL.prototype.inBrackets = function(str) {
return '[' + str + ']';
};
BGCL.prototype.info = function(line) {
console.log(line);
};
BGCL.prototype.printJSON = function(obj) {
this.info(JSON.stringify(obj, null, 2));
};
BGCL.prototype.action = function(line) {
console.log('*** ' + line);
console.log();
};
// Check if current session is using a long lived token and warn user if true
// Used to prevent a user from changing or possibly invalidating (in the case
// of a call to logout) the long-lived token.
BGCL.prototype.checkAndWarnOfLongLivedTokenChange = function(input, warning) {
return this.bitgo.session()
.then(function(res) {
if (_.contains(_.keys(res), 'label')) {
console.log(warning);
return input.getVariable('confirm', 'Type \'go\' to confirm: ')()
.then(function() {
if (input.confirm !== 'go') {
throw new Error('cancelling method call');
}
});
}
});
};
BGCL.prototype.header = function(line) {
return line; // '> ' + line; // + ' ]';
};
BGCL.prototype.userHeader = function() {
var user = this.bitgo.user();
var username = user ? user.username : 'None';
this.info('Current User: ' + username);
};
BGCL.prototype.walletHeader = function() {
if (this.session.wallet) {
console.log('Current wallet: ' + this.session.wallet.id());
}
};
BGCL.prototype.formatWalletId = function(walletId) {
var label = this.session.labelForWallet(walletId);
if (label) {
return _.string.prune(label, 22);
}
var shortened = _.string.prune(walletId, 12);
return this.inBrackets('Wallet: ' + shortened);
};
BGCL.prototype.fetchLabels = function() {
var self = this;
return this.bitgo.labels()
.then(function(labels) {
self.session.labels = _.groupBy(labels, 'address');
self.session.save();
return labels;
});
};
BGCL.prototype.fetchUsers = function(userIds) {
var self = this;
var userFetches = userIds.map(function(id) {
return self.bitgo.getUser({ id: id });
});
return Q.all(userFetches);
};
BGCL.prototype.retryForUnlock = function(params, func) {
var self = this;
return func()
.catch(function(err) {
if (err.needsOTP) {
// unlock and try again
return self.handleUnlock(params).then(func);
} else {
throw err;
}
});
};
BGCL.prototype.getRandomPassword = function() {
this.addEntropy(128);
return bs58check.encode(new Buffer(sjcl.random.randomWords(7)));
};
BGCL.prototype.handleToken = function() {
var self = this;
// If no token set, display current one
if (!this.args.token) {
return self.ensureAuthenticated()
.then(function() {
self.info(self.bitgo._token);
});
}
self.bitgo.clear();
var input = new UserInput(this.args);
return Q()
.then(input.getVariable('token', 'Token: '))
.then(function() {
self.bitgo._token = input.token;
return self.bitgo.me();
})
.then(function(user) {
self.bitgo._user = user;
self.session = new Session(self.bitgo);
self.action('Logged in as ' + user.username);
var promises = [];
promises.push(self.handleWallets());
promises.push(self.fetchLabels());
return Q.all(promises);
})
.catch(function(err) {
if (err.status === 401) {
throw new Error('Invalid token');
}
throw err;
});
};
BGCL.prototype.handleLogin = function() {
var self = this;
self.bitgo.clear();
var input = new UserInput(this.args);
return Q()
.then(input.getVariable('username', 'Email: '))
.then(input.getVariable('password', 'Password: '))
.then(input.getVariable('otp', '2-Step Verification Code: '))
.then(function() {
return self.bitgo.authenticate(input);
})
.then(function() {
self.session = new Session(self.bitgo);
self.action('Logged in as ' + input.username);
var promises = [];
promises.push(self.handleWallets());
promises.push(self.fetchLabels());
return Q.all(promises);
})
.catch(function(err) {
if (err.needsOTP) {
throw new Error('Incorrect 2-step verification code.');
}
if (err.status === 401) {
throw new Error('Invalid login/password');
}
throw err;
});
};
BGCL.prototype.handleLogout = function() {
var self = this;
var input = new UserInput(this.args);
return this.checkAndWarnOfLongLivedTokenChange(input, "About to logout of a session with a longed-lived access token!\n" +
"This will invalidate the long-lived access token, making it unusable in the future\n")
.then(function() {
return self.bitgo.logout()
})
.then(function() {
self.action('Logged out');
});
};
BGCL.prototype.handleStatus = function() {
var self = this;
var status = {
env: this.bitgo.getEnv(),
network: bitgo.getNetwork(),
sessionFile: jsonFilename(this.bitgo.getEnv()),
};
if (this.bitgo.user()) {
status.user = this.bitgo.user().username;
}
if (this.session.wallet) {
status.wallet = this.session.wallet.id();
}
return self.ensureAuthenticated()
.then(function() {
// JSON output
if (self.args.json) {
return self.printJSON(status);
}
// normal output
self.info('Environment: ' + status.env);
self.info('Network: ' + status.network);
self.info('Session file: ' + status.sessionFile);
self.userHeader();
return self.ensureAuthenticated()
.then(function() {
self.walletHeader();
});
});
};
BGCL.prototype.handleOTPList = function() {
var self = this;
return this.bitgo.me()
.then(function(user) {
// JSON output
if (self.args.json) {
return self.printJSON(user.otpDevices);
}
// normal output
self.info(_.string.rpad('ID', 34) + _.string.rpad('Type', 10) + 'Label');
user.otpDevices.forEach(function(device) {
self.info(_.string.rpad(device.id, 34) + _.string.rpad(device.type, 10) + device.label);
});
});
};
BGCL.prototype.handleOTPRemove = function() {
var self = this;
var deviceId = this.args.deviceId;
return this.retryForUnlock({}, function() {
return self.doDelete('/user/otp/' + deviceId)
.then(function() {
self.info('Removed');
});
});
};
BGCL.prototype.handleOTPAddYubikey = function() {
var self = this;
var input = new UserInput(this.args);
return Q()
.then(input.getVariable('otp', 'Enter Yubikey OTP: ', true))
.then(input.getVariable('label', 'Label (optional): '))
.then(function() {
return self.retryForUnlock({}, function() {
return self.doPut('/user/otp', { type: 'yubikey', otp: input.otp, label: input.label || undefined });
});
})
.then(function() {
self.info('Added');
});
};
BGCL.prototype.handleOTPAddTOTP = function() {
var self = this;
var key;
var input = new UserInput(this.args);
var svgFile = BITGO_DIR + '/totp.svg';
var htmlFile = BITGO_DIR + '/totp.html';
return this.doGet('/user/otp/totp', {})
.then(function(res) {
key = res;
fs.writeFileSync(svgFile, qr.imageSync(key.url, { type: 'svg' }));
fs.writeFileSync(htmlFile, '<center><img src="totp.svg" width=256 height=256><h2 style="font-family:Helvetica">Scan with Google Authenticator</h2></center>');
open(htmlFile);
})
.then(input.getVariable('otp', 'Scan QR Code in browser and enter numeric code: ', true))
.then(input.getVariable('label', 'Label (optional): '))
.then(function() {
fs.unlinkSync(svgFile);
fs.unlinkSync(htmlFile);
return self.retryForUnlock({}, function() {
var params = {
type: 'totp',
key: key.key,
hmac: key.hmac,