-
Notifications
You must be signed in to change notification settings - Fork 14
/
psbt.ts
257 lines (241 loc) · 7.2 KB
/
psbt.ts
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
// Copyright (c) 2023 Jose-Luis Landabaso - https://bitcoinerlab.com
// Distributed under the MIT software license
import type { PsbtInput, Bip32Derivation } from 'bip174/src/lib/interfaces';
import type { KeyInfo } from './types';
import {
payments,
Network,
Psbt,
Transaction,
PsbtTxInput
} from 'bitcoinjs-lib';
import * as varuint from 'bip174/src/lib/converter/varint';
interface PsbtInputExtended extends PsbtInput, PsbtTxInput {}
function reverseBuffer(buffer: Buffer): Buffer {
if (buffer.length < 1) return buffer;
let j = buffer.length - 1;
let tmp = 0;
for (let i = 0; i < buffer.length / 2; i++) {
tmp = buffer[i]!;
buffer[i] = buffer[j]!;
buffer[j] = tmp;
j--;
}
return buffer;
}
function witnessStackToScriptWitness(witness: Buffer[]): Buffer {
let buffer = Buffer.allocUnsafe(0);
function writeSlice(slice: Buffer): void {
buffer = Buffer.concat([buffer, Buffer.from(slice)]);
}
function writeVarInt(i: number): void {
const currentLen = buffer.length;
const varintLen = varuint.encodingLength(i);
buffer = Buffer.concat([buffer, Buffer.allocUnsafe(varintLen)]);
varuint.encode(i, buffer, currentLen);
}
function writeVarSlice(slice: Buffer): void {
writeVarInt(slice.length);
writeSlice(slice);
}
function writeVector(vector: Buffer[]): void {
writeVarInt(vector.length);
vector.forEach(writeVarSlice);
}
writeVector(witness);
return buffer;
}
/**
* This function must do two things:
* 1. Check if the `input` can be finalized. If it can not be finalized, throw.
* ie. `Can not finalize input #${inputIndex}`
* 2. Create the finalScriptSig and finalScriptWitness Buffers.
*/
type FinalScriptsFunc = (
inputIndex: number, // Which input is it?
input: PsbtInput, // The PSBT input contents
script: Buffer, // The "meaningful" locking script Buffer (redeemScript for P2SH etc.)
isSegwit: boolean, // Is it segwit?
isP2SH: boolean, // Is it P2SH?
isP2WSH: boolean // Is it P2WSH?
) => {
finalScriptSig: Buffer | undefined;
finalScriptWitness: Buffer | undefined;
};
export function finalScriptsFuncFactory(
scriptSatisfaction: Buffer,
network: Network
): FinalScriptsFunc {
const finalScriptsFunc: FinalScriptsFunc = (
_index,
_input,
lockingScript /*witnessScript or redeemScript*/,
isSegwit,
isP2SH,
_isP2WSH
) => {
let finalScriptWitness: Buffer | undefined;
let finalScriptSig: Buffer | undefined;
//p2wsh
if (isSegwit && !isP2SH) {
const payment = payments.p2wsh({
redeem: { input: scriptSatisfaction, output: lockingScript },
network
});
if (!payment.witness)
throw new Error(`Error: p2wsh failed producing a witness`);
finalScriptWitness = witnessStackToScriptWitness(payment.witness);
}
//p2sh-p2wsh
else if (isSegwit && isP2SH) {
const payment = payments.p2sh({
redeem: payments.p2wsh({
redeem: { input: scriptSatisfaction, output: lockingScript },
network
}),
network
});
if (!payment.witness)
throw new Error(`Error: p2sh-p2wsh failed producing a witness`);
finalScriptWitness = witnessStackToScriptWitness(payment.witness);
finalScriptSig = payment.input;
}
//p2sh
else {
finalScriptSig = payments.p2sh({
redeem: { input: scriptSatisfaction, output: lockingScript },
network
}).input;
}
return {
finalScriptWitness,
finalScriptSig
};
};
return finalScriptsFunc;
}
/**
* Important: Read comments on descriptor.updatePsbt regarding not passing txHex
*/
export function updatePsbt({
psbt,
vout,
txHex,
txId,
value,
sequence,
locktime,
keysInfo,
scriptPubKey,
isSegwit,
witnessScript,
redeemScript
}: {
psbt: Psbt;
vout: number;
txHex?: string;
txId?: string;
value?: number;
sequence: number | undefined;
locktime: number | undefined;
keysInfo: KeyInfo[];
scriptPubKey: Buffer;
isSegwit: boolean;
witnessScript: Buffer | undefined;
redeemScript: Buffer | undefined;
}): number {
//Some data-sanity checks:
if (!isSegwit && txHex === undefined)
throw new Error(`Error: txHex is mandatory for Non-Segwit inputs`);
if (
isSegwit &&
txHex === undefined &&
(txId === undefined || value === undefined)
)
throw new Error(`Error: pass txHex or txId+value for Segwit inputs`);
if (txHex !== undefined) {
const tx = Transaction.fromHex(txHex);
const out = tx?.outs?.[vout];
if (!out) throw new Error(`Error: tx ${txHex} does not have vout ${vout}`);
const outputScript = out.script;
if (!outputScript)
throw new Error(
`Error: could not extract outputScript for txHex ${txHex} and vout ${vout}`
);
if (Buffer.compare(outputScript, scriptPubKey) !== 0)
throw new Error(
`Error: txHex ${txHex} for vout ${vout} does not correspond to scriptPubKey ${scriptPubKey}`
);
if (txId !== undefined) {
if (tx.getId() !== txId)
throw new Error(
`Error: txId for ${txHex} and vout ${vout} does not correspond to ${txId}`
);
} else {
txId = tx.getId();
}
if (value !== undefined) {
if (out.value !== value)
throw new Error(
`Error: value for ${txHex} and vout ${vout} does not correspond to ${value}`
);
} else {
value = out.value;
}
}
if (txId === undefined || !value)
throw new Error(
`Error: txHex+vout required. Alternatively, but ONLY for Segwit inputs, txId+value can also be passed.`
);
if (locktime !== undefined) {
if (psbt.locktime !== 0 && psbt.locktime !== undefined)
throw new Error(
`Error: transaction locktime has already been set: ${psbt.locktime}`
);
psbt.setLocktime(locktime);
}
let inputSequence;
if (locktime !== undefined) {
if (sequence === undefined) {
// for CTV nSequence MUST be <= 0xfffffffe otherwise OP_CHECKLOCKTIMEVERIFY will fail.
inputSequence = 0xfffffffe;
} else if (sequence > 0xfffffffe) {
throw new Error(
`Error: incompatible sequence: ${inputSequence} and locktime: ${locktime}`
);
} else {
inputSequence = sequence;
}
} else {
inputSequence = sequence;
}
const input: PsbtInputExtended = {
hash: reverseBuffer(Buffer.from(txId, 'hex')),
index: vout
};
if (txHex !== undefined) {
input.nonWitnessUtxo = Transaction.fromHex(txHex).toBuffer();
}
const bip32Derivation = keysInfo
.filter(
(keyInfo: KeyInfo) =>
keyInfo.pubkey && keyInfo.masterFingerprint && keyInfo.path
)
.map(
(keyInfo: KeyInfo): Bip32Derivation => ({
masterFingerprint: keyInfo.masterFingerprint!,
pubkey: keyInfo.pubkey,
path: keyInfo.path!
})
);
if (bip32Derivation.length) input.bip32Derivation = bip32Derivation;
if (isSegwit && txHex !== undefined) {
//There's no need to put both witnessUtxo and nonWitnessUtxo
input.witnessUtxo = { script: scriptPubKey, value };
}
if (inputSequence !== undefined) input.sequence = inputSequence;
if (witnessScript) input.witnessScript = witnessScript;
if (redeemScript) input.redeemScript = redeemScript;
psbt.addInput(input);
return psbt.data.inputs.length - 1;
}