-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathwallets.ts
More file actions
1675 lines (1458 loc) · 59.9 KB
/
wallets.ts
File metadata and controls
1675 lines (1458 loc) · 59.9 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
/**
* @prettier
*/
import assert from 'assert';
import { BigNumber } from 'bignumber.js';
import { bip32 } from '@bitgo/utxo-lib';
import * as _ from 'lodash';
import { CoinFeature } from '@bitgo/statics';
import { sanitizeLegacyPath } from '../../api';
import * as common from '../../common';
import { IBaseCoin, KeychainsTriplet, SupplementGenerateWalletOptions } from '../baseCoin';
import { BitGoBase } from '../bitgoBase';
import { getSharedSecret } from '../ecdh';
import { AddKeychainOptions, Keychain, KeyIndices } from '../keychain';
import { decodeOrElse, promiseProps, RequestTracer } from '../utils';
import {
AcceptShareOptions,
AcceptShareOptionsRequest,
AddWalletOptions,
BulkAcceptShareOptions,
BulkAcceptShareResponse,
BulkUpdateWalletShareOptions,
BulkUpdateWalletShareOptionsRequest,
BulkUpdateWalletShareResponse,
GenerateBaseMpcWalletOptions,
GenerateGoAccountWalletOptions,
GenerateGoAccountWalletOptionsCodec,
GenerateLightningWalletOptions,
GenerateLightningWalletOptionsCodec,
GenerateMpcWalletOptions,
GenerateSMCMpcWalletOptions,
GenerateWalletOptions,
GetWalletByAddressOptions,
GetWalletOptions,
GoAccountWalletWithUserKeychain,
IWallets,
LightningWalletWithKeychains,
ListWalletOptions,
UpdateShareOptions,
WalletShares,
WalletWithKeychains,
} from './iWallets';
import { WalletShare } from './iWallet';
import { Wallet } from './wallet';
import { TssSettings } from '@bitgo/public-types';
import { createEvmKeyRingWallet, validateEvmKeyRingWalletParams } from '../evm/evmUtils';
/**
* Check if a wallet is a WalletWithKeychains
*/
export function isWalletWithKeychains(
wallet: WalletWithKeychains | LightningWalletWithKeychains | GoAccountWalletWithUserKeychain
): wallet is WalletWithKeychains {
return wallet.responseType === 'WalletWithKeychains';
}
export class Wallets implements IWallets {
private readonly bitgo: BitGoBase;
private readonly baseCoin: IBaseCoin;
constructor(bitgo: BitGoBase, baseCoin: IBaseCoin) {
this.bitgo = bitgo;
this.baseCoin = baseCoin;
}
/**
* Get a wallet by ID (proxy for getWallet)
* @param params
*/
async get(params: GetWalletOptions = {}): Promise<Wallet> {
return this.getWallet(params);
}
/**
* List a user's wallets
* @param params
* @returns {*}
*/
async list(params: ListWalletOptions & { enterprise?: string } = {}): Promise<{ wallets: Wallet[] }> {
if (params.skip && params.prevId) {
throw new Error('cannot specify both skip and prevId');
}
const body = (await this.bitgo.get(this.baseCoin.url('/wallet')).query(params).result()) as any;
body.wallets = body.wallets.map((w) => new Wallet(this.bitgo, this.baseCoin, w));
return body;
}
/**
* add
* Add a new wallet (advanced mode).
* This allows you to manually submit the keys, type, m and n of the wallet
* Parameters include:
* "label": label of the wallet to be shown in UI
* "m": number of keys required to unlock wallet (2)
* "n": number of keys available on the wallet (3)
* "keys": array of keychain ids
*/
async add(params: AddWalletOptions): Promise<any> {
params = params || {};
common.validateParams(params, [], ['label', 'enterprise', 'type']);
if (typeof params.label !== 'string') {
throw new Error('missing required string parameter label');
}
validateEvmKeyRingWalletParams(params, this.baseCoin);
if (!params.evmKeyRingReferenceWalletId && params.type !== 'custodial') {
// no need to pass keys for (single) custodial wallets
if (Array.isArray(params.keys) === false || !_.isNumber(params.m) || !_.isNumber(params.n)) {
throw new Error('invalid argument');
}
// TODO: support more types of multisig
if (!this.baseCoin.isValidMofNSetup(params)) {
throw new Error('unsupported multi-sig type');
}
}
if (params.gasPrice && !_.isNumber(params.gasPrice)) {
throw new Error('invalid argument for gasPrice - number expected');
}
if (params.walletVersion) {
if (!_.isNumber(params.walletVersion)) {
throw new Error('invalid argument for walletVersion - number expected');
}
if (params.multisigType === 'tss' && this.baseCoin.getMPCAlgorithm() === 'ecdsa' && params.walletVersion === 3) {
const tssSettings: TssSettings = await this.bitgo
.get(this.bitgo.microservicesUrl('/api/v2/tss/settings'))
.result();
const multisigTypeVersion =
tssSettings.coinSettings[this.baseCoin.getFamily()]?.walletCreationSettings?.multiSigTypeVersion;
if (multisigTypeVersion === 'MPCv2') {
params.walletVersion = 5;
}
}
}
if (params.tags && Array.isArray(params.tags) === false) {
throw new Error('invalid argument for tags - array expected');
}
if (params.clientFlags && Array.isArray(params.clientFlags) === false) {
throw new Error('invalid argument for clientFlags - array expected');
}
if (params.isCold && !_.isBoolean(params.isCold)) {
throw new Error('invalid argument for isCold - boolean expected');
}
if (params.isCustodial && !_.isBoolean(params.isCustodial)) {
throw new Error('invalid argument for isCustodial - boolean expected');
}
if (params.address && (!_.isString(params.address) || !this.baseCoin.isValidAddress(params.address))) {
throw new Error('invalid argument for address - valid address string expected');
}
const newWallet = await this.bitgo.post(this.baseCoin.url('/wallet/add')).send(params).result();
return {
wallet: new Wallet(this.bitgo, this.baseCoin, newWallet),
};
}
private async generateLightningWallet(params: GenerateLightningWalletOptions): Promise<LightningWalletWithKeychains> {
const reqId = new RequestTracer();
this.bitgo.setRequestTracer(reqId);
const { label, passphrase, enterprise, passcodeEncryptionCode, subType, lightningProvider } = params;
// TODO BTC-1899: only userAuth key is required for custodial lightning wallet. all 3 keys are required for self custodial lightning.
// to avoid changing the platform for custodial flow, let us all 3 keys both wallet types.
const keychainPromises = ([undefined, 'userAuth', 'nodeAuth'] as const).map((purpose) => {
return async (): Promise<Keychain> => {
const keychain = this.baseCoin.keychains().create();
const keychainParams: AddKeychainOptions = {
pub: keychain.pub,
encryptedPrv: this.bitgo.encrypt({ password: passphrase, input: keychain.prv }),
originalPasscodeEncryptionCode: purpose === undefined ? passcodeEncryptionCode : undefined,
coinSpecific: purpose === undefined ? undefined : { [this.baseCoin.getChain()]: { purpose } },
keyType: 'independent',
source: 'user',
};
return await this.baseCoin.keychains().add(keychainParams);
};
});
const { userKeychain, userAuthKeychain, nodeAuthKeychain } = await promiseProps({
userKeychain: keychainPromises[0](),
userAuthKeychain: keychainPromises[1](),
nodeAuthKeychain: keychainPromises[2](),
});
const walletParams: SupplementGenerateWalletOptions = {
label,
m: 1,
n: 1,
type: 'hot',
subType,
enterprise,
keys: [userKeychain.id],
coinSpecific: { [this.baseCoin.getChain()]: { keys: [userAuthKeychain.id, nodeAuthKeychain.id] } },
lightningProvider,
};
const newWallet = await this.bitgo.post(this.baseCoin.url('/wallet/add')).send(walletParams).result();
const wallet = new Wallet(this.bitgo, this.baseCoin, newWallet);
return {
wallet,
userKeychain,
userAuthKeychain,
nodeAuthKeychain,
responseType: 'LightningWalletWithKeychains',
};
}
/**
* Generate a Go Account wallet
* @param params GenerateGoAccountWalletOptions
* @returns Promise<GoAccountWalletWithUserKeychain>
*/
private async generateGoAccountWallet(
params: GenerateGoAccountWalletOptions
): Promise<GoAccountWalletWithUserKeychain> {
const reqId = new RequestTracer();
this.bitgo.setRequestTracer(reqId);
const { label, passphrase, enterprise, passcodeEncryptionCode } = params;
const keychain = this.baseCoin.keychains().create();
const keychainParams: AddKeychainOptions = {
pub: keychain.pub,
encryptedPrv: this.bitgo.encrypt({ password: passphrase, input: keychain.prv }),
originalPasscodeEncryptionCode: passcodeEncryptionCode,
keyType: 'independent',
source: 'user',
};
const userKeychain = await this.baseCoin.keychains().add(keychainParams);
const walletParams: SupplementGenerateWalletOptions = {
label,
m: 1,
n: 1,
type: 'trading',
enterprise,
keys: [userKeychain.id],
};
const newWallet = await this.bitgo.post(this.baseCoin.url('/wallet/add')).send(walletParams).result();
const wallet = new Wallet(this.bitgo, this.baseCoin, newWallet);
const result: GoAccountWalletWithUserKeychain = {
wallet,
userKeychain,
responseType: 'GoAccountWalletWithUserKeychain',
};
// Add warning if the user keychain has an encrypted private key
if (!_.isUndefined(userKeychain.encryptedPrv)) {
result.warning = 'Be sure to backup the user keychain -- it is not stored anywhere else!';
}
return result;
}
/**
* Generate a new wallet
* 1. Creates the user keychain locally on the client, and encrypts it with the provided passphrase
* 2. If no pub was provided, creates the backup keychain locally on the client, and encrypts it with the provided passphrase
* 3. Uploads the encrypted user and backup keychains to BitGo
* 4. Creates the BitGo key on the service
* 5. Creates the wallet on BitGo with the 3 public keys above
* @param params
* @param params.label Label for the wallet
* @param params.passphrase Passphrase to be used to encrypt the user and backup keychains
* @param params.userKey User xpub
* @param params.backupXpub Backup xpub
* @param params.backupXpubProvider
* @param params.enterprise the enterpriseId
* @param params.disableTransactionNotifications
* @param params.passcodeEncryptionCode optional this is a recovery code that can be used to decrypt the original passphrase in a recovery case.
* The user must generate and keep the encrypted original passphrase safe while this code is stored on BitGo
* @param params.coldDerivationSeed optional seed for SMC wallets
* @param params.gasPrice
* @param params.disableKRSEmail
* @param params.walletVersion
* @param params.multisigType optional multisig type, 'onchain' or 'tss' or 'blsdkg'; if absent, we will defer to the coin's default type
* @param params.isDistributedCustody optional parameter for creating bitgo key. This is only necessary if you want to create
* a distributed custody wallet. If provided, you must have the enterprise license and pass in
* `params.enterprise` into `generateWallet` as well.
* @param params.type optional wallet type, 'hot' or 'cold' or 'custodial'; if absent, we will defer to 'hot'
* @param params.bitgoKeyId optional bitgo key id for SMC TSS wallets
* @param params.commonKeychain optional common keychain for SMC TSS wallets
*
* @returns {*}
*/
async generateWallet(
params: GenerateWalletOptions = {}
): Promise<WalletWithKeychains | LightningWalletWithKeychains | GoAccountWalletWithUserKeychain> {
// Assign the default multiSig type value based on the coin
if (!params.multisigType) {
params.multisigType = this.baseCoin.getDefaultMultisigType();
}
if (this.baseCoin.getFamily() === 'lnbtc') {
const options = decodeOrElse(
GenerateLightningWalletOptionsCodec.name,
GenerateLightningWalletOptionsCodec,
params,
(errors) => {
throw new Error(`error(s) parsing generate lightning wallet request params: ${errors}`);
}
);
const walletData = await this.generateLightningWallet(options);
walletData.encryptedWalletPassphrase = this.bitgo.encrypt({
input: options.passphrase,
password: options.passcodeEncryptionCode,
});
return walletData;
}
// Go Account wallet generation
if (this.baseCoin.getFamily() === 'ofc' && params.type === 'trading') {
const options = decodeOrElse(
GenerateGoAccountWalletOptionsCodec.name,
GenerateGoAccountWalletOptionsCodec,
params,
(errors) => {
throw new Error(`error(s) parsing generate go account request params: ${errors}`);
}
);
const walletData = await this.generateGoAccountWallet(options);
walletData.encryptedWalletPassphrase = this.bitgo.encrypt({
input: options.passphrase,
password: options.passcodeEncryptionCode,
});
return walletData;
}
common.validateParams(params, ['label'], ['passphrase', 'userKey', 'backupXpub']);
if (typeof params.label !== 'string') {
throw new Error('missing required string parameter label');
}
const { type = 'hot', label, passphrase, enterprise, isDistributedCustody, evmKeyRingReferenceWalletId } = params;
const isTss = params.multisigType === 'tss' && this.baseCoin.supportsTss();
const canEncrypt = !!passphrase && typeof passphrase === 'string';
if (validateEvmKeyRingWalletParams(params, this.baseCoin)) {
return await createEvmKeyRingWallet({
label,
evmKeyRingReferenceWalletId: evmKeyRingReferenceWalletId!,
bitgo: this.bitgo,
baseCoin: this.baseCoin,
});
}
const walletParams: SupplementGenerateWalletOptions = {
label: label,
m: 2,
n: 3,
keys: [],
type: !!params.userKey && params.multisigType !== 'onchain' ? 'cold' : type,
};
if (!_.isUndefined(params.passcodeEncryptionCode)) {
if (!_.isString(params.passcodeEncryptionCode)) {
throw new Error('passcodeEncryptionCode must be a string');
}
}
if (!_.isUndefined(enterprise)) {
if (!_.isString(enterprise)) {
throw new Error('invalid enterprise argument, expecting string');
}
walletParams.enterprise = enterprise;
}
// EVM TSS wallets must use wallet version 3, 5 and 6
if (
isTss &&
this.baseCoin.isEVM() &&
!evmKeyRingReferenceWalletId &&
!(params.walletVersion === 3 || params.walletVersion === 5 || params.walletVersion === 6)
) {
throw new Error('EVM TSS wallets are only supported for wallet version 3, 5 and 6');
}
if (isTss) {
if (!this.baseCoin.supportsTss()) {
throw new Error(`coin ${this.baseCoin.getFamily()} does not support TSS at this time`);
}
if (
(params.walletVersion === 5 || params.walletVersion === 6) &&
!this.baseCoin.getConfig().features.includes(CoinFeature.MPCV2)
) {
throw new Error(`coin ${this.baseCoin.getFamily()} does not support TSS MPCv2 at this time`);
}
assert(enterprise, 'enterprise is required for TSS wallet');
if (type === 'cold') {
// validate
assert(params.bitgoKeyId, 'bitgoKeyId is required for SMC TSS wallet');
assert(params.commonKeychain, 'commonKeychain is required for SMC TSS wallet');
return this.generateSMCMpcWallet({
multisigType: 'tss',
label,
enterprise,
walletVersion: params.walletVersion,
bitgoKeyId: params.bitgoKeyId,
commonKeychain: params.commonKeychain,
coldDerivationSeed: params.coldDerivationSeed,
});
}
if (type === 'custodial') {
return this.generateCustodialMpcWallet({
multisigType: 'tss',
label,
enterprise,
walletVersion: params.walletVersion,
});
}
assert(passphrase, 'cannot generate TSS keys without passphrase');
const walletData = await this.generateMpcWallet({
multisigType: 'tss',
label,
passphrase,
originalPasscodeEncryptionCode: params.passcodeEncryptionCode,
enterprise,
walletVersion: params.walletVersion,
});
if (params.passcodeEncryptionCode) {
walletData.encryptedWalletPassphrase = this.bitgo.encrypt({
input: passphrase,
password: params.passcodeEncryptionCode,
});
}
return walletData;
}
// Handle distributed custody
if (isDistributedCustody) {
if (!enterprise) {
throw new Error('must provide enterprise when creating distributed custody wallet');
}
if (!type || type !== 'cold') {
throw new Error('distributed custody wallets must be type: cold');
}
}
const hasBackupXpub = !!params.backupXpub;
const hasBackupXpubProvider = !!params.backupXpubProvider;
if (hasBackupXpub && hasBackupXpubProvider) {
throw new Error('Cannot provide more than one backupXpub or backupXpubProvider flag');
}
if (params.gasPrice && params.eip1559) {
throw new Error('can not use both eip1559 and gasPrice values');
}
if (!_.isUndefined(params.disableTransactionNotifications)) {
if (!_.isBoolean(params.disableTransactionNotifications)) {
throw new Error('invalid disableTransactionNotifications argument, expecting boolean');
}
walletParams.disableTransactionNotifications = params.disableTransactionNotifications;
}
if (!_.isUndefined(params.gasPrice)) {
const gasPriceBN = new BigNumber(params.gasPrice);
if (gasPriceBN.isNaN()) {
throw new Error('invalid gas price argument, expecting number or number as string');
}
walletParams.gasPrice = gasPriceBN.toString();
}
if (!_.isUndefined(params.eip1559) && !_.isEmpty(params.eip1559)) {
const maxFeePerGasBN = new BigNumber(params.eip1559.maxFeePerGas);
if (maxFeePerGasBN.isNaN()) {
throw new Error('invalid max fee argument, expecting number or number as string');
}
const maxPriorityFeePerGasBN = new BigNumber(params.eip1559.maxPriorityFeePerGas);
if (maxPriorityFeePerGasBN.isNaN()) {
throw new Error('invalid priority fee argument, expecting number or number as string');
}
walletParams.eip1559 = {
maxFeePerGas: maxFeePerGasBN.toString(),
maxPriorityFeePerGas: maxPriorityFeePerGasBN.toString(),
};
}
if (!_.isUndefined(params.disableKRSEmail)) {
if (!_.isBoolean(params.disableKRSEmail)) {
throw new Error('invalid disableKRSEmail argument, expecting boolean');
}
walletParams.disableKRSEmail = params.disableKRSEmail;
}
if (!_.isUndefined(params.walletVersion)) {
if (!_.isNumber(params.walletVersion)) {
throw new Error('invalid walletVersion provided, expecting number');
}
walletParams.walletVersion = params.walletVersion;
}
// Ensure each krsSpecific param is either a string, boolean, or number
const { krsSpecific } = params;
if (!_.isUndefined(krsSpecific)) {
Object.keys(krsSpecific).forEach((key) => {
const val = krsSpecific[key];
if (!_.isBoolean(val) && !_.isString(val) && !_.isNumber(val)) {
throw new Error('krsSpecific object contains illegal values. values must be strings, booleans, or numbers');
}
});
}
let derivationPath: string | undefined = undefined;
const reqId = new RequestTracer();
if (params.type === 'custodial' && (params.multisigType ?? 'onchain') === 'onchain') {
// for custodial multisig, when the wallet is created on the platfor side, the keys are not needed
walletParams.n = undefined;
walletParams.m = undefined;
walletParams.keys = undefined;
walletParams.keySignatures = undefined;
const newWallet = await this.bitgo.post(this.baseCoin.url('/wallet/add')).send(walletParams).result(); // returns the ids
const userKeychain = this.baseCoin.keychains().get({ id: newWallet.keys[KeyIndices.USER], reqId });
const backupKeychain = this.baseCoin.keychains().get({ id: newWallet.keys[KeyIndices.BACKUP], reqId });
const bitgoKeychain = this.baseCoin.keychains().get({ id: newWallet.keys[KeyIndices.BITGO], reqId });
const [userKey, bitgoKey, backupKey] = await Promise.all([userKeychain, bitgoKeychain, backupKeychain]);
const result: WalletWithKeychains = {
wallet: new Wallet(this.bitgo, this.baseCoin, newWallet),
userKeychain: userKey,
backupKeychain: bitgoKey,
bitgoKeychain: backupKey,
responseType: 'WalletWithKeychains',
};
return result;
} else {
const userKeychainPromise = async (): Promise<Keychain> => {
let userKeychainParams;
let userKeychain;
// User provided user key
if (params.userKey) {
userKeychain = { pub: params.userKey };
userKeychainParams = userKeychain;
if (params.coldDerivationSeed) {
// the derivation only makes sense when a key already exists
const derivation = this.baseCoin.deriveKeyWithSeed({
key: params.userKey,
seed: params.coldDerivationSeed,
});
derivationPath = derivation.derivationPath;
userKeychain.pub = derivation.key;
userKeychain.derivedFromParentWithSeed = params.coldDerivationSeed;
}
} else {
if (!canEncrypt) {
throw new Error('cannot generate user keypair without passphrase');
}
// Create the user key.
userKeychain = this.baseCoin.keychains().create();
userKeychain.encryptedPrv = this.bitgo.encrypt({ password: passphrase, input: userKeychain.prv });
userKeychainParams = {
pub: userKeychain.pub,
encryptedPrv: userKeychain.encryptedPrv,
originalPasscodeEncryptionCode: params.passcodeEncryptionCode,
};
}
userKeychainParams.reqId = reqId;
const newUserKeychain = await this.baseCoin.keychains().add(userKeychainParams);
return _.extend({}, newUserKeychain, userKeychain);
};
const backupKeychainPromise = async (): Promise<Keychain> => {
if (params.backupXpubProvider) {
// If requested, use a KRS or backup key provider
return this.baseCoin.keychains().createBackup({
provider: params.backupXpubProvider || 'defaultRMGBackupProvider',
disableKRSEmail: params.disableKRSEmail,
krsSpecific: params.krsSpecific,
type: this.baseCoin.getChain(),
passphrase: params.passphrase,
reqId,
});
}
// User provided backup xpub
if (params.backupXpub) {
// user provided backup ethereum address
return this.baseCoin.keychains().add({
pub: params.backupXpub,
source: 'backup',
reqId,
});
} else {
if (!canEncrypt) {
throw new Error('cannot generate backup keypair without passphrase');
}
// No provided backup xpub or address, so default to creating one here
return this.baseCoin.keychains().createBackup({ reqId, passphrase: params.passphrase });
}
};
const { userKeychain, backupKeychain, bitgoKeychain }: KeychainsTriplet = await promiseProps({
userKeychain: userKeychainPromise(),
backupKeychain: backupKeychainPromise(),
bitgoKeychain: this.baseCoin
.keychains()
.createBitGo({ enterprise: params.enterprise, reqId, isDistributedCustody: params.isDistributedCustody }),
});
walletParams.keys = [userKeychain.id, backupKeychain.id, bitgoKeychain.id];
const { prv } = userKeychain;
if (_.isString(prv)) {
assert(backupKeychain.pub);
assert(bitgoKeychain.pub);
walletParams.keySignatures = {
backup: (await this.baseCoin.signMessage({ prv }, backupKeychain.pub)).toString('hex'),
bitgo: (await this.baseCoin.signMessage({ prv }, bitgoKeychain.pub)).toString('hex'),
};
}
const keychains = {
userKeychain,
backupKeychain,
bitgoKeychain,
};
const finalWalletParams = await this.baseCoin.supplementGenerateWallet(walletParams, keychains);
if (_.includes(['xrp', 'xlm', 'cspr'], this.baseCoin.getFamily()) && !_.isUndefined(params.rootPrivateKey)) {
walletParams.rootPrivateKey = params.rootPrivateKey;
}
this.bitgo.setRequestTracer(reqId);
const newWallet = await this.bitgo.post(this.baseCoin.url('/wallet/add')).send(finalWalletParams).result();
const result: WalletWithKeychains = {
wallet: new Wallet(this.bitgo, this.baseCoin, newWallet),
userKeychain: userKeychain,
backupKeychain: backupKeychain,
bitgoKeychain: bitgoKeychain,
responseType: 'WalletWithKeychains',
};
if (!_.isUndefined(backupKeychain.prv)) {
result.warning = 'Be sure to backup the backup keychain -- it is not stored anywhere else!';
}
if (!_.isUndefined(derivationPath)) {
userKeychain.derivationPath = derivationPath;
}
if (canEncrypt && params.passcodeEncryptionCode) {
result.encryptedWalletPassphrase = this.bitgo.encrypt({
input: passphrase,
password: params.passcodeEncryptionCode,
});
}
return result;
}
}
/**
* List the user's wallet shares
* @param params
*/
async listShares(params: Record<string, unknown> = {}): Promise<any> {
return await this.bitgo.get(this.baseCoin.url('/walletshare')).result();
}
/**
* List the user's wallet shares v2
* @returns {Promise<WalletShares>}
*/
async listSharesV2(): Promise<WalletShares> {
return await this.bitgo.get(this.bitgo.url('/walletshares', 2)).result();
}
/**
* Gets a wallet share information, including the encrypted sharing keychain. requires unlock if keychain is present.
* @param params
* @param params.walletShareId - the wallet share to get information on
*/
async getShare(params: { walletShareId?: string } = {}): Promise<any> {
common.validateParams(params, ['walletShareId'], []);
return await this.bitgo.get(this.baseCoin.url('/walletshare/' + params.walletShareId)).result();
}
/**
* Update a wallet share
* @param params.walletShareId - the wallet share to update
* @param params.state - the new state of the wallet share
* @param params
*/
async updateShare(params: UpdateShareOptions = {}): Promise<any> {
common.validateParams(params, ['walletShareId'], []);
return await this.bitgo
.post(this.baseCoin.url('/walletshare/' + params.walletShareId))
.send(params)
.result();
}
/**
* Bulk accept wallet shares
* @param params AcceptShareOptionsRequest[]
* @returns {Promise<BulkAcceptShareResponse>}
*/
async bulkAcceptShareRequest(params: AcceptShareOptionsRequest[]): Promise<BulkAcceptShareResponse> {
return await this.bulkAcceptShareRequestWithRetry(params);
}
private async bulkAcceptShareRequestWithRetry(params: AcceptShareOptionsRequest[]): Promise<BulkAcceptShareResponse> {
// Server has a limit of approximately 1MB for payload size
let MAX_PAYLOAD_SIZE = 950000; // ~950KB to leave some buffer
// Function to calculate the size of a payload
const calculatePayloadSize = (items: AcceptShareOptionsRequest[]): number => {
return Buffer.byteLength(JSON.stringify({ keysForWalletShares: items }), 'utf8');
};
const results: any[] = [];
const remainingParams = [...params];
while (remainingParams.length > 0) {
// Build optimal batch by adding items until we reach size limit
const batch: AcceptShareOptionsRequest[] = [];
// Start with empty batch
// Add items one by one while monitoring payload size
while (remainingParams.length > 0) {
// Test adding the next item
const testBatch = [...batch, remainingParams[0]];
const testSize = calculatePayloadSize(testBatch);
// If adding this item would exceed the size limit, stop adding
if (testSize > MAX_PAYLOAD_SIZE && batch.length > 0) {
break;
}
// Otherwise, add the item to the batch
batch.push(remainingParams.shift()!);
}
// Handle case where even a single item is too large
if (batch.length === 0 && remainingParams.length > 0) {
// Send just the first item even if it's oversized
batch.push(remainingParams.shift()!);
}
const payloadObj = { keysForWalletShares: batch };
try {
const result = await this.bitgo.put(this.bitgo.url('/walletshares/accept', 2)).send(payloadObj).result();
if (result.acceptedWalletShares && Array.isArray(result.acceptedWalletShares)) {
results.push(...result.acceptedWalletShares);
}
} catch (error: any) {
if (error.status === 413 && batch.length > 1) {
// If we still get 413 with multiple items, put them back and try with half the batch size
remainingParams.unshift(...batch);
MAX_PAYLOAD_SIZE = Math.floor(MAX_PAYLOAD_SIZE / 2); // Reduce size limit for next attempt
continue;
}
throw error;
}
}
return {
acceptedWalletShares: results,
};
}
async bulkUpdateWalletShareRequest(
params: BulkUpdateWalletShareOptionsRequest[]
): Promise<BulkUpdateWalletShareResponse> {
return await this.bitgo
.put(this.bitgo.url('/walletshares/update', 2))
.send({
shares: params,
})
.result();
}
/**
* Resend a wallet share invitation email
* @param params
* @param params.walletShareId - the wallet share whose invitiation should be resent
*/
async resendShareInvite(params: { walletShareId?: string } = {}): Promise<any> {
common.validateParams(params, ['walletShareId'], []);
const urlParts = params.walletShareId + '/resendemail';
return this.bitgo.post(this.baseCoin.url('/walletshare/' + urlParts)).result();
}
/**
* Cancel a wallet share
* @param params
* @param params.walletShareId - the wallet share to update
*/
async cancelShare(params: { walletShareId?: string } = {}): Promise<any> {
common.validateParams(params, ['walletShareId'], []);
return await this.bitgo
.del(this.baseCoin.url('/walletshare/' + params.walletShareId))
.send()
.result();
}
/**
* Re-share wallet with existing spenders of the wallet
* @param walletId
* @param userPassword
*/
async reshareWalletWithSpenders(walletId: string, userPassword: string): Promise<void> {
const wallet = await this.get({ id: walletId });
if (!wallet?._wallet?.enterprise) {
throw new Error('Enterprise not found for the wallet');
}
const enterpriseUsersResponse = await this.bitgo
.get(this.bitgo.url(`/enterprise/${wallet?._wallet?.enterprise}/user`))
.result();
// create a map of users for easy lookup - we need the user email id to share the wallet
const usersMap = new Map(
[...enterpriseUsersResponse?.adminUsers, ...enterpriseUsersResponse?.nonAdminUsers].map((obj) => [obj.id, obj])
);
if (wallet._wallet.users) {
for (const user of wallet._wallet.users) {
const userObject = usersMap.get(user.user);
if (user.permissions.includes('spend') && !user.permissions.includes('admin') && userObject) {
const shareParams = {
walletId: walletId,
user: user.user,
permissions: user.permissions.join(','),
walletPassphrase: userPassword,
email: userObject.email.email,
reshare: true,
skipKeychain: false,
};
await wallet.shareWallet(shareParams);
}
}
}
}
/**
* Accepts a wallet share, adding the wallet to the user's list
* Needs a user's password to decrypt the shared key
*
* @param params
* @param params.walletShareId - the wallet share to accept
* @param params.userPassword - (required if more a keychain was shared) user's password to decrypt the shared wallet
* @param params.newWalletPassphrase - new wallet passphrase for saving the shared wallet prv.
* If left blank and a wallet with more than view permissions was shared,
* then the user's login password is used.
* @param params.overrideEncryptedPrv - set only if the prv was received out-of-band.
*/
async acceptShare(params: AcceptShareOptions = {}): Promise<any> {
common.validateParams(params, ['walletShareId'], ['overrideEncryptedPrv', 'userPassword', 'newWalletPassphrase']);
let encryptedPrv = params.overrideEncryptedPrv;
const walletShare = await this.getShare({ walletShareId: params.walletShareId });
// Multi-user-key case: requires user to provide their own public key in addition to the encrypted private key
if (walletShare.userMultiKeyRotationRequired) {
if (_.isUndefined(params.userPassword)) {
throw new Error('userPassword param must be provided to generate user keychain');
}
const walletKeychain = this.baseCoin.keychains().create();
const encryptedPrv = this.bitgo.encrypt({
password: params.newWalletPassphrase || params.userPassword,
input: walletKeychain.prv,
});
const updateParams: UpdateShareOptions = {
walletShareId: params.walletShareId,
state: 'accepted',
encryptedPrv: encryptedPrv,
pub: walletKeychain.pub,
};
// Note: Unlike keychainOverrideRequired, we do NOT reshare the wallet with spenders
// This is a key difference - multi-key-user-key wallets don't require reshare
return this.updateShare(updateParams);
}
// Keychain override case: requires user keychain creation and signing
if (
walletShare.keychainOverrideRequired &&
walletShare.permissions.indexOf('admin') !== -1 &&
walletShare.permissions.indexOf('spend') !== -1
) {
if (_.isUndefined(params.userPassword)) {
throw new Error('userPassword param must be provided to decrypt shared key');
}
const walletKeychain = await this.baseCoin.keychains().createUserKeychain(params.userPassword);
if (_.isUndefined(walletKeychain.encryptedPrv)) {
throw new Error('encryptedPrv was not found on wallet keychain');
}
const payload = {
tradingAccountId: walletShare.wallet,
pubkey: walletKeychain.pub,
timestamp: new Date().toISOString(),
};
const payloadString = JSON.stringify(payload);
const privateKey = this.bitgo.decrypt({
password: params.userPassword,
input: walletKeychain.encryptedPrv,
});
const signature = await this.baseCoin.signMessage({ prv: privateKey }, payloadString);
const response = await this.updateShare({
walletShareId: params.walletShareId,
state: 'accepted',
keyId: walletKeychain.id,
signature: signature.toString('hex'),
payload: payloadString,
});
// If the wallet share was accepted successfully (changed=true), reshare the wallet with the spenders
if (response.changed && response.state === 'accepted') {
try {
await this.reshareWalletWithSpenders(walletShare.wallet, params.userPassword);
} catch (e) {
// TODO: PX-3826
// Do nothing
}
}
return response;
}
// Return right away if there is no keychain to decrypt, or if explicit encryptedPrv was provided
if (!walletShare.keychain || !walletShare.keychain.encryptedPrv || encryptedPrv) {
return this.updateShare({
walletShareId: params.walletShareId,
state: 'accepted',
});
}
// More than viewing was requested, so we need to process the wallet keys using the shared ecdh scheme
if (_.isUndefined(params.userPassword)) {
throw new Error('userPassword param must be provided to decrypt shared key');
}
const sharingKeychain = (await this.bitgo.getECDHKeychain()) as any;
if (_.isUndefined(sharingKeychain.encryptedXprv)) {
throw new Error('encryptedXprv was not found on sharing keychain');
}
// Now we have the sharing keychain, we can work out the secret used for sharing the wallet with us
sharingKeychain.prv = this.bitgo.decrypt({
password: params.userPassword,
input: sharingKeychain.encryptedXprv,
});
const secret = getSharedSecret(
// Derive key by path (which is used between these 2 users only)
bip32.fromBase58(sharingKeychain.prv).derivePath(sanitizeLegacyPath(walletShare.keychain.path)),
Buffer.from(walletShare.keychain.fromPubKey, 'hex')
).toString('hex');
// Yes! We got the secret successfully here, now decrypt the shared wallet prv
const decryptedSharedWalletPrv = this.bitgo.decrypt({
password: secret,
input: walletShare.keychain.encryptedPrv,
});
// We will now re-encrypt the wallet with our own password
const newWalletPassphrase = params.newWalletPassphrase || params.userPassword;
encryptedPrv = this.bitgo.encrypt({
password: newWalletPassphrase,
input: decryptedSharedWalletPrv,
});
const updateParams: UpdateShareOptions = {
walletShareId: params.walletShareId,