Repository navigation
Expand file tree
/
Copy pathbaseTSSUtils.ts
More file actions
736 lines (684 loc) · 27.9 KB
/
Copy pathbaseTSSUtils.ts
File metadata and controls
736 lines (684 loc) · 27.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
import { EncryptionVersion, IRequestTracer } from '../../../api';
import * as openpgp from 'openpgp';
import { Key, readKey, SerializedKeyPair } from 'openpgp';
import { IBaseCoin, KeychainsTriplet } from '../../baseCoin';
import { BitGoBase } from '../../bitgoBase';
import { Keychain, KeyIndices, WebauthnKeyEncryptionInfo } from '../../keychain';
import { getTxRequest } from '../../tss';
import { IWallet } from '../../wallet';
import { MpcUtils } from '../mpcUtils';
import * as _ from 'lodash';
import {
BitgoGPGPublicKey,
BitgoHeldBackupKeyShare,
CommitmentShareRecord,
CreateBitGoKeychainParamsBase,
CreateKeychainParamsBase,
CustomCommitmentGeneratingFunction,
CustomEddsaMPCv2SigningRound1GeneratingFunction,
CustomEddsaMPCv2SigningRound2GeneratingFunction,
CustomEddsaMPCv2SigningRound3GeneratingFunction,
CustomGShareGeneratingFunction,
CustomKShareGeneratingFunction,
CustomMPCv2SigningRound1GeneratingFunction,
CustomMPCv2SigningRound2GeneratingFunction,
CustomMPCv2SigningRound3GeneratingFunction,
CustomMuDeltaShareGeneratingFunction,
CustomPaillierModulusGetterFunction,
CustomRShareGeneratingFunction,
CustomSShareGeneratingFunction,
EncryptedSignerShareRecord,
IntentOptionsForMessage,
IntentOptionsForTypedData,
ITssUtils,
PopulatedIntentForMessageSigning,
PopulatedIntentForTypedDataSigning,
PrebuildTransactionWithIntentOptions,
RequestType,
SignatureShareRecord,
TSSParams,
TSSParamsForMessage,
TssSignTxRequestParamsWithPrv,
TxRequest,
TxRequestVersion,
} from './baseTypes';
import { GShare, SignShare } from '../../../account-lib/mpc/tss';
import { RequestTracer } from '../util';
import { envRequiresBitgoPubGpgKeyConfig, getBitgoMpcGpgPubKey } from '../../tss/bitgoPubKeys';
import { getBitgoGpgPubKey } from '../opengpgUtils';
import assert from 'assert';
import { MessageStandardType } from '../messageTypes';
/**
* BaseTssUtil class which different signature schemes have to extend
*/
export default class BaseTssUtils<KeyShare> extends MpcUtils implements ITssUtils<KeyShare> {
private _wallet?: IWallet;
protected bitgoPublicGpgKey: openpgp.Key;
protected bitgoMPCv2PublicGpgKey: openpgp.Key | undefined;
protected bitgoEddsaMpcv2PublicGpgKey: openpgp.Key | undefined;
constructor(bitgo: BitGoBase, baseCoin: IBaseCoin, wallet?: IWallet) {
super(bitgo, baseCoin);
this._wallet = wallet;
}
get wallet(): IWallet {
if (_.isNil(this._wallet)) {
throw new Error('Wallet not defined');
}
return this._wallet;
}
protected async setBitgoGpgPubKey(bitgo) {
const { mpcV1, mpcV2, eddsaMpcV2 } = await getBitgoGpgPubKey(bitgo);
// Do not unset the MPCv1 key if it is already set. This is to avoid unsetting if extra constants api calls fail.
if (mpcV1 !== undefined) {
this.bitgoPublicGpgKey = mpcV1;
}
// Do not unset the MPCv2 key if it is already set
if (mpcV2 !== undefined) {
this.bitgoMPCv2PublicGpgKey = mpcV2;
}
// Do not unset the EdDSA MPCv2 key if it is already set
if (eddsaMpcV2 !== undefined) {
this.bitgoEddsaMpcv2PublicGpgKey = eddsaMpcV2;
}
}
public async pickBitgoPubGpgKeyForSigning(
isMpcv2: boolean,
reqId?: IRequestTracer,
enterpriseId?: string,
isEddsaMpcv2?: boolean
): Promise<openpgp.Key> {
let bitgoGpgPubKey;
try {
const bitgoKeyChain = await this.baseCoin.keychains().get({ id: this.wallet.keyIds()[KeyIndices.BITGO], reqId });
if (!bitgoKeyChain || !bitgoKeyChain.hsmType) {
throw new Error('Missing Bitgo GPG Pub Key Type.');
}
bitgoGpgPubKey = await openpgp.readKey({
armoredKey: getBitgoMpcGpgPubKey(
this.bitgo.getEnv(),
bitgoKeyChain.hsmType === 'nitro' ? 'nitro' : 'onprem',
isEddsaMpcv2 ? 'eddsaMpcv2' : isMpcv2 ? 'mpcv2' : 'mpcv1'
),
});
} catch (e) {
if (!envRequiresBitgoPubGpgKeyConfig(this.bitgo.getEnv())) {
console.warn(
`Unable to get BitGo GPG key based on key data with error: ${e}. Fetching BitGo GPG key based on feature flags.`
);
// First try to get the key based on feature flags, if that fails, fallback to the default key from constants api.
bitgoGpgPubKey = await this.getBitgoGpgPubkeyBasedOnFeatureFlags(enterpriseId, isMpcv2, reqId)
.then(async ({ mpcv2PublicKey, eddsaMpcv2PublicKey }) => {
if (isEddsaMpcv2) {
return eddsaMpcv2PublicKey ?? (await this.getBitgoEddsaMpcv2PublicGpgKey());
}
return (
mpcv2PublicKey ?? (isMpcv2 ? await this.getBitgoMpcv2PublicGpgKey() : await this.getBitgoPublicGpgKey())
);
})
.catch(async () => {
if (isEddsaMpcv2) {
return this.getBitgoEddsaMpcv2PublicGpgKey();
}
return isMpcv2 ? await this.getBitgoMpcv2PublicGpgKey() : await this.getBitgoPublicGpgKey();
});
} else {
throw new Error(
`Environment "${this.bitgo.getEnv()}" requires a BitGo GPG Pub Key Config in BitGoJS for TSS. Error thrown while getting the key from config: ${e}`
);
}
}
return bitgoGpgPubKey;
}
async getBitgoPublicGpgKey(): Promise<openpgp.Key> {
if (!this.bitgoPublicGpgKey) {
// retry getting bitgo's gpg key
await this.setBitgoGpgPubKey(this.bitgo);
if (!this.bitgoPublicGpgKey) {
throw new Error("Failed to get Bitgo's gpg key");
}
}
return this.bitgoPublicGpgKey;
}
async getBitgoMpcv2PublicGpgKey(): Promise<openpgp.Key> {
if (!this.bitgoMPCv2PublicGpgKey) {
// retry getting bitgo's gpg key
await this.setBitgoGpgPubKey(this.bitgo);
if (!this.bitgoMPCv2PublicGpgKey) {
throw new Error("Failed to get Bitgo's gpg key");
}
}
return this.bitgoMPCv2PublicGpgKey;
}
async getBitgoEddsaMpcv2PublicGpgKey(): Promise<openpgp.Key> {
if (!this.bitgoEddsaMpcv2PublicGpgKey) {
// retry getting bitgo's gpg key
await this.setBitgoGpgPubKey(this.bitgo);
if (!this.bitgoEddsaMpcv2PublicGpgKey) {
throw new Error("Failed to get Bitgo's EdDSA MPCv2 gpg key");
}
}
return this.bitgoEddsaMpcv2PublicGpgKey;
}
async createBitgoHeldBackupKeyShare(
userGpgKey: SerializedKeyPair<string>,
enterprise: string | undefined
): Promise<BitgoHeldBackupKeyShare> {
const keyResponse = await this.bitgo
.post(this.baseCoin.url('/krs/backupkeys'))
.send({
enterprise,
userGPGPublicKey: userGpgKey.publicKey,
})
.result();
if (!keyResponse || !keyResponse.keyShares) {
throw new Error('Failed to get backup shares from BitGo.');
}
return {
id: keyResponse.id,
keyShares: keyResponse.keyShares,
};
}
public finalizeBitgoHeldBackupKeyShare(
keyId: string,
commonKeychain: string,
userKeyShare: KeyShare,
bitgoKeychain: Keychain,
userGpgKey: SerializedKeyPair<string>,
backupGpgKey: Key
): Promise<BitgoHeldBackupKeyShare> {
throw new Error('Method not implemented.');
}
createUserKeychain(params: CreateKeychainParamsBase): Promise<Keychain> {
throw new Error('Method not implemented.');
}
createBackupKeychain(params: CreateKeychainParamsBase): Promise<Keychain> {
throw new Error('Method not implemented.');
}
createBitgoKeychain(params: CreateBitGoKeychainParamsBase): Promise<Keychain> {
throw new Error('Method not implemented.');
}
createKeychains(params: {
passphrase: string;
enterprise?: string | undefined;
originalPasscodeEncryptionCode?: string | undefined;
isThirdPartyBackup?: boolean;
webauthnInfo?: WebauthnKeyEncryptionInfo;
encryptionVersion?: EncryptionVersion;
}): Promise<KeychainsTriplet> {
throw new Error('Method not implemented.');
}
signTxRequest(params: TssSignTxRequestParamsWithPrv): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
signTxRequestForMessage(params: TSSParamsForMessage): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
/**
* Signs a transaction using TSS for EdDSA and through utilization of custom share generators
*
* @param {string | TxRequest} txRequest - transaction request with unsigned transaction
* @param {CustomRShareGeneratingFunction} externalSignerRShareGenerator a function that creates R shares in the EdDSA TSS flow
* @param {CustomGShareGeneratingFunction} externalSignerGShareGenerator a function that creates G shares in the EdDSA TSS flow
* @returns {Promise<TxRequest>} - a signed tx request
*/
signEddsaTssUsingExternalSigner(
txRequest: string | TxRequest,
externalSignerCommitmentGenerator: CustomCommitmentGeneratingFunction,
externalSignerRShareGenerator: CustomRShareGeneratingFunction,
externalSignerGShareGenerator: CustomGShareGeneratingFunction
): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
/**
* Signs a transaction using TSS for ECDSA and through utilization of custom share generators
*
* @param {params: TSSParams | TSSParamsForMessage} params - params object that represents parameters to sign a transaction or a message.
* @param {RequestType} requestType - the type of the request to sign (transaction or message).
* @param {CustomPaillierModulusGetterFunction} externalSignerPaillierModulusGetter a function that creates Paillier Modulus shares in the ECDSA TSS flow.
* @param {CustomKShareGeneratingFunction} externalSignerKShareGenerator a function that creates K shares in the ECDSA TSS flow.
* @param {CustomMuDeltaShareGeneratingFunction} externalSignerMuDeltaShareGenerator a function that creates Mu and Delta shares in the ECDSA TSS flow.
* @param {CustomSShareGeneratingFunction} externalSignerSShareGenerator a function that creates S shares in the ECDSA TSS flow.
*/
signEcdsaTssUsingExternalSigner(
params: TSSParams | TSSParamsForMessage,
requestType: RequestType,
externalSignerPaillierModulusGetter: CustomPaillierModulusGetterFunction,
externalSignerKShareGenerator: CustomKShareGeneratingFunction,
externalSignerMuDeltaShareGenerator: CustomMuDeltaShareGeneratingFunction,
externalSignerSShareGenerator: CustomSShareGeneratingFunction
): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
/**
* Signs a transaction using TSS MPCv2 for ECDSA and through utilization of custom share generators
*
* @param {TSSParams | TSSParamsForMessage} params - params object that represents parameters to sign a transaction or a message.
* @param {CustomMPCv2SigningRound1GeneratingFunction} externalSignerMPCv2SigningRound1Generator - a function that creates MPCv2 Round 1 shares in the ECDSA TSS MPCv2 flow.
* @param {CustomMPCv2SigningRound2GeneratingFunction} externalSignerMPCv2SigningRound2Generator - a function that creates MPCv2 Round 2 shares in the ECDSA TSS MPCv2 flow.
* @param {CustomMPCv2SigningRound3GeneratingFunction} externalSignerMPCv2SigningRound3Generator - a function that creates MPCv2 Round 3 shares in the ECDSA TSS MPCv2 flow.
* @param {RequestType} requestType - the type of the request to sign (transaction or message).
* @returns {Promise<TxRequest>} - a signed tx request
*/
signEcdsaMPCv2TssUsingExternalSigner(
params: TSSParams | TSSParamsForMessage,
externalSignerMPCv2SigningRound1Generator: CustomMPCv2SigningRound1GeneratingFunction,
externalSignerMPCv2SigningRound2Generator: CustomMPCv2SigningRound2GeneratingFunction,
externalSignerMPCv2SigningRound3Generator: CustomMPCv2SigningRound3GeneratingFunction,
requestType?: RequestType
): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
signEddsaMPCv2TssUsingExternalSigner(
params: TSSParams | TSSParamsForMessage,
externalSignerEddsaMPCv2SigningRound1Generator: CustomEddsaMPCv2SigningRound1GeneratingFunction,
externalSignerEddsaMPCv2SigningRound2Generator: CustomEddsaMPCv2SigningRound2GeneratingFunction,
externalSignerEddsaMPCv2SigningRound3Generator: CustomEddsaMPCv2SigningRound3GeneratingFunction,
requestType?: RequestType
): Promise<TxRequest> {
throw new Error('Method not implemented.');
}
/**
* Create an Commitment (User to BitGo) share from an unsigned transaction and private user signing material
* EDDSA only
*
* @param {Object} params - params object
* @param {TxRequest} params.txRequest - transaction request with unsigned transaction
* @param {string} params.prv - user signing material
* @param {string} params.walletPassphrase - wallet passphrase
*
* @returns {Promise<{ userToBitgoCommitment: CommitmentShareRecor, encryptedSignerShare: EncryptedSignerShareRecord }>} - Commitment Share and the Encrypted Signer Share to BitGo
*/
createCommitmentShareFromTxRequest(params: {
txRequest: TxRequest;
prv: string;
walletPassphrase: string;
bitgoGpgPubKey: string;
}): Promise<{
userToBitgoCommitment: CommitmentShareRecord;
encryptedSignerShare: EncryptedSignerShareRecord;
encryptedUserToBitgoRShare: EncryptedSignerShareRecord;
}> {
throw new Error('Method not implemented.');
}
/**
* Create an R (User to BitGo) share from an unsigned transaction and private user signing material
*
* @param {Object} params - params object
* @param {TxRequest} params.txRequest - transaction request with unsigned transaction
* @param {string} params.prv - user signing material
* @param {string} [params.walletPassphrase] - wallet passphrase
* @param {EncryptedSignerShareRecord} [params.encryptedUserToBitgoRShare] - encrypted user to bitgo R share generated in the commitment phase
* @returns {Promise<{ rShare: SignShare }>} - R Share to BitGo
*/
createRShareFromTxRequest(params: {
txRequest: TxRequest;
walletPassphrase: string;
encryptedUserToBitgoRShare: EncryptedSignerShareRecord;
}): Promise<{ rShare: SignShare }> {
throw new Error('Method not implemented.');
}
/**
* Create a G (User to BitGo) share from an unsigned transaction and private user signing material
*
* @param {Object} params - params object
* @param {TxRequest} params.txRequest - transaction request with unsigned transaction
* @param {string} params.prv - user signing material
* @param {SignatureShareRecord} params.bitgoToUserRShare - BitGo to User R Share
* @param {SignShare} params.userToBitgoRShare - User to BitGo R Share
* @param {CommitmentShareRecord} params.bitgoToUserCommitment - BitGo to User Commitment
* @returns {Promise<GShare>} - GShare from User to BitGo
*/
createGShareFromTxRequest(params: {
txRequest: TxRequest;
prv: string;
bitgoToUserRShare: SignatureShareRecord;
userToBitgoRShare: SignShare;
bitgoToUserCommitment: CommitmentShareRecord;
}): Promise<GShare> {
throw new Error('Method not implemented.');
}
/**
* Builds a tx request from params and verify it
*
* @param {PrebuildTransactionWithIntentOptions} params - parameters to build the tx
* @param {TxRequestVersion} apiVersion lite or full
* @param {boolean} preview boolean indicating if this is to preview a tx request, which will not initiate policy checks or pending approvals
* @returns {Promise<TxRequest>} - a built tx request
*/
async prebuildTxWithIntent(
params: PrebuildTransactionWithIntentOptions,
apiVersion: TxRequestVersion = 'lite',
preview?: boolean
): Promise<TxRequest> {
const intentOptions = this.populateIntent(this.baseCoin, params);
const whitelistedParams = {
intent: {
...intentOptions,
},
apiVersion: apiVersion,
preview,
};
const reqTracer = params.reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
const unsignedTx = (await this.bitgo
.post(this.bitgo.url('/wallet/' + this.wallet.id() + '/txrequests', 2))
.send(whitelistedParams)
.result()) as TxRequest;
return unsignedTx;
}
/**
* Create a tx request from params for message signing
* @deprecated Use createSignMessageRequest instead
*
* @param params
* @param apiVersion
* @param preview
*/
async createTxRequestWithIntentForMessageSigning(
params: IntentOptionsForMessage,
apiVersion: TxRequestVersion = 'full',
preview?: boolean
): Promise<TxRequest> {
const intentOptions: PopulatedIntentForMessageSigning = {
custodianMessageId: params.custodianMessageId,
intentType: params.intentType,
sequenceId: params.sequenceId,
comment: params.comment,
memo: params.memo?.value,
isTss: params.isTss,
messageRaw: params.messageRaw,
messageEncoded: params.messageEncoded ?? '',
};
return this.createTxRequestBase(intentOptions, apiVersion, preview, params.reqId);
}
/**
* Create a sign message request
*
* @param params - the parameters for the sign message request
* @param apiVersion - the API version to use, defaults to 'full'
*/
async buildSignMessageRequest(
params: IntentOptionsForMessage,
apiVersion: TxRequestVersion = 'full'
): Promise<TxRequest> {
assert(
params.intentType === 'signMessage',
'Intent type must be signMessage for createMsgRequestWithSignMessageIntent'
);
const intent: PopulatedIntentForMessageSigning = {
custodianMessageId: params.custodianMessageId,
intentType: params.intentType,
sequenceId: params.sequenceId,
comment: params.comment,
memo: params.memo?.value,
isTss: params.isTss,
messageRaw: params.messageRaw,
messageStandardType: params.messageStandardType ?? MessageStandardType.UNKNOWN,
messageEncoded: params.messageEncoded ?? '',
signerAddress: params.signerAddress,
};
return this.buildSignMessageRequestBase(intent, apiVersion, params.reqId);
}
/**
* Create a tx request from params for type data signing
*
* @param params
* @param apiVersion
* @param preview
*/
async createTxRequestWithIntentForTypedDataSigning(
params: IntentOptionsForTypedData,
apiVersion: TxRequestVersion = 'full',
preview?: boolean
): Promise<TxRequest> {
const intentOptions: PopulatedIntentForTypedDataSigning = {
custodianMessageId: params.custodianMessageId,
intentType: params.intentType,
sequenceId: params.sequenceId,
comment: params.comment,
memo: params.memo?.value,
isTss: params.isTss,
messageRaw: params.typedDataRaw,
messageEncoded: params.typedDataEncoded ?? '',
};
return this.createTxRequestBase(intentOptions, apiVersion, preview, params.reqId);
}
/**
* Calls Bitgo API to create tx request.
*
* @private
*/
private async createTxRequestBase(
intentOptions: PopulatedIntentForTypedDataSigning | PopulatedIntentForMessageSigning,
apiVersion: TxRequestVersion,
preview?: boolean,
reqId?: IRequestTracer
): Promise<TxRequest> {
// TODO(WCN-541): add optional attestation pass-through for MPC /txrequests (deferred until
// multisig attestation, WCN-539, is verified end-to-end on staging).
const whitelistedParams = {
intent: {
...intentOptions,
},
apiVersion,
preview,
};
const reqTracer = reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
return this.bitgo
.post(this.bitgo.url(`/wallet/${this.wallet.id()}/txrequests`, 2))
.send(whitelistedParams)
.result();
}
/**
* Calls Bitgo API to create msg request.
*
* @private
*/
private async buildSignMessageRequestBase(
intent: PopulatedIntentForMessageSigning,
apiVersion: TxRequestVersion,
reqId?: IRequestTracer
): Promise<TxRequest> {
const whitelistedParams = {
intent: {
...intent,
},
apiVersion,
};
const reqTracer = reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
return this.bitgo
.post(this.bitgo.url(`/wallet/${this.wallet.id()}/msgrequests`, 2))
.send(whitelistedParams)
.result();
}
/**
* Call delete signature shares for a txRequest, the endpoint delete the signatures and return them
*
* @param {string} txRequestId tx id reference to delete signature shares
* @param {IRequestTracer} reqId - the request tracer request id
* @returns {SignatureShareRecord[]}
*/
async deleteSignatureShares(txRequestId: string, reqId?: IRequestTracer): Promise<SignatureShareRecord[]> {
const reqTracer = reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
return this.bitgo
.del(this.bitgo.url(`/wallet/${this.wallet.id()}/txrequests/${txRequestId}/signatureshares`, 2))
.send()
.result();
}
/**
* Initialize the send procedure once Bitgo has the User To Bitgo GShare
*
* @param {String} txRequestId - the txRequest Id
* @param {IRequestTracer} reqId - the request tracer request id
* @returns {Promise<any>}
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async sendTxRequest(txRequestId: string, reqId?: IRequestTracer): Promise<any> {
const reqTracer = reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
return this.bitgo
.post(this.baseCoin.url('/wallet/' + this.wallet.id() + '/tx/send'))
.send({ txRequestId })
.result();
}
/**
* Delete signature shares, get the tx request without them from the db and sign it to finally send it.
*
* Note : This can be performed in order to reach latest network conditions required on pending approval flow.
*
* @param {String} txRequestId - the txRequest Id to make the requests.
* @param {String} decryptedPrv - decrypted prv to sign the tx request.
* @param {RequestTracer} reqId id tracer.
* @returns {Promise<any>}
*/
async recreateTxRequest(txRequestId: string, decryptedPrv: string, reqId: IRequestTracer): Promise<TxRequest> {
await this.deleteSignatureShares(txRequestId, reqId);
// after delete signatures shares get the tx without them
const txRequest = await this.getTxRequest(txRequestId, reqId);
return await this.signTxRequest({ txRequest, prv: decryptedPrv, reqId });
}
/**
* Gets the latest Tx Request by id
*
* @param {String} txRequestId - the txRequest Id
* @param {IRequestTracer} reqId - request tracer request id
* @returns {Promise<TxRequest>}
*/
async getTxRequest(txRequestId: string, reqId?: IRequestTracer): Promise<TxRequest> {
return getTxRequest(this.bitgo, this.wallet.id(), txRequestId, reqId);
}
/**
* It gets the appropriate BitGo GPG public keys for key creation based on a
* combination of coin and the feature flags on the user and their enterprise if set.
* Returns both the default MPCv2 key and the EdDSA-specific MPCv2 key (if present).
* @param enterpriseId - enterprise under which user wants to create the wallet
* @param isMPCv2 - true to get the MPCv2 GPG public key, defaults to false
* @param reqId - request tracer request id
*/
public async getBitgoGpgPubkeyBasedOnFeatureFlags(
enterpriseId: string | undefined,
isMPCv2 = false,
reqId?: IRequestTracer
): Promise<{ mpcv2PublicKey: Key; eddsaMpcv2PublicKey: Key | undefined }> {
const reqTracer = reqId || new RequestTracer();
this.bitgo.setRequestTracer(reqTracer);
const response: BitgoGPGPublicKey = await this.bitgo
.get(this.baseCoin.url('/tss/pubkey'))
.query({ enterpriseId })
.retry(3)
.result();
const mpcv2PublicKey = await readKey({
armoredKey: (isMPCv2 ? response.mpcv2PublicKey : response.publicKey) as string,
});
const eddsaMpcv2PublicKey = response.eddsaMpcv2PublicKey
? await readKey({ armoredKey: response.eddsaMpcv2PublicKey })
: undefined;
return { mpcv2PublicKey, eddsaMpcv2PublicKey };
}
/**
* Returns supported TxRequest versions for this wallet
* @deprecated Whenever needed, use apiVersion 'full' for TSS wallets
*/
public supportedTxRequestVersions(): TxRequestVersion[] {
if (!this._wallet || this._wallet.type() === 'trading' || this._wallet.multisigType() !== 'tss') {
return [];
} else if (this._wallet.baseCoin.getMPCAlgorithm() === 'ecdsa') {
return ['full'];
} else if (this._wallet.baseCoin.getMPCAlgorithm() === 'eddsa' && this._wallet.type() === 'hot') {
if (this._wallet.multisigTypeVersion() === 'MPCv2') {
return ['full'];
}
return ['lite', 'full'];
} else {
return ['full'];
}
}
/**
* Returns true if the txRequest is using apiVersion == full and is pending approval
* @param txRequest
* @returns boolean
*/
isPendingApprovalTxRequestFull(txRequest: TxRequest): boolean {
const { apiVersion, state } = txRequest;
return apiVersion === 'full' && 'pendingApproval' === state;
}
/**
* Get the signable hex, derivation path, and serialized tx hex from a full single-transaction request.
* @param {TxRequest} txRequest - the transaction request object
* @returns {{ signableHex: string; derivationPath: string; serializedTxHex: string | undefined }} - the signable hex, derivation path, and serialized tx hex
*/
protected getSignableHexAndDerivationPath(
txRequest: TxRequest,
missingTransactionsMessage = 'createOfflineShare requires exactly one transaction in txRequest'
): {
signableHex: string;
derivationPath: string;
serializedTxHex: string | undefined;
} {
assert(txRequest.transactions && txRequest.transactions.length === 1, missingTransactionsMessage);
const unsignedTx = txRequest.transactions[0].unsignedTx;
assert(unsignedTx, 'Missing unsignedTx in transactions');
assert(unsignedTx.signableHex, 'Missing signableHex in unsignedTx');
assert(unsignedTx.derivationPath, 'Missing derivationPath in unsignedTx');
return {
signableHex: unsignedTx.signableHex,
derivationPath: unsignedTx.derivationPath,
serializedTxHex: unsignedTx.serializedTxHex,
};
}
/**
* Gets the BitGo and user GPG keys from the BitGo public GPG key and the encrypted user GPG private key.
* @param {string} bitgoPublicGpgKey - the BitGo public GPG key
* @param {string} encryptedUserGpgPrvKey - the encrypted user GPG private key
* @param {string} walletPassphrase - the wallet passphrase
* @param {string} adata - the additional data to validate the GPG keys
* @param {string} userGpgKeyDomainSeparator - the domain separator expected in the encrypted GPG key adata
* @returns {Promise<{ bitgoGpgKey: openpgp.Key; userGpgPrvKey: openpgp.PrivateKey }>} - the BitGo and user GPG keys
*/
protected async getBitgoAndUserGpgKeys(
bitgoPublicGpgKey: string,
encryptedUserGpgPrvKey: string,
walletPassphrase: string,
adata: string,
userGpgKeyDomainSeparator: string
): Promise<{
bitgoGpgKey: openpgp.Key;
userGpgPrvKey: openpgp.PrivateKey;
}> {
const bitgoGpgKey = await openpgp.readKey({ armoredKey: bitgoPublicGpgKey });
const decryptedGpgPrvKey = await this.bitgo.decrypt({
input: encryptedUserGpgPrvKey,
password: walletPassphrase,
});
if (adata) {
this.validateAdata(adata, encryptedUserGpgPrvKey, userGpgKeyDomainSeparator);
}
const userGpgPrvKey = await openpgp.readPrivateKey({ armoredKey: decryptedGpgPrvKey });
return { bitgoGpgKey, userGpgPrvKey };
}
/**
* Validates encryption additional authenticated data against the ciphertext envelope.
* @param adata string
* @param cyphertext string
* @param roundDomainSeparator string
* @throws {Error} if the adata or cyphertext is invalid
*/
protected validateAdata(adata: string, cyphertext: string, roundDomainSeparator: string): void {
let cypherJson;
try {
cypherJson = JSON.parse(cyphertext);
} catch (e) {
throw new Error('Failed to parse cyphertext to JSON, got: ' + cyphertext);
}
// using decodeURIComponent to handle special characters
if (
decodeURIComponent(cypherJson.adata) !== decodeURIComponent(`${roundDomainSeparator}:${adata}`) &&
decodeURIComponent(cypherJson.adata) !== decodeURIComponent(adata)
) {
throw new Error('Adata does not match cyphertext adata');
}
}
}