-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathwallet.ts
More file actions
2615 lines (2296 loc) · 91.5 KB
/
wallet.ts
File metadata and controls
2615 lines (2296 loc) · 91.5 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
/**
* @hidden
*/
/**
*/
//
// Wallet Object
// BitGo accessor for a specific wallet
//
// Copyright 2014, BitGo, Inc. All Rights Reserved.
//
import { VirtualSizes } from '@bitgo/unspents';
import assert from 'assert';
import * as utxolib from '@bitgo/utxo-lib';
import { bip32 } from '@bitgo/utxo-lib';
import {
common,
ErrorNoInputToRecover,
getNetwork,
getSharedSecret,
makeRandomKey,
sanitizeLegacyPath,
} from '@bitgo/sdk-core';
import _ from 'lodash';
import { signPsbtRequest } from './signPsbt';
import { tryPromise } from '../util';
const TransactionBuilder = require('./transactionBuilder');
const PendingApproval = require('./pendingapproval');
const { getExternalChainCode, getInternalChainCode, isChainCode, scriptTypeForChain } = utxolib.bitgo;
const request = require('superagent');
//
// Constructor
//
const Wallet = function (bitgo, wallet) {
// @ts-expect-error - no implicit this
(this.bitgo as any) = bitgo;
// @ts-expect-error - no implicit this
this.wallet = wallet;
// @ts-expect-error - no implicit this
this.keychains = [];
if (wallet.private) {
// @ts-expect-error - no implicit this
this.keychains = wallet.private.keychains;
}
};
Wallet.prototype.toJSON = function () {
return this.wallet;
};
//
// id
// Get the id of this wallet.
//
Wallet.prototype.id = function () {
return this.wallet.id;
};
//
// label
// Get the label of this wallet.
//
Wallet.prototype.label = function () {
return this.wallet.label;
};
//
// balance
// Get the balance of this wallet.
//
Wallet.prototype.balance = function () {
return this.wallet.balance;
};
//
// balance
// Get the spendable balance of this wallet.
// This is the total of all unspents except those that are unconfirmed and external
//
Wallet.prototype.spendableBalance = function () {
return this.wallet.spendableBalance;
};
//
// confirmedBalance
// Get the confirmedBalance of this wallet.
//
Wallet.prototype.confirmedBalance = function () {
return this.wallet.confirmedBalance;
};
//
// canSendInstant
// Returns if the wallet can send instant transactions
// This is impacted by the choice of backup key provider
//
Wallet.prototype.canSendInstant = function () {
return this.wallet && this.wallet.canSendInstant;
};
//
// instant balance
// Get the instant balance of this wallet.
// This is the total of all unspents that may be spent instantly.
//
Wallet.prototype.instantBalance = function () {
if (!this.canSendInstant()) {
throw new Error('not an instant wallet');
}
return this.wallet.instantBalance;
};
//
// unconfirmedSends
// Get the balance of unconfirmedSends of this wallet.
//
Wallet.prototype.unconfirmedSends = function () {
return this.wallet.unconfirmedSends;
};
//
// unconfirmedReceives
// Get the balance of unconfirmedReceives balance of this wallet.
//
Wallet.prototype.unconfirmedReceives = function () {
return this.wallet.unconfirmedReceives;
};
//
// type
// Get the type of this wallet, e.g. 'safehd'
//
Wallet.prototype.type = function () {
return this.wallet.type;
};
Wallet.prototype.url = function (extra) {
extra = extra || '';
return this.bitgo.url('/wallet/' + this.id() + extra);
};
//
// pendingApprovals
// returns the pending approvals list for this wallet as pending approval objects
//
Wallet.prototype.pendingApprovals = function () {
const self = this;
return this.wallet.pendingApprovals.map(function (p) {
return new PendingApproval(self.bitgo, p, self);
});
};
//
// approvalsRequired
// returns the number of approvals required to approve pending approvals involving this wallet
//
Wallet.prototype.approvalsRequired = function () {
return this.wallet.approvalsRequired || 1;
};
//
// get
// Refetches this wallet and returns it
//
Wallet.prototype.get = function (params, callback): Promise<any> {
params = params || {};
common.validateParams(params, [], [], callback);
const self = this;
return Promise.resolve(
this.bitgo
.get(this.url())
.result()
.then(function (res) {
self.wallet = res;
return self;
})
)
.then(callback)
.catch(callback);
};
//
// updateApprovalsRequired
// Updates the number of approvals required on a pending approval involving this wallet.
// The approvals required is by default 1, but this function allows you to update the
// number such that 1 <= approvalsRequired <= walletAdmins.length - 1
//
Wallet.prototype.updateApprovalsRequired = function (params, callback): Promise<any> {
params = params || {};
common.validateParams(params, [], [], callback);
if (
params.approvalsRequired === undefined ||
!_.isInteger(params.approvalsRequired) ||
params.approvalsRequired < 1
) {
throw new Error('invalid approvalsRequired: must be a nonzero positive number');
}
const self = this;
const currentApprovalsRequired = this.approvalsRequired();
if (currentApprovalsRequired === params.approvalsRequired) {
// no-op, just return the current wallet
return tryPromise(function () {
return self.wallet;
})
.then(callback)
.catch(callback);
}
return Promise.resolve(this.bitgo.put(this.url()).send(params).result()).then(callback).catch(callback);
};
/**
* Returns the correct chain for change, taking into consideration segwit
*/
Wallet.prototype.getChangeChain = function (params) {
let useSegwitChange = !!this.bitgo.getConstants().enableSegwit;
if (!_.isUndefined(params.segwitChange)) {
if (!_.isBoolean(params.segwitChange)) {
throw new Error('segwitChange must be a boolean');
}
// if segwit is disabled through the constants, segwit change should still not be created
useSegwitChange = this.bitgo.getConstants().enableSegwit && params.segwitChange;
}
return useSegwitChange ? getInternalChainCode('p2shP2wsh') : getInternalChainCode('p2sh');
};
//
// createAddress
// Creates a new address for use with this wallet.
//
Wallet.prototype.createAddress = function (params, callback) {
const self = this;
params = params || {};
common.validateParams(params, [], [], callback);
if (this.type() === 'safe') {
throw new Error('You are using a legacy wallet that cannot create a new address');
}
// Default to client-side address validation on, for safety. Use validate=false to disable.
const shouldValidate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
const allowExisting = params.allowExisting;
if (typeof allowExisting !== 'boolean') {
params.allowExisting = allowExisting === 'true';
}
const isSegwit = this.bitgo.getConstants().enableSegwit;
const defaultChain = isSegwit ? getExternalChainCode('p2shP2wsh') : getExternalChainCode('p2sh');
let chain = params.chain;
if (chain === null || chain === undefined) {
chain = defaultChain;
}
return Promise.resolve(
this.bitgo
.post(this.url('/address/' + chain))
.send(params)
.result()
.then(function (addr) {
if (shouldValidate) {
self.validateAddress(addr);
}
return addr;
})
)
.then(callback)
.catch(callback);
};
/**
* Generate address locally without calling server
* @param params
*
*/
Wallet.prototype.generateAddress = function ({ segwit, path, keychains, threshold }) {
const isSegwit = !!segwit;
let signatureThreshold = 2;
if (_.isInteger(threshold)) {
signatureThreshold = threshold;
if (signatureThreshold <= 0) {
throw new Error('threshold has to be positive');
}
}
const pathRegex = /^\/1?[01]\/\d+$/;
if (!path.match(pathRegex)) {
throw new Error('unsupported path: ' + path);
}
let rootKeys = this.keychains;
if (Array.isArray(keychains)) {
rootKeys = keychains;
}
const network = common.Environments[this.bitgo.getEnv()].network;
const derivedKeys = rootKeys.map(function (k) {
const hdnode = bip32.fromBase58(k.xpub);
const derivationPath = k.path + (k.walletSubPath || '') + path;
return hdnode.derivePath(sanitizeLegacyPath(derivationPath)).publicKey;
});
const pathComponents = path.split('/');
const normalizedPathComponents = _.map(pathComponents, (component) => {
if (component && component.length > 0) {
return parseInt(component, 10);
}
});
const pathDetails = _.filter(normalizedPathComponents, _.isInteger);
const addressDetails: any = {
chainPath: path,
path: path,
chain: pathDetails[0],
index: pathDetails[1],
wallet: this.id(),
};
const {
scriptPubKey: outputScript,
redeemScript,
witnessScript,
} = utxolib.bitgo.outputScripts.createOutputScript2of3(derivedKeys, isSegwit ? 'p2shP2wsh' : 'p2sh');
addressDetails.witnessScript = witnessScript?.toString('hex');
addressDetails.redeemScript = redeemScript?.toString('hex');
addressDetails.outputScript = outputScript.toString('hex');
addressDetails.address = utxolib.address.fromOutputScript(outputScript, getNetwork(network));
return addressDetails;
};
//
// validateAddress
// Validates an address and path by calculating it locally from the keychain xpubs
//
Wallet.prototype.validateAddress = function (params) {
common.validateParams(params, ['address', 'path'], []);
const isSegwit = !!params.witnessScript && params.witnessScript.length > 0;
const generatedAddress = this.generateAddress({ path: params.path, segwit: isSegwit });
if (generatedAddress.address !== params.address) {
throw new Error('address validation failure: ' + params.address + ' vs. ' + generatedAddress.address);
}
};
//
// addresses
// Gets the addresses of a HD wallet.
// Options include:
// limit: the number of addresses to get
//
Wallet.prototype.addresses = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
const query: any = {};
if (params.details) {
query.details = 1;
}
const chain = params.chain;
if (chain !== null && chain !== undefined) {
if (Array.isArray(chain)) {
query.chain = _.uniq(_.filter(chain, _.isInteger));
} else {
if (chain !== 0 && chain !== 1) {
throw new Error('invalid chain argument, expecting 0 or 1');
}
query.chain = chain;
}
}
if (params.limit) {
if (!_.isInteger(params.limit)) {
throw new Error('invalid limit argument, expecting number');
}
query.limit = params.limit;
}
if (params.skip) {
if (!_.isInteger(params.skip)) {
throw new Error('invalid skip argument, expecting number');
}
query.skip = params.skip;
}
if (params.sort) {
if (!_.isNumber(params.sort)) {
throw new Error('invalid sort argument, expecting number');
}
query.sort = params.sort;
}
const url = this.url('/addresses');
return Promise.resolve(this.bitgo.get(url).query(query).result()).then(callback).catch(callback);
};
Wallet.prototype.stats = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
const args: string[] = [];
if (params.limit) {
if (!_.isInteger(params.limit)) {
throw new Error('invalid limit argument, expecting number');
}
args.push('limit=' + params.limit);
}
let query = '';
if (args.length) {
query = '?' + args.join('&');
}
const url = this.url('/stats' + query);
return Promise.resolve(this.bitgo.get(url).result()).then(callback).catch(callback);
};
/**
* Refresh the wallet object by syncing with the back-end
* @param callback
* @returns {Wallet}
*/
Wallet.prototype.refresh = function (params, callback) {
return async function () {
// when set to true, gpk returns the private data of safe wallets
const query = _.extend({}, _.pick(params, ['gpk']));
// @ts-expect-error - no implicit this
const res = await this.bitgo.get(this.url()).query(query).result();
// @ts-expect-error - no implicit this
this.wallet = res;
// @ts-expect-error - no implicit this
return this;
}
.call(this)
.then(callback)
.catch(callback);
};
//
// address
// Gets information about a single address on a HD wallet.
// Information includes index, path, redeemScript, sent, received, txCount and balance
// Options include:
// address: the address on this wallet to get
//
Wallet.prototype.address = function (params, callback) {
params = params || {};
common.validateParams(params, ['address'], [], callback);
const url = this.url('/addresses/' + params.address);
return Promise.resolve(this.bitgo.get(url).result()).then(callback).catch(callback);
};
/**
* Freeze the wallet for a duration of choice, stopping BitGo from signing any transactions.
* @param {number} limit The duration to freeze the wallet for in seconds, defaults to 3600.
*/
Wallet.prototype.freeze = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
if (params.duration) {
if (!_.isNumber(params.duration)) {
throw new Error('invalid duration - should be number of seconds');
}
}
return Promise.resolve(this.bitgo.post(this.url('/freeze')).send(params).result())
.then(callback)
.catch(callback);
};
//
// delete
// Deletes the wallet
//
Wallet.prototype.delete = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
return Promise.resolve(this.bitgo.del(this.url()).result()).then(callback).catch(callback);
};
//
// labels
// List the labels for the addresses in a given wallet
//
Wallet.prototype.labels = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
const url = this.bitgo.url('/labels/' + this.id());
return Promise.resolve(this.bitgo.get(url).result('labels')).then(callback).catch(callback);
};
/**
* Rename a wallet
* @param params
* - label: the wallet's intended new name
* @param callback
* @returns {*}
*/
Wallet.prototype.setWalletName = function (params, callback) {
params = params || {};
common.validateParams(params, ['label'], [], callback);
const url = this.bitgo.url('/wallet/' + this.id());
return Promise.resolve(this.bitgo.put(url).send({ label: params.label }).result())
.then(callback)
.catch(callback);
};
//
// setLabel
// Sets a label on the provided address
//
Wallet.prototype.setLabel = function (params, callback) {
params = params || {};
common.validateParams(params, ['address', 'label'], [], callback);
const self = this;
if (!self.bitgo.verifyAddress({ address: params.address })) {
throw new Error('Invalid bitcoin address: ' + params.address);
}
const url = this.bitgo.url('/labels/' + this.id() + '/' + params.address);
return Promise.resolve(this.bitgo.put(url).send({ label: params.label }).result())
.then(callback)
.catch(callback);
};
//
// deleteLabel
// Deletes the label associated with the provided address
//
Wallet.prototype.deleteLabel = function (params, callback) {
params = params || {};
common.validateParams(params, ['address'], [], callback);
const self = this;
if (!self.bitgo.verifyAddress({ address: params.address })) {
throw new Error('Invalid bitcoin address: ' + params.address);
}
const url = this.bitgo.url('/labels/' + this.id() + '/' + params.address);
return Promise.resolve(this.bitgo.del(url).result()).then(callback).catch(callback);
};
//
// unspents
// List ALL the unspents for a given wallet
// This method will return a paged list of all unspents
//
// Parameters include:
// limit: the optional limit of unspents to collect in BTC
// minConf: only include results with this number of confirmations
// target: the amount of btc to find to spend
// instant: only find instant transactions (must specify a target)
//
Wallet.prototype.unspents = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
const allUnspents: any[] = [];
const self = this;
const getUnspentsBatch = function (skip, limit?) {
const queryObject = _.cloneDeep(params);
if (skip > 0) {
queryObject.skip = skip;
}
if (limit && limit > 0) {
queryObject.limit = limit;
}
return self.unspentsPaged(queryObject).then(function (result) {
// The API has its own limit handling. For example, the API does not support limits bigger than 500. If the limit
// specified here is bigger than that, we will have to do multiple requests with necessary limit adjustment.
for (let i = 0; i < result.unspents.length; i++) {
const unspent = result.unspents[i];
allUnspents.push(unspent);
}
// Our limit adjustment makes sure that we never fetch more unspents than we need, meaning that if we hit the
// limit, we hit it precisely
if (allUnspents.length >= params.limit) {
return allUnspents; // we aren't interested in any further unspents
}
const totalUnspentCount = result.total;
// if no target is specified and the SDK indicates that there has been a limit, we need to fetch another batch
if (!params.target && totalUnspentCount && totalUnspentCount > allUnspents.length) {
// we need to fetch the next batch
// let's just offset the current skip by the count
const newSkip = skip + result.count;
let newLimit: number | undefined;
if (limit > 0) {
// we set the new limit to be precisely the number of missing unspents to hit our own limit
newLimit = limit - allUnspents.length;
}
return getUnspentsBatch(newSkip, newLimit);
}
return allUnspents;
});
};
return getUnspentsBatch(0, params.limit).then(callback).catch(callback);
};
/**
* List the unspents (paged) for a given wallet, returning the result as an object of unspents, count, skip and total
* This method may not return all the unspents as the list is paged by the API
* @param params
* @param params.limit the optional limit of unspents to collect in BTC
* @param params.skip index in list of unspents to start paging from
* @param params.minConfirms only include results with this number of confirmations
* @param params.target the amount of btc to find to spend
* @param params.instant only find instant transactions (must specify a target)
* @param params.targetWalletUnspents desired number of unspents to have in the wallet after the tx goes through (requires target)
* @param params.minSize minimum unspent size in satoshis
* @param params.segwit request segwit unspents (defaults to true if undefined)
* @param params.allowLedgerSegwit allow segwit unspents for ledger devices (defaults to false if undefined)
* @param callback
* @returns {*}
*/
Wallet.prototype.unspentsPaged = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
if (!_.isUndefined(params.limit) && !_.isInteger(params.limit)) {
throw new Error('invalid limit - should be number');
}
if (!_.isUndefined(params.skip) && !_.isInteger(params.skip)) {
throw new Error('invalid skip - should be number');
}
if (!_.isUndefined(params.minConfirms) && !_.isInteger(params.minConfirms)) {
throw new Error('invalid minConfirms - should be number');
}
if (!_.isUndefined(params.target) && !_.isNumber(params.target)) {
throw new Error('invalid target - should be number');
}
if (!_.isUndefined(params.instant) && !_.isBoolean(params.instant)) {
throw new Error('invalid instant flag - should be boolean');
}
if (!_.isUndefined(params.segwit) && !_.isBoolean(params.segwit)) {
throw new Error('invalid segwit flag - should be boolean');
}
if (!_.isUndefined(params.targetWalletUnspents) && !_.isInteger(params.targetWalletUnspents)) {
throw new Error('invalid targetWalletUnspents flag - should be number');
}
if (!_.isUndefined(params.minSize) && !_.isNumber(params.minSize)) {
throw new Error('invalid argument: minSize must be a number');
}
if (!_.isUndefined(params.instant) && !_.isUndefined(params.minConfirms)) {
throw new Error('only one of instant and minConfirms may be defined');
}
if (!_.isUndefined(params.targetWalletUnspents) && _.isUndefined(params.target)) {
throw new Error('targetWalletUnspents can only be specified in conjunction with a target');
}
if (!_.isUndefined(params.allowLedgerSegwit) && !_.isBoolean(params.allowLedgerSegwit)) {
throw new Error('invalid argument: allowLedgerSegwit must be a boolean');
}
const queryObject = _.cloneDeep(params);
if (!_.isUndefined(params.target)) {
// skip and limit are unavailable when a target is specified
delete queryObject.skip;
delete queryObject.limit;
}
queryObject.segwit = true;
if (!_.isUndefined(params.segwit)) {
queryObject.segwit = params.segwit;
}
if (!_.isUndefined(params.allowLedgerSegwit)) {
queryObject.allowLedgerSegwit = params.allowLedgerSegwit;
}
return Promise.resolve(this.bitgo.get(this.url('/unspents')).query(queryObject).result())
.then(callback)
.catch(callback);
};
//
// transactions
// List the transactions for a given wallet
// Options include:
// TODO: Add iterators for start/count/etc
Wallet.prototype.transactions = function (params, callback) {
params = params || {};
common.validateParams(params, [], [], callback);
const args: string[] = [];
if (params.limit) {
if (!_.isInteger(params.limit)) {
throw new Error('invalid limit argument, expecting number');
}
args.push('limit=' + params.limit);
}
if (params.skip) {
if (!_.isInteger(params.skip)) {
throw new Error('invalid skip argument, expecting number');
}
args.push('skip=' + params.skip);
}
if (params.minHeight) {
if (!_.isInteger(params.minHeight)) {
throw new Error('invalid minHeight argument, expecting number');
}
args.push('minHeight=' + params.minHeight);
}
if (params.maxHeight) {
if (!_.isInteger(params.maxHeight) || params.maxHeight < 0) {
throw new Error('invalid maxHeight argument, expecting positive integer');
}
args.push('maxHeight=' + params.maxHeight);
}
if (params.minConfirms) {
if (!_.isInteger(params.minConfirms) || params.minConfirms < 0) {
throw new Error('invalid minConfirms argument, expecting positive integer');
}
args.push('minConfirms=' + params.minConfirms);
}
if (!_.isUndefined(params.compact)) {
if (!_.isBoolean(params.compact)) {
throw new Error('invalid compact argument, expecting boolean');
}
args.push('compact=' + params.compact);
}
let query = '';
if (args.length) {
query = '?' + args.join('&');
}
const url = this.url('/tx' + query);
return Promise.resolve(this.bitgo.get(url).result()).then(callback).catch(callback);
};
//
// transaction
// Get a transaction by ID for a given wallet
Wallet.prototype.getTransaction = function (params, callback) {
params = params || {};
common.validateParams(params, ['id'], [], callback);
const url = this.url('/tx/' + params.id);
return Promise.resolve(this.bitgo.get(url).result()).then(callback).catch(callback);
};
//
// pollForTransaction
// Poll a transaction until successful or times out
// Parameters:
// id: the txid
// delay: delay between polls in ms (default: 1000)
// timeout: timeout in ms (default: 10000)
Wallet.prototype.pollForTransaction = function (params, callback) {
const self = this;
params = params || {};
common.validateParams(params, ['id'], [], callback);
if (params.delay && !_.isNumber(params.delay)) {
throw new Error('invalid delay parameter');
}
if (params.timeout && !_.isNumber(params.timeout)) {
throw new Error('invalid timeout parameter');
}
params.delay = params.delay || 1000;
params.timeout = params.timeout || 10000;
const start = new Date();
const doNextPoll = function () {
return self
.getTransaction(params)
.then(function (res) {
return res;
})
.catch(function (err) {
if (err.status !== 404 || new Date().valueOf() - start.valueOf() > params.timeout) {
throw err;
}
return new Promise((resolve) => setTimeout(resolve, params.delay)).then(function () {
return doNextPoll();
});
});
};
return doNextPoll();
};
//
// transaction by sequence id
// Get a transaction by sequence id for a given wallet
Wallet.prototype.getWalletTransactionBySequenceId = function (params, callback) {
params = params || {};
common.validateParams(params, ['sequenceId'], [], callback);
const url = this.url('/tx/sequence/' + params.sequenceId);
return Promise.resolve(this.bitgo.get(url).result()).then(callback).catch(callback);
};
//
// Key chains
// Gets the user key chain for this wallet
// The user key chain is typically the first keychain of the wallet and has the encrypted xpriv stored on BitGo.
// Useful when trying to get the users' keychain from the server before decrypting to sign a transaction.
Wallet.prototype.getEncryptedUserKeychain = function (params, callback) {
return async function () {
params = params || {};
common.validateParams(params, [], [], callback);
// @ts-expect-error - no implicit this
const self = this;
async function tryKeyChain(index) {
if (!self.keychains || index >= self.keychains.length) {
const error: any = new Error('No encrypted keychains on this wallet.');
error.code = 'no_encrypted_keychain_on_wallet';
throw error;
}
const params = { xpub: self.keychains[index].xpub };
const keychain = await self.bitgo.keychains().get(params);
// If we find the xprv, then this is probably the user keychain we're looking for
keychain.walletSubPath = self.keychains[index].path;
if (keychain.encryptedXprv) {
return keychain;
}
return tryKeyChain(index + 1);
}
return tryKeyChain(0);
}
.call(this)
.then(callback)
.catch(callback);
};
//
// createTransaction
// Create a transaction (unsigned). To sign it, do signTransaction
// Parameters:
// recipients - object of recipient addresses and the amount to send to each e.g. {address:1500, address2:1500}
// fee - the blockchain fee to send (optional)
// feeRate - the fee per kb to send (optional)
// minConfirms - minimum number of confirms to use when gathering unspents
// forceChangeAtEnd - force change address to be last output (optional)
// noSplitChange - disable automatic change splitting for purposes of unspent management
// changeAddress - override the change address (optional)
// validate - extra verification of change addresses (which are always verified server-side) (defaults to global config)
// Returns:
// callback(err, { transactionHex: string, unspents: [inputs], fee: satoshis })
Wallet.prototype.createTransaction = function (params, callback) {
params = _.extend({}, params);
common.validateParams(params, [], [], callback);
if (
(!_.isNumber(params.fee) && !_.isUndefined(params.fee)) ||
(!_.isNumber(params.feeRate) && !_.isUndefined(params.feeRate)) ||
(!_.isNumber(params.minConfirms) && !_.isUndefined(params.minConfirms)) ||
(!_.isBoolean(params.forceChangeAtEnd) && !_.isUndefined(params.forceChangeAtEnd)) ||
(!_.isString(params.changeAddress) && !_.isUndefined(params.changeAddress)) ||
(!_.isBoolean(params.validate) && !_.isUndefined(params.validate)) ||
(!_.isBoolean(params.instant) && !_.isUndefined(params.instant))
) {
throw new Error('invalid argument');
}
if (!_.isObject(params.recipients)) {
throw new Error('expecting recipients object');
}
params.validate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
params.wallet = this;
return TransactionBuilder.createTransaction(params).then(callback).catch(callback);
};
//
// signTransaction
// Sign a previously created transaction with a keychain
// Parameters:
// transactionHex - serialized form of the transaction in hex
// unspents - array of unspent information, where each unspent is a chainPath
// and redeemScript with the same index as the inputs in the
// transactionHex
// keychain - Keychain containing the xprv to sign with.
// signingKey - For legacy safe wallets, the private key string.
// validate - extra verification of signatures (which are always verified server-side) (defaults to global config)
// Returns:
// callback(err, transaction)
Wallet.prototype.signTransaction = function (params, callback) {
params = _.extend({}, params);
if (params.psbt) {
return tryPromise(() => signPsbtRequest(params))
.then(callback)
.catch(callback);
}
common.validateParams(params, ['transactionHex'], [], callback);
if (!Array.isArray(params.unspents)) {
throw new Error('expecting the unspents array');
}
if ((!_.isObject(params.keychain) || !params.keychain.xprv) && !_.isString(params.signingKey)) {
// allow passing in a WIF private key for legacy safe wallet support
const error: any = new Error('expecting keychain object with xprv or signingKey WIF');
error.code = 'missing_keychain_or_signingKey';
throw error;
}
params.validate = params.validate !== undefined ? params.validate : this.bitgo.getValidate();
params.bitgo = this.bitgo;
return TransactionBuilder.signTransaction(params)
.then(function (result) {
return {
tx: result.transactionHex,
};
})
.then(callback)
.catch(callback);
};
//
// send
// Send a transaction to the Bitcoin network via BitGo.
// One of the keys is typically signed, and BitGo will sign the other (if approved) and relay it to the P2P network.
// Parameters:
// tx - the hex encoded, signed transaction to send
// Returns:
//
Wallet.prototype.sendTransaction = function (params, callback) {
params = params || {};
common.validateParams(params, ['tx'], ['message', 'otp'], callback);
return Promise.resolve(this.bitgo.post(this.bitgo.url('/tx/send')).send(params).result())
.then(function (body) {
if (body.pendingApproval) {
return _.extend(body, { status: 'pendingApproval' });
}
if (body.otp) {
return _.extend(body, { status: 'otp' });
}
return {
status: 'accepted',
tx: body.transaction,
hash: body.transactionHash,
instant: body.instant,
instantId: body.instantId,
};
})
.then(callback)
.catch(callback);
};
/**
* Share the wallet with an existing BitGo user.
* @param {string} user The recipient's user id, must have a corresponding user record in our database.
* @param {keychain} keychain The keychain to be shared with the recipient.
* @param {string} permissions A comma-separated value string that specifies the recipient's permissions if the share is accepted.
* @param {string} message The message to be used for this share.
*/
Wallet.prototype.createShare = function (params, callback) {
params = params || {};
common.validateParams(params, ['user', 'permissions'], [], callback);
if (params.keychain && !_.isEmpty(params.keychain)) {
if (
!params.keychain.xpub ||
!params.keychain.encryptedXprv ||
!params.keychain.fromPubKey ||
!params.keychain.toPubKey ||
!params.keychain.path
) {
throw new Error('requires keychain parameters - xpub, encryptedXprv, fromPubKey, toPubKey, path');