@scure/btc-signer 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +19 -3
  2. package/lib/_type_test.d.ts +2 -0
  3. package/lib/_type_test.d.ts.map +1 -0
  4. package/lib/_type_test.js +59 -0
  5. package/lib/_type_test.js.map +1 -0
  6. package/lib/esm/_type_test.js +57 -0
  7. package/lib/esm/_type_test.js.map +1 -0
  8. package/lib/esm/index.js +13 -3007
  9. package/lib/esm/index.js.map +1 -1
  10. package/lib/esm/payment.js +681 -0
  11. package/lib/esm/payment.js.map +1 -0
  12. package/lib/esm/psbt.js +441 -0
  13. package/lib/esm/psbt.js.map +1 -0
  14. package/lib/esm/script.js +347 -0
  15. package/lib/esm/script.js.map +1 -0
  16. package/lib/esm/transaction.js +1013 -0
  17. package/lib/esm/transaction.js.map +1 -0
  18. package/lib/esm/utils.js +115 -0
  19. package/lib/esm/utils.js.map +1 -0
  20. package/lib/esm/utxo.js +491 -0
  21. package/lib/esm/utxo.js.map +1 -0
  22. package/lib/index.d.ts +18 -1439
  23. package/lib/index.d.ts.map +1 -1
  24. package/lib/index.js +53 -3042
  25. package/lib/index.js.map +1 -0
  26. package/lib/payment.d.ts +167 -0
  27. package/lib/payment.d.ts.map +1 -0
  28. package/lib/payment.js +704 -0
  29. package/lib/payment.js.map +1 -0
  30. package/lib/psbt.d.ts +834 -0
  31. package/lib/psbt.d.ts.map +1 -0
  32. package/lib/psbt.js +446 -0
  33. package/lib/psbt.js.map +1 -0
  34. package/lib/script.d.ts +154 -0
  35. package/lib/script.d.ts.map +1 -0
  36. package/lib/script.js +353 -0
  37. package/lib/script.js.map +1 -0
  38. package/lib/transaction.d.ts +223 -0
  39. package/lib/transaction.d.ts.map +1 -0
  40. package/lib/transaction.js +1022 -0
  41. package/lib/transaction.js.map +1 -0
  42. package/lib/utils.d.ts +30 -0
  43. package/lib/utils.d.ts.map +1 -0
  44. package/lib/utils.js +128 -0
  45. package/lib/utils.js.map +1 -0
  46. package/lib/utxo.d.ts +251 -0
  47. package/lib/utxo.d.ts.map +1 -0
  48. package/lib/utxo.js +501 -0
  49. package/lib/utxo.js.map +1 -0
  50. package/package.json +40 -10
  51. package/src/_type_test.ts +69 -0
  52. package/src/index.ts +28 -0
  53. package/src/package.json +3 -0
  54. package/src/payment.ts +749 -0
  55. package/src/psbt.ts +512 -0
  56. package/src/script.ts +236 -0
  57. package/src/transaction.ts +1065 -0
  58. package/src/utils.ts +118 -0
  59. package/src/utxo.ts +517 -0
  60. package/index.ts +0 -3067
package/src/psbt.ts ADDED
@@ -0,0 +1,512 @@
1
+ import { hex } from '@scure/base';
2
+ import * as P from 'micro-packed';
3
+ import { CompactSize, CompactSizeLen, RawOutput, RawTx, RawWitness, VarBytes } from './script.js';
4
+ import { Transaction } from './transaction.js'; // circular
5
+ import { Bytes, compareBytes, PubT, validatePubkey } from './utils.js';
6
+
7
+ // PSBT BIP174, BIP370, BIP371
8
+
9
+ // Can be 33 or 64 bytes
10
+ const PubKeyECDSA = P.validate(P.bytes(null), (pub) => validatePubkey(pub, PubT.ecdsa));
11
+ const PubKeySchnorr = P.validate(P.bytes(32), (pub) => validatePubkey(pub, PubT.schnorr));
12
+ const SignatureSchnorr = P.validate(P.bytes(null), (sig) => {
13
+ if (sig.length !== 64 && sig.length !== 65)
14
+ throw new Error('Schnorr signature should be 64 or 65 bytes long');
15
+ return sig;
16
+ });
17
+
18
+ const BIP32Der = P.struct({
19
+ fingerprint: P.U32BE,
20
+ path: P.array(null, P.U32LE),
21
+ });
22
+ const TaprootBIP32Der = P.struct({
23
+ hashes: P.array(CompactSizeLen, P.bytes(32)),
24
+ der: BIP32Der,
25
+ });
26
+ // The 78 byte serialized extended public key as defined by BIP 32.
27
+ const GlobalXPUB = P.bytes(78);
28
+ const tapScriptSigKey = P.struct({ pubKey: PubKeySchnorr, leafHash: P.bytes(32) });
29
+
30
+ // Complex structure for PSBT fields
31
+ // <control byte with leaf version and parity bit> <internal key p> <C> <E> <AB>
32
+ const _TaprootControlBlock = P.struct({
33
+ version: P.U8, // With parity :(
34
+ internalKey: P.bytes(32),
35
+ merklePath: P.array(null, P.bytes(32)),
36
+ });
37
+ export const TaprootControlBlock = P.validate(_TaprootControlBlock, (cb) => {
38
+ if (cb.merklePath.length > 128)
39
+ throw new Error('TaprootControlBlock: merklePath should be of length 0..128 (inclusive)');
40
+ return cb;
41
+ });
42
+
43
+ // {<8-bit uint depth> <8-bit uint leaf version> <compact size uint scriptlen> <bytes script>}*
44
+ const tapTree = P.array(
45
+ null,
46
+ P.struct({
47
+ depth: P.U8,
48
+ version: P.U8,
49
+ script: VarBytes,
50
+ })
51
+ );
52
+
53
+ const BytesInf = P.bytes(null); // Bytes will conflict with Bytes type
54
+ const Bytes20 = P.bytes(20);
55
+ const Bytes32 = P.bytes(32);
56
+ // versionsRequiringExclusing = !versionsAllowsInclusion (as set)
57
+ // {name: [tag, keyCoder, valueCoder, versionsRequiringInclusion, versionsRequiringExclusing, versionsAllowsInclusion, silentIgnore]}
58
+ // SilentIgnore: we use some v2 fields for v1 representation too, so we just clean them before serialize
59
+
60
+ // Tables from BIP-0174 (https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki)
61
+ // prettier-ignore
62
+ export const PSBTGlobal = {
63
+ unsignedTx: [0x00, false, RawTx, [0], [0], false],
64
+ xpub: [0x01, GlobalXPUB, BIP32Der, [], [0, 2], false],
65
+ txVersion: [0x02, false, P.U32LE, [2], [2], false],
66
+ fallbackLocktime: [0x03, false, P.U32LE, [], [2], false],
67
+ inputCount: [0x04, false, CompactSizeLen, [2], [2], false],
68
+ outputCount: [0x05, false, CompactSizeLen, [2], [2], false],
69
+ txModifiable: [0x06, false, P.U8, [], [2], false], // TODO: bitfield
70
+ version: [0xfb, false, P.U32LE, [], [0, 2], false],
71
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
72
+ } as const;
73
+ // prettier-ignore
74
+ export const PSBTInput = {
75
+ nonWitnessUtxo: [0x00, false, RawTx, [], [0, 2], false],
76
+ witnessUtxo: [0x01, false, RawOutput, [], [0, 2], false],
77
+ partialSig: [0x02, PubKeyECDSA, BytesInf, [], [0, 2], false],
78
+ sighashType: [0x03, false, P.U32LE, [], [0, 2], false],
79
+ redeemScript: [0x04, false, BytesInf, [], [0, 2], false],
80
+ witnessScript: [0x05, false, BytesInf, [], [0, 2], false],
81
+ bip32Derivation: [0x06, PubKeyECDSA, BIP32Der, [], [0, 2], false],
82
+ finalScriptSig: [0x07, false, BytesInf, [], [0, 2], false],
83
+ finalScriptWitness: [0x08, false, RawWitness, [], [0, 2], false],
84
+ porCommitment: [0x09, false, BytesInf, [], [0, 2], false],
85
+ ripemd160: [0x0a, Bytes20, BytesInf, [], [0, 2], false],
86
+ sha256: [0x0b, Bytes32, BytesInf, [], [0, 2], false],
87
+ hash160: [0x0c, Bytes20, BytesInf, [], [0, 2], false],
88
+ hash256: [0x0d, Bytes32, BytesInf, [], [0, 2], false],
89
+ txid: [0x0e, false, Bytes32, [2], [2], true],
90
+ index: [0x0f, false, P.U32LE, [2], [2], true],
91
+ sequence: [0x10, false, P.U32LE, [], [2], true],
92
+ requiredTimeLocktime: [0x11, false, P.U32LE, [], [2], false],
93
+ requiredHeightLocktime: [0x12, false, P.U32LE, [], [2], false],
94
+ tapKeySig: [0x13, false, SignatureSchnorr, [], [0, 2], false],
95
+ tapScriptSig: [0x14, tapScriptSigKey, SignatureSchnorr, [], [0, 2], false],
96
+ tapLeafScript: [0x15, TaprootControlBlock, BytesInf, [], [0, 2], false],
97
+ tapBip32Derivation: [0x16, Bytes32, TaprootBIP32Der, [], [0, 2], false],
98
+ tapInternalKey: [0x17, false, PubKeySchnorr, [], [0, 2], false],
99
+ tapMerkleRoot: [0x18, false, Bytes32, [], [0, 2], false],
100
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
101
+ } as const;
102
+ // All other keys removed when finalizing
103
+ export const PSBTInputFinalKeys: (keyof TransactionInput)[] = [
104
+ 'txid',
105
+ 'sequence',
106
+ 'index',
107
+ 'witnessUtxo',
108
+ 'nonWitnessUtxo',
109
+ 'finalScriptSig',
110
+ 'finalScriptWitness',
111
+ 'unknown',
112
+ ];
113
+
114
+ // Can be modified even on signed input
115
+ export const PSBTInputUnsignedKeys: (keyof TransactionInput)[] = [
116
+ 'partialSig',
117
+ 'finalScriptSig',
118
+ 'finalScriptWitness',
119
+ 'tapKeySig',
120
+ 'tapScriptSig',
121
+ ];
122
+
123
+ // prettier-ignore
124
+ export const PSBTOutput = {
125
+ redeemScript: [0x00, false, BytesInf, [], [0, 2], false],
126
+ witnessScript: [0x01, false, BytesInf, [], [0, 2], false],
127
+ bip32Derivation: [0x02, PubKeyECDSA, BIP32Der, [], [0, 2], false],
128
+ amount: [0x03, false, P.I64LE, [2], [2], true],
129
+ script: [0x04, false, BytesInf, [2], [2], true],
130
+ tapInternalKey: [0x05, false, PubKeySchnorr, [], [0, 2], false],
131
+ tapTree: [0x06, false, tapTree, [], [0, 2], false],
132
+ tapBip32Derivation: [0x07, PubKeySchnorr, TaprootBIP32Der, [], [0, 2], false],
133
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
134
+ } as const;
135
+
136
+ // Can be modified even on signed input
137
+ export const PSBTOutputUnsignedKeys: (keyof typeof PSBTOutput)[] = [];
138
+
139
+ const PSBTKeyPair = P.array(
140
+ P.NULL,
141
+ P.struct({
142
+ // <key> := <keylen> <keytype> <keydata> WHERE keylen = len(keytype)+len(keydata)
143
+ key: P.prefix(CompactSizeLen, P.struct({ type: CompactSizeLen, key: P.bytes(null) })),
144
+ // <value> := <valuelen> <valuedata>
145
+ value: P.bytes(CompactSizeLen),
146
+ })
147
+ );
148
+
149
+ type PSBTKeyCoder = P.CoderType<any> | false;
150
+
151
+ type PSBTKeyMapInfo = Readonly<
152
+ [
153
+ number,
154
+ PSBTKeyCoder,
155
+ any,
156
+ readonly number[], // versionsRequiringInclusion
157
+ readonly number[], // versionsAllowsInclusion
158
+ boolean, // silentIgnore
159
+ ]
160
+ >;
161
+
162
+ function PSBTKeyInfo(info: PSBTKeyMapInfo) {
163
+ const [type, kc, vc, reqInc, allowInc, silentIgnore] = info;
164
+ return { type, kc, vc, reqInc, allowInc, silentIgnore };
165
+ }
166
+
167
+ type PSBTKeyMap = Record<string, PSBTKeyMapInfo>;
168
+
169
+ const PSBTUnknownKey = P.struct({ type: CompactSizeLen, key: P.bytes(null) });
170
+ type PSBTUnknownFields = { unknown?: [P.UnwrapCoder<typeof PSBTUnknownKey>, Bytes][] };
171
+ export type PSBTKeyMapKeys<T extends PSBTKeyMap> = {
172
+ -readonly [K in keyof T]?: T[K][1] extends false
173
+ ? P.UnwrapCoder<T[K][2]>
174
+ : [P.UnwrapCoder<T[K][1]>, P.UnwrapCoder<T[K][2]>][];
175
+ } & PSBTUnknownFields;
176
+ // Key cannot be 'unknown', value coder cannot be array for elements with empty key
177
+ function PSBTKeyMap<T extends PSBTKeyMap>(psbtEnum: T): P.CoderType<PSBTKeyMapKeys<T>> {
178
+ // -> Record<type, [keyName, ...coders]>
179
+ const byType: Record<number, [string, PSBTKeyCoder, P.CoderType<any>]> = {};
180
+ for (const k in psbtEnum) {
181
+ const [num, kc, vc] = psbtEnum[k];
182
+ byType[num] = [k, kc, vc];
183
+ }
184
+ return P.wrap({
185
+ encodeStream: (w: P.Writer, value: PSBTKeyMapKeys<T>) => {
186
+ let out: P.UnwrapCoder<typeof PSBTKeyPair> = [];
187
+ // Because we use order of psbtEnum, keymap is sorted here
188
+ for (const name in psbtEnum) {
189
+ const val = value[name];
190
+ if (val === undefined) continue;
191
+ const [type, kc, vc] = psbtEnum[name];
192
+ if (!kc) {
193
+ out.push({ key: { type, key: P.EMPTY }, value: vc.encode(val) });
194
+ } else {
195
+ // Low level interface, returns keys as is (with duplicates). Useful for debug
196
+ const kv: [Bytes, Bytes][] = val!.map(
197
+ ([k, v]: [P.UnwrapCoder<typeof kc>, P.UnwrapCoder<typeof vc>]) => [
198
+ kc.encode(k),
199
+ vc.encode(v),
200
+ ]
201
+ );
202
+ // sort by keys
203
+ kv.sort((a, b) => compareBytes(a[0], b[0]));
204
+ for (const [key, value] of kv) out.push({ key: { key, type }, value });
205
+ }
206
+ }
207
+ if (value.unknown) {
208
+ value.unknown.sort((a, b) => compareBytes(a[0].key, b[0].key));
209
+ for (const [k, v] of value.unknown) out.push({ key: k, value: v });
210
+ }
211
+ PSBTKeyPair.encodeStream(w, out);
212
+ },
213
+ decodeStream: (r: P.Reader): PSBTKeyMapKeys<T> => {
214
+ const raw = PSBTKeyPair.decodeStream(r);
215
+ const out: any = {};
216
+ const noKey: Record<string, true> = {};
217
+ for (const elm of raw) {
218
+ let name = 'unknown';
219
+ let key: any = elm.key.key;
220
+ let value = elm.value;
221
+ if (byType[elm.key.type]) {
222
+ const [_name, kc, vc] = byType[elm.key.type];
223
+ name = _name;
224
+ if (!kc && key.length) {
225
+ throw new Error(
226
+ `PSBT: Non-empty key for ${name} (key=${hex.encode(key)} value=${hex.encode(value)}`
227
+ );
228
+ }
229
+ key = kc ? kc.decode(key) : undefined;
230
+ value = vc.decode(value);
231
+ if (!kc) {
232
+ if (out[name]) throw new Error(`PSBT: Same keys: ${name} (key=${key} value=${value})`);
233
+ out[name] = value;
234
+ noKey[name] = true;
235
+ continue;
236
+ }
237
+ } else {
238
+ // For unknown: add key type inside key
239
+ key = { type: elm.key.type, key: elm.key.key };
240
+ }
241
+ // Only keyed elements at this point
242
+ if (noKey[name])
243
+ throw new Error(`PSBT: Key type with empty key and no key=${name} val=${value}`);
244
+ if (!out[name]) out[name] = [];
245
+ out[name].push([key, value]);
246
+ }
247
+ return out;
248
+ },
249
+ });
250
+ }
251
+
252
+ export const PSBTInputCoder = P.validate(PSBTKeyMap(PSBTInput), (i) => {
253
+ if (i.finalScriptWitness && !i.finalScriptWitness.length)
254
+ throw new Error('validateInput: wmpty finalScriptWitness');
255
+ //if (i.finalScriptSig && !i.finalScriptSig.length) throw new Error('validateInput: empty finalScriptSig');
256
+ if (i.partialSig && !i.partialSig.length) throw new Error('Empty partialSig');
257
+ if (i.partialSig) for (const [k] of i.partialSig) validatePubkey(k, PubT.ecdsa);
258
+ if (i.bip32Derivation) for (const [k] of i.bip32Derivation) validatePubkey(k, PubT.ecdsa);
259
+ // Locktime = unsigned little endian integer greater than or equal to 500000000 representing
260
+ if (i.requiredTimeLocktime !== undefined && i.requiredTimeLocktime < 500000000)
261
+ throw new Error(`validateInput: wrong timeLocktime=${i.requiredTimeLocktime}`);
262
+ // unsigned little endian integer greater than 0 and less than 500000000
263
+ if (
264
+ i.requiredHeightLocktime !== undefined &&
265
+ (i.requiredHeightLocktime <= 0 || i.requiredHeightLocktime >= 500000000)
266
+ )
267
+ throw new Error(`validateInput: wrong heighLocktime=${i.requiredHeightLocktime}`);
268
+
269
+ if (i.nonWitnessUtxo && i.index !== undefined) {
270
+ const last = i.nonWitnessUtxo.outputs.length - 1;
271
+ if (i.index > last) throw new Error(`validateInput: index(${i.index}) not in nonWitnessUtxo`);
272
+ const prevOut = i.nonWitnessUtxo.outputs[i.index];
273
+ if (
274
+ i.witnessUtxo &&
275
+ (!P.equalBytes(i.witnessUtxo.script, prevOut.script) ||
276
+ i.witnessUtxo.amount !== prevOut.amount)
277
+ )
278
+ throw new Error('validateInput: witnessUtxo different from nonWitnessUtxo');
279
+ }
280
+ if (i.tapLeafScript) {
281
+ // tap leaf version appears here twice: in control block and at the end of script
282
+ for (const [k, v] of i.tapLeafScript) {
283
+ if ((k.version & 0b1111_1110) !== v[v.length - 1])
284
+ throw new Error('validateInput: tapLeafScript version mimatch');
285
+ if (v[v.length - 1] & 1)
286
+ throw new Error('validateInput: tapLeafScript version has parity bit!');
287
+ }
288
+ }
289
+ // Validate txid for nonWitnessUtxo is correct
290
+ if (i.nonWitnessUtxo && i.index !== undefined && i.txid) {
291
+ const outputs = i.nonWitnessUtxo.outputs;
292
+ if (outputs.length - 1 < i.index) throw new Error('nonWitnessUtxo: incorect output index');
293
+ // At this point, we are using previous tx output to create new input.
294
+ // Script safety checks are unnecessary:
295
+ // - User has no control over previous tx. If somebody send money in same tx
296
+ // as unspendable output, we still want user able to spend money
297
+ // - We still want some checks to notify user about possible errors early
298
+ // in case user wants to use wrong input by mistake
299
+ // - Worst case: tx will be rejected by nodes. Still better than disallowing user
300
+ // to spend real input, no matter how broken it looks
301
+ const tx = Transaction.fromRaw(RawTx.encode(i.nonWitnessUtxo), {
302
+ allowUnknownOutputs: true,
303
+ disableScriptCheck: true,
304
+ allowUnknownInputs: true,
305
+ });
306
+ const txid = hex.encode(i.txid);
307
+ // PSBTv2 vectors have non-final tx in inputs
308
+ if (tx.isFinal && tx.id !== txid)
309
+ throw new Error(`nonWitnessUtxo: wrong txid, exp=${txid} got=${tx.id}`);
310
+ }
311
+ return i;
312
+ });
313
+
314
+ export type ExtendType<T, E> = {
315
+ [K in keyof T]: K extends keyof E ? E[K] | T[K] : T[K];
316
+ };
317
+ export type RequireType<T, K extends keyof T> = T & {
318
+ [P in K]-?: T[P];
319
+ };
320
+
321
+ export type TransactionInput = P.UnwrapCoder<typeof PSBTInputCoder>;
322
+ export type TransactionInputUpdate = ExtendType<
323
+ TransactionInput,
324
+ {
325
+ nonWitnessUtxo?: string | Bytes;
326
+ txid?: string;
327
+ }
328
+ >;
329
+
330
+ export const PSBTOutputCoder = P.validate(PSBTKeyMap(PSBTOutput), (o) => {
331
+ if (o.bip32Derivation) for (const [k] of o.bip32Derivation) validatePubkey(k, PubT.ecdsa);
332
+ return o;
333
+ });
334
+
335
+ export type TransactionOutput = P.UnwrapCoder<typeof PSBTOutputCoder>;
336
+ export type TransactionOutputUpdate = ExtendType<TransactionOutput, { script?: string }>;
337
+ export type TransactionOutputRequired = {
338
+ script: Bytes;
339
+ amount: bigint;
340
+ };
341
+
342
+ const PSBTGlobalCoder = P.validate(PSBTKeyMap(PSBTGlobal), (g) => {
343
+ const version = g.version || 0;
344
+ if (version === 0) {
345
+ if (!g.unsignedTx) throw new Error('PSBTv0: missing unsignedTx');
346
+ if (g.unsignedTx.segwitFlag || g.unsignedTx.witnesses)
347
+ throw new Error('PSBTv0: witness in unsingedTx');
348
+ for (const inp of g.unsignedTx.inputs)
349
+ if (inp.finalScriptSig && inp.finalScriptSig.length)
350
+ throw new Error('PSBTv0: input scriptSig found in unsignedTx');
351
+ }
352
+ return g;
353
+ });
354
+
355
+ export const _RawPSBTV0 = P.struct({
356
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
357
+ global: PSBTGlobalCoder,
358
+ inputs: P.array('global/unsignedTx/inputs/length', PSBTInputCoder),
359
+ outputs: P.array(null, PSBTOutputCoder),
360
+ });
361
+
362
+ export const _RawPSBTV2 = P.struct({
363
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
364
+ global: PSBTGlobalCoder,
365
+ inputs: P.array('global/inputCount', PSBTInputCoder),
366
+ outputs: P.array('global/outputCount', PSBTOutputCoder),
367
+ });
368
+
369
+ export type PSBTRaw = typeof _RawPSBTV0 | typeof _RawPSBTV2;
370
+
371
+ export const _DebugPSBT = P.struct({
372
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
373
+ items: P.array(
374
+ null,
375
+ P.apply(
376
+ P.array(P.NULL, P.tuple([P.hex(CompactSizeLen), P.bytes(CompactSize)])),
377
+ P.coders.dict()
378
+ )
379
+ ),
380
+ });
381
+
382
+ function validatePSBTFields<T extends PSBTKeyMap>(
383
+ version: number,
384
+ info: T,
385
+ lst: PSBTKeyMapKeys<T>
386
+ ) {
387
+ for (const k in lst) {
388
+ if (k === 'unknown') continue;
389
+ if (!info[k]) continue;
390
+ const { allowInc } = PSBTKeyInfo(info[k]);
391
+ if (!allowInc.includes(version)) throw new Error(`PSBTv${version}: field ${k} is not allowed`);
392
+ }
393
+ for (const k in info) {
394
+ const { reqInc } = PSBTKeyInfo(info[k]);
395
+ if (reqInc.includes(version) && lst[k] === undefined)
396
+ throw new Error(`PSBTv${version}: missing required field ${k}`);
397
+ }
398
+ }
399
+
400
+ export function cleanPSBTFields<T extends PSBTKeyMap>(
401
+ version: number,
402
+ info: T,
403
+ lst: PSBTKeyMapKeys<T>
404
+ ) {
405
+ const out: PSBTKeyMapKeys<T> = {};
406
+ for (const _k in lst) {
407
+ const k = _k as string & keyof PSBTKeyMapKeys<T>;
408
+ if (k !== 'unknown') {
409
+ if (!info[k]) continue;
410
+ const { allowInc, silentIgnore } = PSBTKeyInfo(info[k]);
411
+ if (!allowInc.includes(version)) {
412
+ if (silentIgnore) continue;
413
+ throw new Error(
414
+ `Failed to serialize in PSBTv${version}: ${k} but versions allows inclusion=${allowInc}`
415
+ );
416
+ }
417
+ }
418
+ out[k] = lst[k];
419
+ }
420
+ return out;
421
+ }
422
+
423
+ function validatePSBT(tx: P.UnwrapCoder<PSBTRaw>) {
424
+ const version = (tx && tx.global && tx.global.version) || 0;
425
+ validatePSBTFields(version, PSBTGlobal, tx.global);
426
+ for (const i of tx.inputs) validatePSBTFields(version, PSBTInput, i);
427
+ for (const o of tx.outputs) validatePSBTFields(version, PSBTOutput, o);
428
+ // We allow only one empty element at the end of map (compat with bitcoinjs-lib bug)
429
+ const inputCount = !version ? tx.global.unsignedTx!.inputs.length : tx.global.inputCount!;
430
+ if (tx.inputs.length < inputCount) throw new Error('Not enough inputs');
431
+ const inputsLeft = tx.inputs.slice(inputCount);
432
+ if (inputsLeft.length > 1 || (inputsLeft.length && Object.keys(inputsLeft[0]).length))
433
+ throw new Error(`Unexpected inputs left in tx=${inputsLeft}`);
434
+ // Same for inputs
435
+ const outputCount = !version ? tx.global.unsignedTx!.outputs.length : tx.global.outputCount!;
436
+ if (tx.outputs.length < outputCount) throw new Error('Not outputs inputs');
437
+ const outputsLeft = tx.outputs.slice(outputCount);
438
+ if (outputsLeft.length > 1 || (outputsLeft.length && Object.keys(outputsLeft[0]).length))
439
+ throw new Error(`Unexpected outputs left in tx=${outputsLeft}`);
440
+ return tx;
441
+ }
442
+
443
+ export function mergeKeyMap<T extends PSBTKeyMap>(
444
+ psbtEnum: T,
445
+ val: PSBTKeyMapKeys<T>,
446
+ cur?: PSBTKeyMapKeys<T>,
447
+ allowedFields?: (keyof PSBTKeyMapKeys<T>)[]
448
+ ): PSBTKeyMapKeys<T> {
449
+ const res: PSBTKeyMapKeys<T> = { ...cur, ...val };
450
+ // All arguments can be provided as hex
451
+ for (const k in psbtEnum) {
452
+ const key = k as keyof typeof psbtEnum;
453
+ const [_, kC, vC] = psbtEnum[key];
454
+ type _KV = [P.UnwrapCoder<typeof kC>, P.UnwrapCoder<typeof vC>];
455
+ const cannotChange = allowedFields && !allowedFields.includes(k);
456
+ if (val[k] === undefined && k in val) {
457
+ if (cannotChange) throw new Error(`Cannot remove signed field=${k}`);
458
+ delete res[k];
459
+ } else if (kC) {
460
+ const oldKV = (cur && cur[k] ? cur[k] : []) as _KV[];
461
+ let newKV = val[key] as _KV[];
462
+ if (newKV) {
463
+ if (!Array.isArray(newKV)) throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
464
+ // Decode hex in k-v
465
+ newKV = newKV.map((val: _KV): _KV => {
466
+ if (val.length !== 2) throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
467
+ return [
468
+ typeof val[0] === 'string' ? kC.decode(hex.decode(val[0])) : val[0],
469
+ typeof val[1] === 'string' ? vC.decode(hex.decode(val[1])) : val[1],
470
+ ];
471
+ });
472
+ const map: Record<string, _KV> = {};
473
+ const add = (kStr: string, k: _KV[0], v: _KV[1]) => {
474
+ if (map[kStr] === undefined) {
475
+ map[kStr] = [k, v];
476
+ return;
477
+ }
478
+ const oldVal = hex.encode(vC.encode(map[kStr][1]));
479
+ const newVal = hex.encode(vC.encode(v));
480
+ if (oldVal !== newVal)
481
+ throw new Error(
482
+ `keyMap(${key as string}): same key=${kStr} oldVal=${oldVal} newVal=${newVal}`
483
+ );
484
+ };
485
+ for (const [k, v] of oldKV) {
486
+ const kStr = hex.encode(kC.encode(k));
487
+ add(kStr, k, v);
488
+ }
489
+ for (const [k, v] of newKV) {
490
+ const kStr = hex.encode(kC.encode(k));
491
+ // undefined removes previous value
492
+ if (v === undefined) {
493
+ if (cannotChange) throw new Error(`Cannot remove signed field=${key as string}/${k}`);
494
+ delete map[kStr];
495
+ } else add(kStr, k, v);
496
+ }
497
+ (res as any)[key] = Object.values(map) as _KV[];
498
+ }
499
+ } else if (typeof res[k] === 'string') {
500
+ res[k] = vC.decode(hex.decode(res[k] as string));
501
+ } else if (cannotChange && k in val && cur && cur[k] !== undefined) {
502
+ if (!P.equalBytes(vC.encode(val[k]), vC.encode(cur[k])))
503
+ throw new Error(`Cannot change signed field=${k}`);
504
+ }
505
+ }
506
+ // Remove unknown keys
507
+ for (const k in res) if (!psbtEnum[k]) delete res[k];
508
+ return res;
509
+ }
510
+
511
+ export const RawPSBTV0 = P.validate(_RawPSBTV0, validatePSBT);
512
+ export const RawPSBTV2 = P.validate(_RawPSBTV2, validatePSBT);