-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathparse.ts
More file actions
171 lines (157 loc) · 6.71 KB
/
parse.ts
File metadata and controls
171 lines (157 loc) · 6.71 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
import { ITransactionRecipient } from '@bitgo/sdk-core';
import { Psbt, descriptorWallet } from '@bitgo/wasm-utxo';
import { AbstractUtxoCoin, ParseTransactionOptions } from '../../abstractUtxoCoin';
import { BaseOutput, BaseParsedTransaction, BaseParsedTransactionOutputs } from '../types';
import { getKeySignatures, toBip32Triple, UtxoNamedKeychains } from '../../keychains';
import { getDescriptorMapFromWallet, getPolicyForEnv } from '../../descriptor';
import { IDescriptorWallet } from '../../descriptor/descriptorWallet';
import { fromExtendedAddressFormatToScript, toExtendedAddressFormat } from '../recipient';
import {
getMissingOutputs,
isImplicitOutput,
outputDifference,
OutputDifferenceWithExpected,
} from '../outputDifference';
import { UtxoCoinName } from '../../names';
import { sumValues, toWasmPsbt, UtxoLibPsbt } from '../../wasmUtil';
type ParsedOutput = Omit<descriptorWallet.ParsedOutput, 'script'> & { script: Buffer };
export type RecipientOutput = Omit<ParsedOutput, 'value'> & {
value: bigint | 'max';
};
function toRecipientOutput(recipient: ITransactionRecipient, coinName: UtxoCoinName): RecipientOutput {
return {
address: recipient.address,
value: recipient.amount === 'max' ? 'max' : BigInt(recipient.amount),
script: fromExtendedAddressFormatToScript(recipient.address, coinName),
scriptId: undefined, // Recipients are external outputs
};
}
// TODO(BTC-1697): allow outputs with `value: 'max'` here
type ParsedOutputs = OutputDifferenceWithExpected<ParsedOutput, RecipientOutput> & {
outputs: ParsedOutput[];
changeOutputs: ParsedOutput[];
};
function parseOutputsWithPsbt(
psbt: Psbt,
descriptorMap: descriptorWallet.DescriptorMap,
recipientOutputs: RecipientOutput[],
coinName: UtxoCoinName
): ParsedOutputs {
const parsed = descriptorWallet.parse(psbt, descriptorMap, coinName);
const outputs: ParsedOutput[] = parsed.outputs.map((output) => ({
...output,
script: Buffer.from(output.script),
}));
const changeOutputs = outputs.filter((o) => o.scriptId !== undefined);
/**
* Two-pass approach to handle self-payments (outputs going to the sender's own wallet address):
*
* Pass 1 — missing outputs: Check all PSBT outputs (including change/internal) against the
* expected recipients. This ensures self-payments that are classified as change outputs by the
* descriptor wallet (isChange = true) are still matched against the intent recipients and do not
* appear as missing. This mirrors the multisig (fixedScript) flow where allOutputs includes
* both explanation.outputs and explanation.changeOutputs.
*
* Pass 2 — implicit outputs: Of the outputs NOT in the recipient list, only flag those that go
* to external addresses (scriptId = undefined) as implicit. Internal outputs (scriptId set) that
* are not in recipients are legitimate change outputs and should not be flagged.
*/
const missingOutputs = getMissingOutputs(outputs, recipientOutputs);
const implicitOutputs = outputs.filter((o) => isImplicitOutput(o, recipientOutputs));
const explicitOutputs = outputDifference(outputs, implicitOutputs);
return {
outputs,
changeOutputs,
explicitOutputs,
implicitOutputs,
missingOutputs,
};
}
function toBaseOutputs(outputs: ParsedOutput[], coinName: UtxoCoinName): BaseOutput<bigint>[];
function toBaseOutputs(outputs: RecipientOutput[], coinName: UtxoCoinName): BaseOutput<bigint | 'max'>[];
function toBaseOutputs(
outputs: (ParsedOutput | RecipientOutput)[],
coinName: UtxoCoinName
): BaseOutput<bigint | 'max'>[] {
return outputs.map(
(o): BaseOutput<bigint | 'max'> => ({
address: toExtendedAddressFormat(o.script, coinName),
amount: o.value === 'max' ? 'max' : BigInt(o.value),
external: o.scriptId === undefined,
})
);
}
export type ParsedOutputsBigInt = BaseParsedTransactionOutputs<bigint, BaseOutput<bigint | 'max'>>;
function toBaseParsedTransactionOutputs(
{ outputs, changeOutputs, explicitOutputs, implicitOutputs, missingOutputs }: ParsedOutputs,
coinName: UtxoCoinName
): ParsedOutputsBigInt {
const explicitExternalOutputs = explicitOutputs.filter((o) => o.scriptId === undefined);
const implicitExternalOutputs = implicitOutputs.filter((o) => o.scriptId === undefined);
return {
outputs: toBaseOutputs(outputs, coinName),
changeOutputs: toBaseOutputs(changeOutputs, coinName),
explicitExternalOutputs: toBaseOutputs(explicitExternalOutputs, coinName),
explicitExternalSpendAmount: sumValues(explicitExternalOutputs),
implicitExternalOutputs: toBaseOutputs(implicitExternalOutputs, coinName),
implicitExternalSpendAmount: sumValues(implicitExternalOutputs),
missingOutputs: toBaseOutputs(missingOutputs, coinName),
};
}
export function toBaseParsedTransactionOutputsFromPsbt(
psbt: Psbt | UtxoLibPsbt | Uint8Array,
descriptorMap: descriptorWallet.DescriptorMap,
recipients: ITransactionRecipient[],
coinName: UtxoCoinName
): ParsedOutputsBigInt {
const wasmPsbt = toWasmPsbt(psbt);
return toBaseParsedTransactionOutputs(
parseOutputsWithPsbt(
wasmPsbt,
descriptorMap,
recipients.map((r) => toRecipientOutput(r, coinName)),
coinName
),
coinName
);
}
export type ParsedDescriptorTransaction<TAmount extends number | bigint> = BaseParsedTransaction<
TAmount,
BaseOutput<TAmount | 'max'>
>;
export function parse(
coin: AbstractUtxoCoin,
wallet: IDescriptorWallet,
params: ParseTransactionOptions<number | bigint>
): ParsedDescriptorTransaction<bigint> {
if (params.txParams.allowExternalChangeAddress) {
throw new Error('allowExternalChangeAddress is not supported for descriptor wallets');
}
if (params.txParams.changeAddress) {
throw new Error('changeAddress is not supported for descriptor wallets');
}
const keychains = params.verification?.keychains;
if (!keychains || !UtxoNamedKeychains.is(keychains)) {
throw new Error('keychain is required for descriptor wallets');
}
const { recipients } = params.txParams;
if (!recipients) {
throw new Error('recipients is required');
}
const psbt = coin.decodeTransactionFromPrebuild(params.txPrebuild);
let wasmPsbt: Psbt;
try {
wasmPsbt = toWasmPsbt(psbt as Psbt | UtxoLibPsbt | Uint8Array);
} catch (e) {
throw new Error(`expected psbt to be a wasm-utxo or utxo-lib PSBT: ${e instanceof Error ? e.message : e}`);
}
const walletKeys = toBip32Triple(keychains);
const descriptorMap = getDescriptorMapFromWallet(wallet, walletKeys, getPolicyForEnv(params.wallet.bitgo.env));
return {
...toBaseParsedTransactionOutputsFromPsbt(wasmPsbt, descriptorMap, recipients, coin.name),
keychains,
keySignatures: getKeySignatures(wallet) ?? {},
customChange: undefined,
needsCustomChangeKeySignatureVerification: false,
};
}