-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathprebuildAndSign.ts
More file actions
328 lines (291 loc) · 11 KB
/
prebuildAndSign.ts
File metadata and controls
328 lines (291 loc) · 11 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
import * as assert from 'assert';
import * as utxolib from '@bitgo/utxo-lib';
import { fixedScriptWallet } from '@bitgo/wasm-utxo';
import nock = require('nock');
import { common, HalfSignedUtxoTransaction, Wallet } from '@bitgo/sdk-core';
import { getSeed } from '@bitgo/sdk-test';
import {
AbstractUtxoCoin,
getReplayProtectionAddresses,
ScriptType2Of3,
utxolibScriptTypes2Of3,
UtxolibScriptType,
} from '../../src';
import { getMainnetCoinName } from '../../src/names';
import { defaultBitGo, encryptKeychain, getDefaultWalletKeys, getUtxoWallet, keychainsBase58, utxoCoins } from './util';
const txFormats = ['legacy', 'psbt'] as const;
export type TxFormat = (typeof txFormats)[number];
type KeyDoc = {
id: string;
pub: string;
source: string;
encryptedPrv: string;
coinSpecific: any;
};
const walletPassphrase = 'gabagool';
const webauthnWalletPassPhrase = 'just the gabagool';
const scriptTypes = [...utxolibScriptTypes2Of3, 'taprootKeyPathSpend', 'p2shP2pk'] as const;
export type ScriptType = (typeof scriptTypes)[number];
type Input = {
scriptType: ScriptType;
value: bigint;
};
function assertSignable(psbtHex: string, inputScripts: ScriptType[], network: utxolib.Network): void {
const psbt = utxolib.bitgo.createPsbtFromHex(psbtHex, network);
// Make sure that you can sign with bitgo key and extract the transaction
// No signatures should be present if it's a p2shP2pk input
if (!inputScripts.includes('p2shP2pk')) {
const key = inputScripts.includes('p2trMusig2') ? rootWalletKeys.backup : rootWalletKeys.bitgo;
psbt.signAllInputsHD(key, { deterministic: true });
psbt.validateSignaturesOfAllInputs();
psbt.finalizeAllInputs();
const tx = psbt.extractTransaction();
assert.ok(tx);
}
}
// Build the key objects
const rootWalletKeys = getDefaultWalletKeys();
const keyDocumentObjects = rootWalletKeys.triple.map((bip32, keyIdx) => {
return {
id: getSeed(keychainsBase58[keyIdx].pub).toString('hex'),
pub: bip32.neutered().toBase58(),
source: ['user', 'backup', 'bitgo'][keyIdx],
encryptedPrv: encryptKeychain(walletPassphrase, keychainsBase58[keyIdx]),
webauthnDevices: [
{
otpDeviceId: '123',
authenticatorInfo: {
credID: 'credID',
fmt: 'packed',
publicKey: 'some value',
},
prfSalt: '456',
encryptedPrv: encryptKeychain(webauthnWalletPassPhrase, keychainsBase58[keyIdx]),
},
],
coinSpecific: {},
};
});
function run(coin: AbstractUtxoCoin, inputScripts: ScriptType[], txFormat: TxFormat): void {
function createPrebuildPsbt(inputs: Input[], outputs: { scriptType: 'p2sh'; value: bigint }[]) {
const psbt = utxolib.testutil.constructPsbt(
inputs as utxolib.testutil.Input[],
outputs,
coin.network,
rootWalletKeys,
'unsigned'
);
utxolib.bitgo.addXpubsToPsbt(psbt, rootWalletKeys);
return psbt;
}
function createNocks(params: {
bgUrl: string;
wallet: Wallet;
keyDocuments: KeyDoc[];
prebuild: utxolib.bitgo.UtxoPsbt;
recipient: { address: string; amount: string };
addressInfo: Record<string, any>;
rbfTxIds?: string[];
feeMultiplier?: number;
selfSend?: boolean;
nockOutputAddresses?: boolean;
txFormat?: string;
}): nock.Scope[] {
const nocks: nock.Scope[] = [];
// Nock the prebuild route (/tx/build, blockheight)
const expected_params = {
recipients: [params.recipient],
rbfTxIds: params.rbfTxIds,
feeMultiplier: params.feeMultiplier,
changeAddressType: ['p2trMusig2', 'p2wsh', 'p2shP2wsh', 'p2sh', 'p2tr'],
};
if (params.txFormat) {
expected_params['txFormat'] = params.txFormat;
}
nocks.push(
nock(params.bgUrl)
.post(`/api/v2/${coin.getChain()}/wallet/${params.wallet.id()}/tx/build`, expected_params)
.reply(200, { txHex: params.prebuild.toHex(), txInfo: {} })
);
nocks.push(nock(params.bgUrl).get(`/api/v2/${coin.getChain()}/public/block/latest`).reply(200, { height: 1000 }));
// nock the keychain fetch - 3 times (prebuildAndSign, verifyTransaction, and signTransaction)
params.keyDocuments.forEach((keyDocument) => {
nocks.push(
nock(params.bgUrl).get(`/api/v2/${coin.getChain()}/key/${keyDocument.id}`).times(3).reply(200, keyDocument)
);
});
// nock the address info fetch
if (params.nockOutputAddresses) {
nocks.push(
nock(params.bgUrl)
.get(`/api/v2/${coin.getChain()}/wallet/${params.wallet.id()}/address/${params.addressInfo.address}`)
.reply(200, params.addressInfo)
);
}
if (params.rbfTxIds) {
nocks.push(
nock(params.bgUrl)
.get(`/api/v2/${coin.getChain()}/wallet/${params.wallet.id()}/tx/${params.rbfTxIds[0]}?includeRbf=true`)
.reply(200, {
outputs: [
{
address: params.recipient.address,
value: Number(params.recipient.amount),
valueString: params.recipient.amount,
wallet: params.selfSend ? params.wallet.id() : 'some-other-wallet-id', // external output if not a self send
},
// Dummy change output to test transfer entries filtering
{
address: params.recipient.address,
value: Number(params.recipient.amount),
valueString: params.recipient.amount,
wallet: params.wallet.id(), // internal output
},
],
})
);
}
// nock the deterministic nonce response
if (inputScripts.includes('taprootKeyPathSpend')) {
const psbt = params.prebuild.clone();
psbt.setAllInputsMusig2NonceHD(rootWalletKeys.user);
psbt.setAllInputsMusig2NonceHD(rootWalletKeys.bitgo);
nocks.push(
nock(params.bgUrl)
.post(`/api/v2/${coin.getChain()}/wallet/${params.wallet.id()}/tx/signpsbt`, (body) => body.psbt)
.reply(200, { psbt: psbt.toHex() })
);
}
return nocks;
}
describe(`${coin.getFullName()}-prebuildAndSign-txFormat=${txFormat}-inputScripts=${inputScripts.join(
','
)}`, function () {
const wallet = getUtxoWallet(coin, {
coinSpecific: { addressVersion: 'base58' },
keys: keyDocumentObjects.map((k) => k.id),
id: 'walletId',
});
const bgUrl = common.Environments[defaultBitGo.getEnv()].uri;
let prebuild: utxolib.bitgo.UtxoPsbt;
let recipient: { address: string; amount: string };
let addressInfo: Record<string, any>;
const fee = BigInt(10000);
before(async function () {
// Make output address information
const outputAmount = BigInt(inputScripts.length) * BigInt(1e8) - fee;
const outputScriptType: UtxolibScriptType = 'p2sh';
const outputChain = fixedScriptWallet.ChainCode.value(outputScriptType, 'external');
const outputAddress = utxolib.bitgo.getWalletAddress(rootWalletKeys, outputChain, 0, coin.network);
recipient = {
address: outputAddress,
amount: outputAmount.toString(),
};
addressInfo = {
address: outputAddress,
chain: outputChain,
index: 0,
coin: coin.getChain(),
wallet: wallet.id(),
coinSpecific: {},
};
prebuild = createPrebuildPsbt(
inputScripts.map((s) => ({ scriptType: s, value: BigInt(1e8) })),
[{ scriptType: outputScriptType, value: outputAmount }]
);
});
afterEach(nock.cleanAll);
[true, false].forEach((useWebauthn) => {
it(`should succeed with ${useWebauthn ? 'webauthn encryptedPrv' : 'encryptedPrv'}`, async function () {
// Check if this wallet/coin combination defaults to psbt
const defaultTxFormat = coin.getDefaultTxFormat(wallet);
const nocks = createNocks({
bgUrl,
wallet,
keyDocuments: keyDocumentObjects,
prebuild,
recipient,
addressInfo,
nockOutputAddresses: txFormat !== 'psbt',
txFormat: defaultTxFormat,
});
// call prebuild and sign, nocks should be consumed
const res = (await wallet.prebuildAndSignTransaction({
recipients: [recipient],
walletPassphrase: useWebauthn ? webauthnWalletPassPhrase : walletPassphrase,
})) as HalfSignedUtxoTransaction;
nocks.forEach((nock) => assert.ok(nock.isDone()));
assertSignable(res.txHex, inputScripts, coin.network);
});
it('should fail if the wallet passphrase is incorrect', async function () {
createNocks({
bgUrl,
wallet,
keyDocuments: keyDocumentObjects,
prebuild,
recipient,
addressInfo,
nockOutputAddresses: txFormat !== 'psbt',
});
await wallet
.prebuildAndSignTransaction({
recipients: [recipient],
walletPassphrase: Math.random().toString(),
})
.should.be.rejectedWith('unable to decrypt keychain with the given wallet passphrase');
});
});
[true, false].forEach((selfSend) => {
it(`should be able to build, sign, & verify a replacement transaction with selfSend: ${selfSend}`, async function () {
const rbfTxIds = ['tx-to-be-replaced'],
feeMultiplier = 1.5;
// Check if this wallet/coin combination defaults to psbt
const defaultTxFormat = coin.getDefaultTxFormat(wallet);
const nocks = createNocks({
bgUrl,
wallet,
keyDocuments: keyDocumentObjects,
prebuild,
recipient,
addressInfo,
rbfTxIds,
feeMultiplier,
selfSend,
nockOutputAddresses: txFormat !== 'psbt',
txFormat: defaultTxFormat,
});
// call prebuild and sign, nocks should be consumed
const res = (await wallet.prebuildAndSignTransaction({
recipients: [recipient],
walletPassphrase,
rbfTxIds,
feeMultiplier,
})) as HalfSignedUtxoTransaction;
nocks.forEach((nock) => assert.ok(nock.isDone()));
assertSignable(res.txHex, inputScripts, coin.network);
});
});
});
}
utxoCoins
.filter((coin) => getMainnetCoinName(coin.name) !== 'bsv')
.forEach((coin) => {
scriptTypes
// Don't iterate over p2shP2pk - in no scenario would a wallet spend two p2shP2pk inputs as these
// are single signature inputs that are used for replay protection and are added to the transaction
// by our system from a separate wallet. We do run tests below where one of the inputs is a p2shP2pk and
// the other is an input spent by the user.
.filter((scriptType) => scriptType !== 'p2shP2pk')
.forEach((inputScript) => {
const inputScriptCleaned = (
inputScript === 'taprootKeyPathSpend' ? 'p2trMusig2' : inputScript
) as ScriptType2Of3;
if (!coin.supportsAddressType(inputScriptCleaned)) {
return;
}
run(coin, [inputScript, inputScript], 'psbt');
if (getReplayProtectionAddresses(coin.name).length) {
run(coin, ['p2shP2pk', inputScript], 'psbt');
}
});
});