-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathtransaction.ts
More file actions
676 lines (600 loc) · 24.8 KB
/
transaction.ts
File metadata and controls
676 lines (600 loc) · 24.8 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
import 'mocha';
import * as assert from 'assert';
import * as _ from 'lodash';
import * as utxolib from '@bitgo/utxo-lib';
import nock = require('nock');
import { BIP32Interface, bitgo, testutil } from '@bitgo/utxo-lib';
import { address as wasmAddress } from '@bitgo/wasm-utxo';
import {
common,
FullySignedTransaction,
HalfSignedUtxoTransaction,
Triple,
WalletSignTransactionOptions,
} from '@bitgo/sdk-core';
import { AbstractUtxoCoin, getReplayProtectionAddresses, generateAddress, getReplayProtectionPubkeys } from '../../src';
import { SdkBackend } from '../../src/transaction/types';
import type { Unspent, WalletUnspent } from '../../src/unspent';
import {
utxoCoins,
shouldEqualJSON,
getFixture,
getUtxoWallet,
mockUnspent,
InputScriptType,
TransactionObj,
transactionToObj,
transactionHexToObj,
createPrebuildTransaction,
getDefaultWalletKeys,
getUtxoCoin,
keychainsBase58,
getWalletKeys,
defaultBitGo,
} from './util';
function getScriptTypes2Of3() {
return [...bitgo.outputScripts.scriptTypes2Of3, 'taprootKeyPathSpend'] as const;
}
describe(`UTXO coin signTransaction`, async function () {
const bgUrl = common.Environments[defaultBitGo.getEnv()].uri;
const coin = getUtxoCoin('btc');
const wallet = getUtxoWallet(coin, { id: '5b34252f1bf349930e34020a00000000', coin: coin.getChain() });
const rootWalletKeys = getDefaultWalletKeys();
const userPrv = rootWalletKeys.user.toBase58();
const pubs = keychainsBase58.map((v) => v.pub) as Triple<string>;
function validatePsbt(txHex: string, targetSigCount: 0 | 1, targetNonceCount?: 1 | 2) {
const psbt = utxolib.bitgo.createPsbtFromHex(txHex, coin.network);
psbt.data.inputs.forEach((input, index) => {
const parsed = utxolib.bitgo.parsePsbtInput(input);
if (parsed.scriptType === 'taprootKeyPathSpend') {
assert.ok(targetNonceCount);
const nonce = psbt.getProprietaryKeyVals(index, {
identifier: utxolib.bitgo.PSBT_PROPRIETARY_IDENTIFIER,
subtype: utxolib.bitgo.ProprietaryKeySubtype.MUSIG2_PUB_NONCE,
});
assert.strictEqual(nonce.length, targetNonceCount);
}
const expectedSigCount = parsed.scriptType === 'p2shP2pk' || targetSigCount === 0 ? undefined : 1;
assert.strictEqual(parsed.signatures?.length, expectedSigCount);
});
}
function validateTx(txHex: string, unspents: Unspent<bigint>[], targetSigCount: 0 | 1) {
const tx = utxolib.bitgo.createTransactionFromHex(txHex, coin.network);
unspents.forEach((u, i) => {
const sigCount = utxolib.bitgo.getStrictSignatureCount(tx.ins[i]);
const expectedSigCount = utxolib.bitgo.isWalletUnspent(u) && !!targetSigCount ? 1 : 0;
assert.strictEqual(sigCount, expectedSigCount);
});
}
async function signTransaction(
tx: utxolib.bitgo.UtxoPsbt | utxolib.bitgo.UtxoTransaction<bigint>,
useSigningSteps: boolean,
unspents?: Unspent<bigint>[]
) {
const isPsbt = tx instanceof utxolib.bitgo.UtxoPsbt;
const isTxWithTaprootKeyPathSpend = isPsbt && utxolib.bitgo.isTransactionWithKeyPathSpendInput(tx);
const txHex = tx.toHex();
function nockSignPsbt(psbtHex: string): nock.Scope {
const psbt = utxolib.bitgo.createPsbtFromHex(psbtHex, coin.network);
return nock(bgUrl)
.post(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/tx/signpsbt`, (body) => body.psbt)
.reply(200, { psbt: psbt.setAllInputsMusig2NonceHD(rootWalletKeys.bitgo).toHex() });
}
if (!useSigningSteps) {
let scope: nock.Scope | undefined;
if (tx instanceof utxolib.bitgo.UtxoPsbt && isTxWithTaprootKeyPathSpend) {
scope = nockSignPsbt(tx.clone().setAllInputsMusig2NonceHD(rootWalletKeys.bitgo).toHex());
}
const psbt = await coin.signTransaction({
txPrebuild: {
txHex,
txInfo: isPsbt ? undefined : { unspents },
walletId: isTxWithTaprootKeyPathSpend ? wallet.id() : undefined,
},
prv: userPrv,
pubs: isPsbt ? undefined : pubs,
});
assert.ok('txHex' in psbt);
if (isPsbt) {
validatePsbt(psbt.txHex, 1, 2);
} else {
assert.ok(unspents);
validateTx(psbt.txHex, unspents, 1);
}
if (scope) {
assert.strictEqual(scope.isDone(), true);
}
return;
}
const signerNoncePsbt = await coin.signTransaction({
txPrebuild: { txHex },
prv: userPrv,
signingStep: 'signerNonce',
});
assert.ok('txHex' in signerNoncePsbt);
if (isPsbt) {
validatePsbt(signerNoncePsbt.txHex, 0, isTxWithTaprootKeyPathSpend ? 1 : undefined);
} else {
assert.ok(unspents);
validateTx(signerNoncePsbt.txHex, unspents, 0);
}
let scope: nock.Scope | undefined;
if (isTxWithTaprootKeyPathSpend) {
scope = nockSignPsbt(signerNoncePsbt.txHex);
}
const cosignerNoncePsbt = await coin.signTransaction({
txPrebuild: { ...signerNoncePsbt, walletId: wallet.id() },
signingStep: 'cosignerNonce',
});
assert.ok('txHex' in cosignerNoncePsbt);
if (isPsbt) {
validatePsbt(cosignerNoncePsbt.txHex, 0, isTxWithTaprootKeyPathSpend ? 2 : undefined);
} else {
assert.ok(unspents);
validateTx(cosignerNoncePsbt.txHex, unspents, 0);
}
if (scope) {
assert.strictEqual(scope.isDone(), true);
}
const signerSigPsbt = await coin.signTransaction({
txPrebuild: { ...cosignerNoncePsbt, txInfo: isPsbt ? undefined : { unspents } },
prv: userPrv,
pubs: isPsbt ? undefined : pubs,
signingStep: 'signerSignature',
});
assert.ok('txHex' in signerSigPsbt);
if (isPsbt) {
validatePsbt(signerSigPsbt.txHex, 1, isTxWithTaprootKeyPathSpend ? 2 : undefined);
} else {
assert.ok(unspents);
validateTx(signerSigPsbt.txHex, unspents, 1);
}
}
it('success when called like customSigningFunction flow - PSBT with taprootKeyPathSpend inputs', async function () {
const inputs: testutil.Input[] = testutil.inputScriptTypes.map((scriptType) => ({
scriptType,
value: BigInt(1000),
}));
const unspentSum = inputs.reduce((prev: bigint, curr) => prev + curr.value, BigInt(0));
const outputs: testutil.Output[] = [{ scriptType: 'p2sh', value: unspentSum - BigInt(1000) }];
const psbt = testutil.constructPsbt(inputs, outputs, coin.network, rootWalletKeys, 'unsigned', {
p2shP2pkKey: getReplayProtectionPubkeys(coin.name)[0],
});
for (const v of [false, true]) {
await signTransaction(psbt, v);
}
});
it('success when called like customSigningFunction flow - PSBT without taprootKeyPathSpend inputs', async function () {
const inputs: testutil.Input[] = testutil.inputScriptTypes
.filter((v) => v !== 'taprootKeyPathSpend')
.map((scriptType) => ({
scriptType,
value: BigInt(1000),
}));
const unspentSum = inputs.reduce((prev: bigint, cur) => prev + cur.value, BigInt(0));
const outputs: testutil.Output[] = [{ scriptType: 'p2sh', value: unspentSum - BigInt(1000) }];
const psbt = testutil.constructPsbt(inputs, outputs, coin.network, rootWalletKeys, 'unsigned');
for (const v of [false, true]) {
await signTransaction(psbt, v);
}
});
it('success when called like customSigningFunction flow - Network Tx', async function () {
const inputs: testutil.TxnInput<bigint>[] = testutil.txnInputScriptTypes
.filter((v) => v !== 'p2shP2pk')
.map((scriptType) => ({
scriptType,
value: BigInt(1000),
}));
const unspentSum = inputs.reduce((prev: bigint, curr) => prev + curr.value, BigInt(0));
const outputs: testutil.TxnOutput<bigint>[] = [{ scriptType: 'p2sh', value: unspentSum - BigInt(1000) }];
const txBuilder = testutil.constructTxnBuilder(inputs, outputs, coin.network, rootWalletKeys, 'unsigned');
const unspents = inputs.map((v, i) => testutil.toTxnUnspent(v, i, coin.network, rootWalletKeys));
for (const v of [false, true]) {
await signTransaction(txBuilder.buildIncomplete(), v, unspents);
}
});
it('fails when called like customSigningFunction flow - PSBT cache miss', async function () {
const inputs: testutil.Input[] = [{ scriptType: 'taprootKeyPathSpend', value: BigInt(1000) }];
const unspentSum = inputs.reduce((prev: bigint, curr) => prev + curr.value, BigInt(0));
const outputs: testutil.Output[] = [{ scriptType: 'p2sh', value: unspentSum - BigInt(1000) }];
const psbt = testutil.constructPsbt(inputs, outputs, coin.network, rootWalletKeys, 'unsigned');
await assert.rejects(
async () => {
await coin.signTransaction({
txPrebuild: { txHex: psbt.toHex() },
prv: userPrv,
signingStep: 'signerSignature',
});
},
{
message: `Psbt is missing from txCache (cache size 0).
This may be due to the request being routed to a different BitGo-Express instance that for signing step 'signerNonce'.`,
}
);
});
it('fails when unsupported locking script is used', async function () {
const inputs: testutil.Input[] = [
{ scriptType: 'p2wsh', value: BigInt(1000) },
{ scriptType: 'p2trMusig2', value: BigInt(1000) },
];
const unspentSum = inputs.reduce((prev: bigint, curr) => prev + curr.value, BigInt(0));
const outputs: testutil.Output[] = [{ scriptType: 'p2sh', value: unspentSum - BigInt(500) }];
const psbt = testutil.constructPsbt(inputs, outputs, coin.network, rootWalletKeys, 'unsigned');
// override the 1st PSBT input with unsupported 2 of 2 multi-sig locking script.
const unspent = testutil.toUnspent(inputs[0], 0, coin.network, rootWalletKeys);
if (!utxolib.bitgo.isWalletUnspent(unspent)) {
throw new Error('invalid unspent');
}
const { publicKeys } = rootWalletKeys.deriveForChainAndIndex(unspent.chain, unspent.index);
const script2Of2 = utxolib.payments.p2ms({ m: 2, pubkeys: [publicKeys[0], publicKeys[1]] });
psbt.data.inputs[0].witnessScript = script2Of2.output;
await assert.rejects(
async () => {
await coin.signTransaction({
txPrebuild: { txHex: psbt.toHex() },
prv: userPrv,
});
},
{
message: `length mismatch`,
}
);
});
});
function run<TNumber extends number | bigint = number>(
coin: AbstractUtxoCoin,
inputScripts: testutil.InputScriptType[],
txFormat: 'legacy' | 'psbt',
{ decodeWith }: { decodeWith?: SdkBackend } = {}
) {
const amountType = coin.amountType;
const title = [
inputScripts.join(','),
`txFormat=${txFormat}`,
`amountType=${amountType}`,
decodeWith ? `decodeWith=${decodeWith}` : '',
];
describe(`${title.join(' ')}`, function () {
const bgUrl = common.Environments[defaultBitGo.getEnv()].uri;
const isTransactionWithKeyPathSpend = inputScripts.some((s) => s === 'taprootKeyPathSpend');
const isTransactionWithReplayProtection = inputScripts.some((s) => s === 'p2shP2pk');
const isTransactionWithP2tr = inputScripts.some((s) => s === 'p2tr');
const isTransactionWithP2trMusig2 = inputScripts.some((s) => s === 'p2trMusig2');
const value = (amountType === 'bigint' ? BigInt('10999999800000001') : 1e8) as TNumber;
const wallet = getUtxoWallet(coin, { id: '5b34252f1bf349930e34020a00000000', coin: coin.getChain() });
const walletKeys = getDefaultWalletKeys();
const fullSign = !(isTransactionWithReplayProtection || isTransactionWithKeyPathSpend);
function getUnspentsForPsbt(): Unspent<bigint>[] {
return inputScripts.map((t, index) => {
return testutil.toUnspent(
{ scriptType: t, value: t === 'p2shP2pk' ? BigInt(1000) : BigInt(value) },
index,
coin.network,
walletKeys
);
});
}
function toTxnInputScriptType(type: testutil.InputScriptType): InputScriptType {
return type === 'p2shP2pk' ? 'replayProtection' : type === 'taprootKeyPathSpend' ? 'p2trMusig2' : type;
}
function getUnspents(): Unspent<TNumber>[] {
return inputScripts.map((type, i) =>
mockUnspent<TNumber>(coin.network, walletKeys, toTxnInputScriptType(type), i, value)
);
}
function getOutputAddress(rootWalletKeys: utxolib.bitgo.RootWalletKeys): string {
return generateAddress(coin.name, {
keychains: rootWalletKeys.triple.map((k) => ({ pub: k.neutered().toBase58() })),
});
}
function getSignParams(
prebuildHex: string,
signer: BIP32Interface,
cosigner: BIP32Interface,
decodeWith: SdkBackend | undefined
): WalletSignTransactionOptions {
const txInfo = {
unspents: txFormat === 'psbt' ? undefined : getUnspents(),
};
return {
txPrebuild: {
walletId: isTransactionWithKeyPathSpend ? wallet.id() : undefined,
txHex: prebuildHex,
txInfo,
decodeWith,
},
prv: signer.toBase58(),
pubs: walletKeys.triple.map((k) => k.neutered().toBase58()),
cosignerPub: cosigner.neutered().toBase58(),
} as WalletSignTransactionOptions;
}
async function createHalfSignedTransaction(
prebuild: utxolib.bitgo.UtxoTransaction<TNumber> | utxolib.bitgo.UtxoPsbt,
signer: BIP32Interface,
cosigner: BIP32Interface
): Promise<HalfSignedUtxoTransaction> {
let scope: nock.Scope | undefined;
if (prebuild instanceof utxolib.bitgo.UtxoPsbt && isTransactionWithKeyPathSpend) {
const psbt = prebuild.clone().setAllInputsMusig2NonceHD(cosigner);
scope = nock(bgUrl)
.post(`/api/v2/${wallet.coin()}/wallet/${wallet.id()}/tx/signpsbt`, (body) => body.psbt)
.reply(200, { psbt: psbt.toHex() });
}
// half-sign with the user key
const result = (await wallet.signTransaction(
getSignParams(prebuild.toBuffer().toString('hex'), signer, cosigner, decodeWith)
)) as Promise<HalfSignedUtxoTransaction>;
if (scope) {
assert.strictEqual(scope.isDone(), true);
}
return result;
}
async function createFullSignedTransaction(
halfSigned: HalfSignedUtxoTransaction,
signer: BIP32Interface,
cosigner: BIP32Interface
): Promise<FullySignedTransaction> {
return (await wallet.signTransaction({
...getSignParams(halfSigned.txHex, signer, cosigner, decodeWith),
isLastSignature: true,
})) as FullySignedTransaction;
}
type TransactionStages = {
prebuild: utxolib.bitgo.UtxoTransaction<TNumber> | utxolib.bitgo.UtxoPsbt;
halfSignedUserBackup?: HalfSignedUtxoTransaction;
halfSignedUserBitGo: HalfSignedUtxoTransaction;
fullSignedUserBackup?: FullySignedTransaction;
fullSignedUserBitGo?: FullySignedTransaction;
};
type TransactionObjStages = Record<keyof TransactionStages, TransactionObj>;
function createPrebuildPsbt() {
const inputs = inputScripts.map(
(t): testutil.Input => ({
scriptType: t,
value: t === 'p2shP2pk' ? BigInt(1000) : BigInt(value),
})
);
const unspentSum = inputs.reduce((prev: bigint, curr) => prev + curr.value, BigInt(0));
const outputs: testutil.Output[] = [
{ address: getOutputAddress(getWalletKeys('test')), value: unspentSum - BigInt(1000) },
];
const psbt = testutil.constructPsbt(inputs, outputs, coin.network, walletKeys, 'unsigned', {
p2shP2pkKey: getReplayProtectionPubkeys(coin.name)[0],
});
utxolib.bitgo.addXpubsToPsbt(psbt, walletKeys);
return psbt;
}
async function getTransactionStages(): Promise<TransactionStages> {
const prebuild =
txFormat === 'psbt'
? createPrebuildPsbt()
: createPrebuildTransaction<TNumber>(coin.network, getUnspents(), getOutputAddress(walletKeys));
const halfSignedUserBitGo = await createHalfSignedTransaction(prebuild, walletKeys.user, walletKeys.bitgo);
const fullSignedUserBitGo =
fullSign && !isTransactionWithP2trMusig2
? await createFullSignedTransaction(halfSignedUserBitGo, walletKeys.bitgo, walletKeys.user)
: undefined;
const halfSignedUserBackup =
!isTransactionWithKeyPathSpend && !(txFormat === 'psbt' && isTransactionWithP2tr)
? await createHalfSignedTransaction(prebuild, walletKeys.user, walletKeys.backup)
: undefined;
const fullSignedUserBackup =
fullSign && halfSignedUserBackup
? await createFullSignedTransaction(halfSignedUserBackup, walletKeys.backup, walletKeys.user)
: undefined;
return {
prebuild,
halfSignedUserBackup,
halfSignedUserBitGo,
fullSignedUserBackup,
fullSignedUserBitGo,
};
}
let transactionStages: TransactionStages;
before('prepare', async function () {
transactionStages = await getTransactionStages();
});
afterEach(nock.cleanAll);
it('match fixtures', async function (this: Mocha.Context) {
if (txFormat === 'psbt') {
// TODO (maybe) - once full PSBT support is added to abstract-utxo module, custom JSON representation of PSBT can be created and tested here.
// signatures of taprootKeyPathSpends are random since random nature of MuSig2 nonce, so psbt hex comparison also wont work.
return this.skip();
}
function toTransactionStagesObj(stages: TransactionStages): TransactionObjStages {
return _.mapValues(stages, (v) =>
v === undefined || v instanceof utxolib.bitgo.UtxoPsbt
? undefined
: v instanceof utxolib.bitgo.UtxoTransaction
? transactionToObj<TNumber>(v)
: transactionHexToObj(v.txHex, coin.network, amountType)
) as TransactionObjStages;
}
shouldEqualJSON(
toTransactionStagesObj(transactionStages),
await getFixture(
coin,
`transactions-${inputScripts.map((t) => toTxnInputScriptType(t)).join('-')}`,
toTransactionStagesObj(transactionStages)
)
);
});
function testPsbtValidSignatures(tx: HalfSignedUtxoTransaction, signedBy: BIP32Interface[]) {
const psbt = utxolib.bitgo.createPsbtFromHex(tx.txHex, coin.network);
const unspents = getUnspentsForPsbt();
psbt.data.inputs.forEach((input, index) => {
const unspent = unspents[index];
if (!utxolib.bitgo.isWalletUnspent(unspent)) {
assert.ok(utxolib.bitgo.getPsbtInputScriptType(input), 'p2shP2pk');
return;
}
const walletUnspent = unspent as WalletUnspent<bigint>;
const pubkeys = walletKeys.deriveForChainAndIndex(walletUnspent.chain, walletUnspent.index).publicKeys;
pubkeys.forEach((pk, pkIndex) => {
psbt.validateSignaturesOfInputCommon(index, pk).should.eql(signedBy.includes(walletKeys.triple[pkIndex]));
});
});
}
function testValidSignatures(
tx: HalfSignedUtxoTransaction | FullySignedTransaction,
signedBy: BIP32Interface[],
sign: 'halfsigned' | 'fullsigned'
) {
if (txFormat === 'psbt' && sign === 'halfsigned') {
testPsbtValidSignatures(tx, signedBy);
return;
}
const unspents =
txFormat === 'psbt'
? getUnspentsForPsbt().map((u) => ({ ...u, value: bitgo.toTNumber(u.value, amountType) as TNumber }))
: getUnspents();
const prevOutputs = unspents.map(
(u): utxolib.TxOutput<TNumber> => ({
script: Buffer.from(wasmAddress.toOutputScriptWithCoin(u.address, coin.name)),
value: u.value,
})
);
const transaction = utxolib.bitgo.createTransactionFromBuffer<TNumber>(
Buffer.from(tx.txHex, 'hex'),
coin.network,
{ amountType }
);
transaction.ins.forEach((input, index) => {
if (inputScripts[index] === 'p2shP2pk') {
assert.ok(coin.isBitGoTaintedUnspent(unspents[index]));
return;
}
const unspent = unspents[index] as WalletUnspent<TNumber>;
const pubkeys = walletKeys.deriveForChainAndIndex(unspent.chain, unspent.index).publicKeys;
pubkeys.forEach((pk, pkIndex) => {
utxolib.bitgo
.verifySignature<TNumber>(
transaction,
index,
prevOutputs[index].value,
{
publicKey: pk,
},
prevOutputs
)
.should.eql(signedBy.includes(walletKeys.triple[pkIndex]));
});
});
}
async function testExplainTx(
stageName: string,
txHex: string,
unspents: Unspent<TNumber>[],
pubs: Triple<string> | undefined
): Promise<void> {
const explanation = await coin.explainTransaction<TNumber>({
txHex,
txInfo: {
unspents,
},
pubs,
decodeWith,
});
const expectedProperties = ['id', 'outputs', 'changeOutputs', 'changeAmount', 'outputAmount'];
if (decodeWith !== 'wasm-utxo') {
expectedProperties.push('displayOrder', 'inputSignatures', 'signatures');
}
explanation.should.have.properties(...expectedProperties);
const expectedSignatureCount =
stageName === 'prebuild' || pubs === undefined
? 0
: stageName.startsWith('halfSigned')
? 1
: stageName.startsWith('fullSigned')
? 2
: undefined;
if ('inputSignatures' in explanation) {
explanation.inputSignatures.should.eql(
// FIXME(BG-35154): implement signature verification for replay protection inputs
inputScripts.map((type) => (type === 'p2shP2pk' ? 0 : expectedSignatureCount))
);
}
if ('signatures' in explanation) {
explanation.signatures.should.eql(expectedSignatureCount);
explanation.changeAmount.should.eql('0'); // no change addresses given
}
let expectedOutputAmount =
BigInt((txFormat === 'psbt' ? getUnspentsForPsbt() : getUnspents()).length) * BigInt(value);
inputScripts.forEach((type) => {
if (type === 'p2shP2pk') {
// replayProtection unspents have value 1000
expectedOutputAmount -= BigInt(value);
expectedOutputAmount += BigInt(1000);
}
});
expectedOutputAmount -= BigInt(1000); // fee of 1000
explanation.outputAmount.should.eql(expectedOutputAmount.toString());
}
it('have valid signature for half-signed transaction', function () {
if (transactionStages.halfSignedUserBackup) {
testValidSignatures(transactionStages.halfSignedUserBackup, [walletKeys.user], 'halfsigned');
}
testValidSignatures(transactionStages.halfSignedUserBitGo, [walletKeys.user], 'halfsigned');
});
it('have valid signatures for full-signed transaction', function () {
if (!fullSign) {
return this.skip();
}
if (transactionStages.fullSignedUserBackup) {
testValidSignatures(transactionStages.fullSignedUserBackup, [walletKeys.user, walletKeys.backup], 'fullsigned');
}
if (transactionStages.fullSignedUserBitGo) {
testValidSignatures(transactionStages.fullSignedUserBitGo, [walletKeys.user, walletKeys.bitgo], 'fullsigned');
}
});
it('have correct results for explainTransaction', async function () {
for (const [stageName, stageTx] of Object.entries(transactionStages)) {
if (!stageTx) {
continue;
}
const txHex =
stageTx instanceof utxolib.bitgo.UtxoPsbt || stageTx instanceof utxolib.bitgo.UtxoTransaction
? stageTx.toBuffer().toString('hex')
: stageTx.txHex;
const pubs = walletKeys.triple.map((k) => k.neutered().toBase58()) as Triple<string>;
const unspents =
txFormat === 'psbt'
? getUnspentsForPsbt().map((u) => ({ ...u, value: bitgo.toTNumber(u.value, amountType) as TNumber }))
: getUnspents();
await testExplainTx(stageName, txHex, unspents, pubs);
if (decodeWith !== 'wasm-utxo') {
await testExplainTx(stageName, txHex, unspents, undefined);
}
}
});
});
}
function runTestForCoin(coin: AbstractUtxoCoin) {
getScriptTypes2Of3().forEach((type) => {
(['legacy', 'psbt'] as const).forEach((txFormat) => {
if (!coin.supportsAddressType(type === 'taprootKeyPathSpend' ? 'p2trMusig2' : type)) {
return;
}
if ((type === 'taprootKeyPathSpend' || type === 'p2trMusig2') && txFormat !== 'psbt') {
return;
}
run(coin, [type, type], txFormat);
if (getReplayProtectionAddresses(coin.name).length) {
run(coin, ['p2shP2pk', type], txFormat);
}
if (txFormat === 'psbt') {
run(coin, [type, type], txFormat, { decodeWith: 'wasm-utxo' });
if (getReplayProtectionAddresses(coin.name).length) {
run(coin, ['p2shP2pk', type], txFormat, { decodeWith: 'wasm-utxo' });
}
}
});
});
}
describe('Transaction Suite', function () {
utxoCoins.forEach((coin) => {
describe(`${coin.getChain()}`, function () {
runTestForCoin(coin);
});
});
});