@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
@@ -0,0 +1,1013 @@
1
+ import * as P from 'micro-packed';
2
+ import { hex } from '@scure/base';
3
+ import { Address, OutScript, checkScript, tapLeafHash } from './payment.js';
4
+ import * as psbt from './psbt.js'; // circular
5
+ import { CompactSizeLen, RawOutput, RawTx, RawWitness, Script, VarBytes } from './script.js';
6
+ import { NETWORK, concatBytes, isBytes } from './utils.js';
7
+ import * as u from './utils.js';
8
+ import { getInputType, toVsize, normalizeInput, getPrevOut } from './utxo.js'; // circular
9
+ const EMPTY32 = new Uint8Array(32);
10
+ const EMPTY_OUTPUT = {
11
+ amount: 0xffffffffffffffffn,
12
+ script: P.EMPTY,
13
+ };
14
+ export const PRECISION = 8;
15
+ export const DEFAULT_VERSION = 2;
16
+ export const DEFAULT_LOCKTIME = 0;
17
+ export const DEFAULT_SEQUENCE = 4294967295;
18
+ export const Decimal = P.coders.decimal(PRECISION);
19
+ // Same as value || def, but doesn't overwrites zero ('0', 0, 0n, etc)
20
+ export const def = (value, def) => (value === undefined ? def : value);
21
+ export function cloneDeep(obj) {
22
+ if (Array.isArray(obj))
23
+ return obj.map((i) => cloneDeep(i));
24
+ // slice of nodejs Buffer doesn't copy
25
+ else if (obj instanceof Uint8Array)
26
+ return Uint8Array.from(obj);
27
+ // immutable
28
+ else if (['number', 'bigint', 'boolean', 'string', 'undefined'].includes(typeof obj))
29
+ return obj;
30
+ // null is object
31
+ else if (obj === null)
32
+ return obj;
33
+ // should be last, so it won't catch other types
34
+ else if (typeof obj === 'object') {
35
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, cloneDeep(v)]));
36
+ }
37
+ throw new Error(`cloneDeep: unknown type=${obj} (${typeof obj})`);
38
+ }
39
+ /**
40
+ * Internal, exported only for backwards-compat. Use `SigHash` instead.
41
+ * @deprecated
42
+ */
43
+ export var SignatureHash;
44
+ (function (SignatureHash) {
45
+ SignatureHash[SignatureHash["DEFAULT"] = 0] = "DEFAULT";
46
+ SignatureHash[SignatureHash["ALL"] = 1] = "ALL";
47
+ SignatureHash[SignatureHash["NONE"] = 2] = "NONE";
48
+ SignatureHash[SignatureHash["SINGLE"] = 3] = "SINGLE";
49
+ SignatureHash[SignatureHash["ANYONECANPAY"] = 128] = "ANYONECANPAY";
50
+ })(SignatureHash || (SignatureHash = {}));
51
+ export var SigHash;
52
+ (function (SigHash) {
53
+ SigHash[SigHash["DEFAULT"] = 0] = "DEFAULT";
54
+ SigHash[SigHash["ALL"] = 1] = "ALL";
55
+ SigHash[SigHash["NONE"] = 2] = "NONE";
56
+ SigHash[SigHash["SINGLE"] = 3] = "SINGLE";
57
+ SigHash[SigHash["DEFAULT_ANYONECANPAY"] = 128] = "DEFAULT_ANYONECANPAY";
58
+ SigHash[SigHash["ALL_ANYONECANPAY"] = 129] = "ALL_ANYONECANPAY";
59
+ SigHash[SigHash["NONE_ANYONECANPAY"] = 130] = "NONE_ANYONECANPAY";
60
+ SigHash[SigHash["SINGLE_ANYONECANPAY"] = 131] = "SINGLE_ANYONECANPAY";
61
+ })(SigHash || (SigHash = {}));
62
+ function getTaprootKeys(privKey, pubKey, internalKey, merkleRoot = P.EMPTY) {
63
+ if (P.equalBytes(internalKey, pubKey)) {
64
+ privKey = u.taprootTweakPrivKey(privKey, merkleRoot);
65
+ pubKey = u.pubSchnorr(privKey);
66
+ }
67
+ return { privKey, pubKey };
68
+ }
69
+ // Force check amount/script
70
+ function outputBeforeSign(i) {
71
+ if (i.script === undefined || i.amount === undefined)
72
+ throw new Error('Transaction/output: script and amount required');
73
+ return { script: i.script, amount: i.amount };
74
+ }
75
+ // Force check index/txid/sequence
76
+ export function inputBeforeSign(i) {
77
+ if (i.txid === undefined || i.index === undefined)
78
+ throw new Error('Transaction/input: txid and index required');
79
+ return {
80
+ txid: i.txid,
81
+ index: i.index,
82
+ sequence: def(i.sequence, DEFAULT_SEQUENCE),
83
+ finalScriptSig: def(i.finalScriptSig, P.EMPTY),
84
+ };
85
+ }
86
+ function cleanFinalInput(i) {
87
+ for (const _k in i) {
88
+ const k = _k;
89
+ if (!psbt.PSBTInputFinalKeys.includes(k))
90
+ delete i[k];
91
+ }
92
+ }
93
+ // (TxHash, Idx)
94
+ const TxHashIdx = P.struct({ txid: P.bytes(32, true), index: P.U32LE });
95
+ function validateSigHash(s) {
96
+ if (typeof s !== 'number' || typeof SigHash[s] !== 'string')
97
+ throw new Error(`Invalid SigHash=${s}`);
98
+ return s;
99
+ }
100
+ function unpackSighash(hashType) {
101
+ const masked = hashType & 0b0011111;
102
+ return {
103
+ isAny: !!(hashType & SignatureHash.ANYONECANPAY),
104
+ isNone: masked === SignatureHash.NONE,
105
+ isSingle: masked === SignatureHash.SINGLE,
106
+ };
107
+ }
108
+ function validateOpts(opts) {
109
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
110
+ throw new Error(`Wrong object type for transaction options: ${opts}`);
111
+ const _opts = {
112
+ ...opts,
113
+ // Defaults
114
+ version: def(opts.version, DEFAULT_VERSION),
115
+ lockTime: def(opts.lockTime, 0),
116
+ PSBTVersion: def(opts.PSBTVersion, 0),
117
+ };
118
+ if (typeof _opts.allowUnknowInput !== 'undefined')
119
+ opts.allowUnknownInputs = _opts.allowUnknowInput;
120
+ if (typeof _opts.allowUnknowOutput !== 'undefined')
121
+ opts.allowUnknownOutputs = _opts.allowUnknowOutput;
122
+ // 0 and -1 happens in tests
123
+ if (![-1, 0, 1, 2].includes(_opts.version))
124
+ throw new Error(`Unknown version: ${_opts.version}`);
125
+ if (typeof _opts.lockTime !== 'number')
126
+ throw new Error('Transaction lock time should be number');
127
+ P.U32LE.encode(_opts.lockTime); // Additional range checks that lockTime
128
+ // There is no PSBT v1, and any new version will probably have fields which we don't know how to parse, which
129
+ // can lead to constructing broken transactions
130
+ if (_opts.PSBTVersion !== 0 && _opts.PSBTVersion !== 2)
131
+ throw new Error(`Unknown PSBT version ${_opts.PSBTVersion}`);
132
+ // Flags
133
+ for (const k of [
134
+ 'allowUnknownOutputs',
135
+ 'allowUnknownInputs',
136
+ 'disableScriptCheck',
137
+ 'bip174jsCompat',
138
+ 'allowLegacyWitnessUtxo',
139
+ 'lowR',
140
+ ]) {
141
+ const v = _opts[k];
142
+ if (v === undefined)
143
+ continue; // optional
144
+ if (typeof v !== 'boolean')
145
+ throw new Error(`Transation options wrong type: ${k}=${v} (${typeof v})`);
146
+ }
147
+ if (_opts.customScripts !== undefined) {
148
+ const cs = _opts.customScripts;
149
+ if (!Array.isArray(cs)) {
150
+ throw new Error(`wrong custom scripts type (expected array): customScripts=${cs} (${typeof cs})`);
151
+ }
152
+ for (const s of cs) {
153
+ if (typeof s.encode !== 'function' || typeof s.decode !== 'function')
154
+ throw new Error(`wrong script=${s} (${typeof s})`);
155
+ if (s.finalizeTaproot !== undefined && typeof s.finalizeTaproot !== 'function')
156
+ throw new Error(`wrong script=${s} (${typeof s})`);
157
+ }
158
+ }
159
+ return Object.freeze(_opts);
160
+ }
161
+ export class Transaction {
162
+ constructor(opts = {}) {
163
+ this.global = {};
164
+ this.inputs = []; // use getInput()
165
+ this.outputs = []; // use getOutput()
166
+ const _opts = (this.opts = validateOpts(opts));
167
+ // Merge with global structure of PSBTv2
168
+ if (_opts.lockTime !== DEFAULT_LOCKTIME)
169
+ this.global.fallbackLocktime = _opts.lockTime;
170
+ this.global.txVersion = _opts.version;
171
+ }
172
+ // Import
173
+ static fromRaw(raw, opts = {}) {
174
+ const parsed = RawTx.decode(raw);
175
+ const tx = new Transaction({ ...opts, version: parsed.version, lockTime: parsed.lockTime });
176
+ for (const o of parsed.outputs)
177
+ tx.addOutput(o);
178
+ tx.outputs = parsed.outputs;
179
+ tx.inputs = parsed.inputs;
180
+ if (parsed.witnesses) {
181
+ for (let i = 0; i < parsed.witnesses.length; i++)
182
+ tx.inputs[i].finalScriptWitness = parsed.witnesses[i];
183
+ }
184
+ return tx;
185
+ }
186
+ // PSBT
187
+ static fromPSBT(psbt_, opts = {}) {
188
+ let parsed;
189
+ try {
190
+ parsed = psbt.RawPSBTV0.decode(psbt_);
191
+ }
192
+ catch (e0) {
193
+ try {
194
+ parsed = psbt.RawPSBTV2.decode(psbt_);
195
+ }
196
+ catch (e2) {
197
+ // Throw error for v0 parsing, since it popular, otherwise it would be shadowed by v2 error
198
+ throw e0;
199
+ }
200
+ }
201
+ const PSBTVersion = parsed.global.version || 0;
202
+ if (PSBTVersion !== 0 && PSBTVersion !== 2)
203
+ throw new Error(`Wrong PSBT version=${PSBTVersion}`);
204
+ const unsigned = parsed.global.unsignedTx;
205
+ const version = PSBTVersion === 0 ? unsigned?.version : parsed.global.txVersion;
206
+ const lockTime = PSBTVersion === 0 ? unsigned?.lockTime : parsed.global.fallbackLocktime;
207
+ const tx = new Transaction({ ...opts, version, lockTime, PSBTVersion });
208
+ // We need slice here, because otherwise
209
+ const inputCount = PSBTVersion === 0 ? unsigned?.inputs.length : parsed.global.inputCount;
210
+ tx.inputs = parsed.inputs.slice(0, inputCount).map((i, j) => ({
211
+ finalScriptSig: P.EMPTY,
212
+ ...parsed.global.unsignedTx?.inputs[j],
213
+ ...i,
214
+ }));
215
+ const outputCount = PSBTVersion === 0 ? unsigned?.outputs.length : parsed.global.outputCount;
216
+ tx.outputs = parsed.outputs.slice(0, outputCount).map((i, j) => ({
217
+ ...i,
218
+ ...parsed.global.unsignedTx?.outputs[j],
219
+ }));
220
+ tx.global = { ...parsed.global, txVersion: version }; // just in case proprietary/unknown fields
221
+ if (lockTime !== DEFAULT_LOCKTIME)
222
+ tx.global.fallbackLocktime = lockTime;
223
+ return tx;
224
+ }
225
+ toPSBT(PSBTVersion = this.opts.PSBTVersion) {
226
+ if (PSBTVersion !== 0 && PSBTVersion !== 2)
227
+ throw new Error(`Wrong PSBT version=${PSBTVersion}`);
228
+ const inputs = this.inputs.map((i) => psbt.cleanPSBTFields(PSBTVersion, psbt.PSBTInput, i));
229
+ for (const inp of inputs) {
230
+ // Don't serialize empty fields
231
+ if (inp.partialSig && !inp.partialSig.length)
232
+ delete inp.partialSig;
233
+ if (inp.finalScriptSig && !inp.finalScriptSig.length)
234
+ delete inp.finalScriptSig;
235
+ if (inp.finalScriptWitness && !inp.finalScriptWitness.length)
236
+ delete inp.finalScriptWitness;
237
+ }
238
+ const outputs = this.outputs.map((i) => psbt.cleanPSBTFields(PSBTVersion, psbt.PSBTOutput, i));
239
+ const global = { ...this.global };
240
+ if (PSBTVersion === 0) {
241
+ global.unsignedTx = RawTx.decode(this.unsignedTx);
242
+ delete global.fallbackLocktime;
243
+ delete global.txVersion;
244
+ }
245
+ else {
246
+ global.version = PSBTVersion;
247
+ global.txVersion = this.version;
248
+ global.inputCount = this.inputs.length;
249
+ global.outputCount = this.outputs.length;
250
+ if (global.fallbackLocktime && global.fallbackLocktime === DEFAULT_LOCKTIME)
251
+ delete global.fallbackLocktime;
252
+ }
253
+ if (this.opts.bip174jsCompat) {
254
+ if (!inputs.length)
255
+ inputs.push({});
256
+ if (!outputs.length)
257
+ outputs.push({});
258
+ }
259
+ return (PSBTVersion === 0 ? psbt.RawPSBTV0 : psbt.RawPSBTV2).encode({
260
+ global,
261
+ inputs,
262
+ outputs,
263
+ });
264
+ }
265
+ // BIP370 lockTime (https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#determining-lock-time)
266
+ get lockTime() {
267
+ let height = DEFAULT_LOCKTIME;
268
+ let heightCnt = 0;
269
+ let time = DEFAULT_LOCKTIME;
270
+ let timeCnt = 0;
271
+ for (const i of this.inputs) {
272
+ if (i.requiredHeightLocktime) {
273
+ height = Math.max(height, i.requiredHeightLocktime);
274
+ heightCnt++;
275
+ }
276
+ if (i.requiredTimeLocktime) {
277
+ time = Math.max(time, i.requiredTimeLocktime);
278
+ timeCnt++;
279
+ }
280
+ }
281
+ if (heightCnt && heightCnt >= timeCnt)
282
+ return height;
283
+ if (time !== DEFAULT_LOCKTIME)
284
+ return time;
285
+ return this.global.fallbackLocktime || DEFAULT_LOCKTIME;
286
+ }
287
+ get version() {
288
+ // Should be not possible
289
+ if (this.global.txVersion === undefined)
290
+ throw new Error('No global.txVersion');
291
+ return this.global.txVersion;
292
+ }
293
+ inputStatus(idx) {
294
+ this.checkInputIdx(idx);
295
+ const input = this.inputs[idx];
296
+ // Finalized
297
+ if (input.finalScriptSig && input.finalScriptSig.length)
298
+ return 'finalized';
299
+ if (input.finalScriptWitness && input.finalScriptWitness.length)
300
+ return 'finalized';
301
+ // Signed taproot
302
+ if (input.tapKeySig)
303
+ return 'signed';
304
+ if (input.tapScriptSig && input.tapScriptSig.length)
305
+ return 'signed';
306
+ // Signed
307
+ if (input.partialSig && input.partialSig.length)
308
+ return 'signed';
309
+ return 'unsigned';
310
+ }
311
+ // Cannot replace unpackSighash, tests rely on very generic implemenetation with signing inputs outside of range
312
+ // We will lose some vectors -> smaller test coverage of preimages (very important!)
313
+ inputSighash(idx) {
314
+ this.checkInputIdx(idx);
315
+ const sighash = getInputType(this.inputs[idx], this.opts.allowLegacyWitnessUtxo).sighash;
316
+ // ALL or DEFAULT -- everything signed
317
+ // NONE -- all inputs + no outputs
318
+ // SINGLE -- all inputs + output with same index
319
+ // ALL + ANYONE -- specific input + all outputs
320
+ // NONE + ANYONE -- specific input + no outputs
321
+ // SINGLE -- specific inputs + output with same index
322
+ const sigOutputs = sighash === SignatureHash.DEFAULT ? SignatureHash.ALL : sighash & 0b11;
323
+ const sigInputs = sighash & SignatureHash.ANYONECANPAY;
324
+ return { sigInputs, sigOutputs };
325
+ }
326
+ // Very nice for debug purposes, but slow. If there is too much inputs/outputs to add, will be quadratic.
327
+ // Some cache will be nice, but there chance to have bugs with cache invalidation
328
+ signStatus() {
329
+ // if addInput or addOutput is not possible, then all inputs or outputs are signed
330
+ let addInput = true, addOutput = true;
331
+ let inputs = [], outputs = [];
332
+ for (let idx = 0; idx < this.inputs.length; idx++) {
333
+ const status = this.inputStatus(idx);
334
+ // Unsigned input doesn't affect anything
335
+ if (status === 'unsigned')
336
+ continue;
337
+ const { sigInputs, sigOutputs } = this.inputSighash(idx);
338
+ // Input type
339
+ if (sigInputs === SignatureHash.ANYONECANPAY)
340
+ inputs.push(idx);
341
+ else
342
+ addInput = false;
343
+ // Output type
344
+ if (sigOutputs === SignatureHash.ALL)
345
+ addOutput = false;
346
+ else if (sigOutputs === SignatureHash.SINGLE)
347
+ outputs.push(idx);
348
+ else if (sigOutputs === SignatureHash.NONE) {
349
+ // Doesn't affect any outputs at all
350
+ }
351
+ else
352
+ throw new Error(`Wrong signature hash output type: ${sigOutputs}`);
353
+ }
354
+ return { addInput, addOutput, inputs, outputs };
355
+ }
356
+ get isFinal() {
357
+ for (let idx = 0; idx < this.inputs.length; idx++)
358
+ if (this.inputStatus(idx) !== 'finalized')
359
+ return false;
360
+ return true;
361
+ }
362
+ // Info utils
363
+ get hasWitnesses() {
364
+ let out = false;
365
+ for (const i of this.inputs)
366
+ if (i.finalScriptWitness && i.finalScriptWitness.length)
367
+ out = true;
368
+ return out;
369
+ }
370
+ // https://en.bitcoin.it/wiki/Weight_units
371
+ get weight() {
372
+ if (!this.isFinal)
373
+ throw new Error('Transaction is not finalized');
374
+ let out = 32;
375
+ // Outputs
376
+ const outputs = this.outputs.map(outputBeforeSign);
377
+ out += 4 * CompactSizeLen.encode(this.outputs.length).length;
378
+ for (const o of outputs)
379
+ out += 32 + 4 * VarBytes.encode(o.script).length;
380
+ // Inputs
381
+ if (this.hasWitnesses)
382
+ out += 2;
383
+ out += 4 * CompactSizeLen.encode(this.inputs.length).length;
384
+ for (const i of this.inputs) {
385
+ out += 160 + 4 * VarBytes.encode(i.finalScriptSig || P.EMPTY).length;
386
+ if (this.hasWitnesses && i.finalScriptWitness)
387
+ out += RawWitness.encode(i.finalScriptWitness).length;
388
+ }
389
+ return out;
390
+ }
391
+ get vsize() {
392
+ return toVsize(this.weight);
393
+ }
394
+ toBytes(withScriptSig = false, withWitness = false) {
395
+ return RawTx.encode({
396
+ version: this.version,
397
+ lockTime: this.lockTime,
398
+ inputs: this.inputs.map(inputBeforeSign).map((i) => ({
399
+ ...i,
400
+ finalScriptSig: (withScriptSig && i.finalScriptSig) || P.EMPTY,
401
+ })),
402
+ outputs: this.outputs.map(outputBeforeSign),
403
+ witnesses: this.inputs.map((i) => i.finalScriptWitness || []),
404
+ segwitFlag: withWitness && this.hasWitnesses,
405
+ });
406
+ }
407
+ get unsignedTx() {
408
+ return this.toBytes(false, false);
409
+ }
410
+ get hex() {
411
+ return hex.encode(this.toBytes(true, this.hasWitnesses));
412
+ }
413
+ get hash() {
414
+ if (!this.isFinal)
415
+ throw new Error('Transaction is not finalized');
416
+ return hex.encode(u.sha256x2(this.toBytes(true)));
417
+ }
418
+ get id() {
419
+ if (!this.isFinal)
420
+ throw new Error('Transaction is not finalized');
421
+ return hex.encode(u.sha256x2(this.toBytes(true)).reverse());
422
+ }
423
+ // Input stuff
424
+ checkInputIdx(idx) {
425
+ if (!Number.isSafeInteger(idx) || 0 > idx || idx >= this.inputs.length)
426
+ throw new Error(`Wrong input index=${idx}`);
427
+ }
428
+ getInput(idx) {
429
+ this.checkInputIdx(idx);
430
+ return cloneDeep(this.inputs[idx]);
431
+ }
432
+ get inputsLength() {
433
+ return this.inputs.length;
434
+ }
435
+ // Modification
436
+ addInput(input, _ignoreSignStatus = false) {
437
+ if (!_ignoreSignStatus && !this.signStatus().addInput)
438
+ throw new Error('Tx has signed inputs, cannot add new one');
439
+ this.inputs.push(normalizeInput(input, undefined, undefined, this.opts.disableScriptCheck));
440
+ return this.inputs.length - 1;
441
+ }
442
+ updateInput(idx, input, _ignoreSignStatus = false) {
443
+ this.checkInputIdx(idx);
444
+ let allowedFields = undefined;
445
+ if (!_ignoreSignStatus) {
446
+ const status = this.signStatus();
447
+ if (!status.addInput || status.inputs.includes(idx))
448
+ allowedFields = psbt.PSBTInputUnsignedKeys;
449
+ }
450
+ this.inputs[idx] = normalizeInput(input, this.inputs[idx], allowedFields, this.opts.disableScriptCheck);
451
+ }
452
+ // Output stuff
453
+ checkOutputIdx(idx) {
454
+ if (!Number.isSafeInteger(idx) || 0 > idx || idx >= this.outputs.length)
455
+ throw new Error(`Wrong output index=${idx}`);
456
+ }
457
+ getOutput(idx) {
458
+ this.checkOutputIdx(idx);
459
+ return cloneDeep(this.outputs[idx]);
460
+ }
461
+ get outputsLength() {
462
+ return this.outputs.length;
463
+ }
464
+ normalizeOutput(o, cur, allowedFields) {
465
+ let { amount, script } = o;
466
+ if (amount === undefined)
467
+ amount = cur?.amount;
468
+ if (typeof amount !== 'bigint')
469
+ throw new Error('amount must be bigint sats');
470
+ if (typeof script === 'string')
471
+ script = hex.decode(script);
472
+ if (script === undefined)
473
+ script = cur?.script;
474
+ let res = { ...cur, ...o, amount, script };
475
+ if (res.amount === undefined)
476
+ delete res.amount;
477
+ res = psbt.mergeKeyMap(psbt.PSBTOutput, res, cur, allowedFields);
478
+ psbt.PSBTOutputCoder.encode(res);
479
+ if (res.script &&
480
+ !this.opts.allowUnknownOutputs &&
481
+ OutScript.decode(res.script).type === 'unknown') {
482
+ throw new Error('Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure');
483
+ }
484
+ if (!this.opts.disableScriptCheck)
485
+ checkScript(res.script, res.redeemScript, res.witnessScript);
486
+ return res;
487
+ }
488
+ addOutput(o, _ignoreSignStatus = false) {
489
+ if (!_ignoreSignStatus && !this.signStatus().addOutput)
490
+ throw new Error('Tx has signed outputs, cannot add new one');
491
+ this.outputs.push(this.normalizeOutput(o));
492
+ return this.outputs.length - 1;
493
+ }
494
+ updateOutput(idx, output, _ignoreSignStatus = false) {
495
+ this.checkOutputIdx(idx);
496
+ let allowedFields = undefined;
497
+ if (!_ignoreSignStatus) {
498
+ const status = this.signStatus();
499
+ if (!status.addOutput || status.outputs.includes(idx))
500
+ allowedFields = psbt.PSBTOutputUnsignedKeys;
501
+ }
502
+ this.outputs[idx] = this.normalizeOutput(output, this.outputs[idx], allowedFields);
503
+ }
504
+ addOutputAddress(address, amount, network = NETWORK) {
505
+ return this.addOutput({ script: OutScript.encode(Address(network).decode(address)), amount });
506
+ }
507
+ // Utils
508
+ get fee() {
509
+ let res = 0n;
510
+ for (const i of this.inputs) {
511
+ const prevOut = getPrevOut(i);
512
+ if (!prevOut)
513
+ throw new Error('Empty input amount');
514
+ res += prevOut.amount;
515
+ }
516
+ const outputs = this.outputs.map(outputBeforeSign);
517
+ for (const o of outputs)
518
+ res -= o.amount;
519
+ return res;
520
+ }
521
+ // Signing
522
+ // Based on https://github.com/bitcoin/bitcoin/blob/5871b5b5ab57a0caf9b7514eb162c491c83281d5/test/functional/test_framework/script.py#L624
523
+ // There is optimization opportunity to re-use hashes for multiple inputs for witness v0/v1,
524
+ // but we are trying to be less complicated for audit purpose for now.
525
+ preimageLegacy(idx, prevOutScript, hashType) {
526
+ const { isAny, isNone, isSingle } = unpackSighash(hashType);
527
+ if (idx < 0 || !Number.isSafeInteger(idx))
528
+ throw new Error(`Invalid input idx=${idx}`);
529
+ if ((isSingle && idx >= this.outputs.length) || idx >= this.inputs.length)
530
+ return P.U256BE.encode(1n);
531
+ prevOutScript = Script.encode(Script.decode(prevOutScript).filter((i) => i !== 'CODESEPARATOR'));
532
+ let inputs = this.inputs
533
+ .map(inputBeforeSign)
534
+ .map((input, inputIdx) => ({
535
+ ...input,
536
+ finalScriptSig: inputIdx === idx ? prevOutScript : P.EMPTY,
537
+ }));
538
+ if (isAny)
539
+ inputs = [inputs[idx]];
540
+ else if (isNone || isSingle) {
541
+ inputs = inputs.map((input, inputIdx) => ({
542
+ ...input,
543
+ sequence: inputIdx === idx ? input.sequence : 0,
544
+ }));
545
+ }
546
+ let outputs = this.outputs.map(outputBeforeSign);
547
+ if (isNone)
548
+ outputs = [];
549
+ else if (isSingle) {
550
+ outputs = outputs.slice(0, idx).fill(EMPTY_OUTPUT).concat([outputs[idx]]);
551
+ }
552
+ const tmpTx = RawTx.encode({
553
+ lockTime: this.lockTime,
554
+ version: this.version,
555
+ segwitFlag: false,
556
+ inputs,
557
+ outputs,
558
+ });
559
+ return u.sha256x2(tmpTx, P.I32LE.encode(hashType));
560
+ }
561
+ preimageWitnessV0(idx, prevOutScript, hashType, amount) {
562
+ const { isAny, isNone, isSingle } = unpackSighash(hashType);
563
+ let inputHash = EMPTY32;
564
+ let sequenceHash = EMPTY32;
565
+ let outputHash = EMPTY32;
566
+ const inputs = this.inputs.map(inputBeforeSign);
567
+ const outputs = this.outputs.map(outputBeforeSign);
568
+ if (!isAny)
569
+ inputHash = u.sha256x2(...inputs.map(TxHashIdx.encode));
570
+ if (!isAny && !isSingle && !isNone)
571
+ sequenceHash = u.sha256x2(...inputs.map((i) => P.U32LE.encode(i.sequence)));
572
+ if (!isSingle && !isNone) {
573
+ outputHash = u.sha256x2(...outputs.map(RawOutput.encode));
574
+ }
575
+ else if (isSingle && idx < outputs.length)
576
+ outputHash = u.sha256x2(RawOutput.encode(outputs[idx]));
577
+ const input = inputs[idx];
578
+ return u.sha256x2(P.I32LE.encode(this.version), inputHash, sequenceHash, P.bytes(32, true).encode(input.txid), P.U32LE.encode(input.index), VarBytes.encode(prevOutScript), P.U64LE.encode(amount), P.U32LE.encode(input.sequence), outputHash, P.U32LE.encode(this.lockTime), P.U32LE.encode(hashType));
579
+ }
580
+ preimageWitnessV1(idx, prevOutScript, hashType, amount, codeSeparator = -1, leafScript, leafVer = 0xc0, annex) {
581
+ if (!Array.isArray(amount) || this.inputs.length !== amount.length)
582
+ throw new Error(`Invalid amounts array=${amount}`);
583
+ if (!Array.isArray(prevOutScript) || this.inputs.length !== prevOutScript.length)
584
+ throw new Error(`Invalid prevOutScript array=${prevOutScript}`);
585
+ const out = [
586
+ P.U8.encode(0),
587
+ P.U8.encode(hashType), // U8 sigHash
588
+ P.I32LE.encode(this.version),
589
+ P.U32LE.encode(this.lockTime),
590
+ ];
591
+ const outType = hashType === SignatureHash.DEFAULT ? SignatureHash.ALL : hashType & 0b11;
592
+ const inType = hashType & SignatureHash.ANYONECANPAY;
593
+ const inputs = this.inputs.map(inputBeforeSign);
594
+ const outputs = this.outputs.map(outputBeforeSign);
595
+ if (inType !== SignatureHash.ANYONECANPAY) {
596
+ out.push(...[
597
+ inputs.map(TxHashIdx.encode),
598
+ amount.map(P.U64LE.encode),
599
+ prevOutScript.map(VarBytes.encode),
600
+ inputs.map((i) => P.U32LE.encode(i.sequence)),
601
+ ].map((i) => u.sha256(concatBytes(...i))));
602
+ }
603
+ if (outType === SignatureHash.ALL) {
604
+ out.push(u.sha256(concatBytes(...outputs.map(RawOutput.encode))));
605
+ }
606
+ const spendType = (annex ? 1 : 0) | (leafScript ? 2 : 0);
607
+ out.push(new Uint8Array([spendType]));
608
+ if (inType === SignatureHash.ANYONECANPAY) {
609
+ const inp = inputs[idx];
610
+ out.push(TxHashIdx.encode(inp), P.U64LE.encode(amount[idx]), VarBytes.encode(prevOutScript[idx]), P.U32LE.encode(inp.sequence));
611
+ }
612
+ else
613
+ out.push(P.U32LE.encode(idx));
614
+ if (spendType & 1)
615
+ out.push(u.sha256(VarBytes.encode(annex || P.EMPTY)));
616
+ if (outType === SignatureHash.SINGLE)
617
+ out.push(idx < outputs.length ? u.sha256(RawOutput.encode(outputs[idx])) : EMPTY32);
618
+ if (leafScript)
619
+ out.push(tapLeafHash(leafScript, leafVer), P.U8.encode(0), P.I32LE.encode(codeSeparator));
620
+ return u.tagSchnorr('TapSighash', ...out);
621
+ }
622
+ // Signer can be privateKey OR instance of bip32 HD stuff
623
+ signIdx(privateKey, idx, allowedSighash, _auxRand) {
624
+ this.checkInputIdx(idx);
625
+ const input = this.inputs[idx];
626
+ const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);
627
+ // Handle BIP32 HDKey
628
+ if (!isBytes(privateKey)) {
629
+ if (!input.bip32Derivation || !input.bip32Derivation.length)
630
+ throw new Error('bip32Derivation: empty');
631
+ const signers = input.bip32Derivation
632
+ .filter((i) => i[1].fingerprint == privateKey.fingerprint)
633
+ .map(([pubKey, { path }]) => {
634
+ let s = privateKey;
635
+ for (const i of path)
636
+ s = s.deriveChild(i);
637
+ if (!P.equalBytes(s.publicKey, pubKey))
638
+ throw new Error('bip32Derivation: wrong pubKey');
639
+ if (!s.privateKey)
640
+ throw new Error('bip32Derivation: no privateKey');
641
+ return s;
642
+ });
643
+ if (!signers.length)
644
+ throw new Error(`bip32Derivation: no items with fingerprint=${privateKey.fingerprint}`);
645
+ let signed = false;
646
+ for (const s of signers)
647
+ if (this.signIdx(s.privateKey, idx))
648
+ signed = true;
649
+ return signed;
650
+ }
651
+ // Sighash checks
652
+ // Just for compat with bitcoinjs-lib, so users won't face unexpected behaviour.
653
+ if (!allowedSighash)
654
+ allowedSighash = [inputType.defaultSighash];
655
+ else
656
+ allowedSighash.forEach(validateSigHash);
657
+ const sighash = inputType.sighash;
658
+ if (!allowedSighash.includes(sighash)) {
659
+ throw new Error(`Input with not allowed sigHash=${sighash}. Allowed: ${allowedSighash.join(', ')}`);
660
+ }
661
+ // It is possible to sign these inputs for legacy/segwit v0 (but no taproot!),
662
+ // however this was because of bug in bitcoin-core, which remains here because of consensus.
663
+ // If this is absolutely neccessary for your case, please open issue.
664
+ // We disable it to avoid complicated workflow where SINGLE will block adding new outputs
665
+ const { sigOutputs } = this.inputSighash(idx);
666
+ if (sigOutputs === SignatureHash.SINGLE && idx >= this.outputs.length) {
667
+ throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${idx}`);
668
+ }
669
+ // Actual signing
670
+ // Taproot
671
+ const prevOut = getPrevOut(input);
672
+ if (inputType.txType === 'taproot') {
673
+ if (input.tapBip32Derivation)
674
+ throw new Error('tapBip32Derivation unsupported');
675
+ const prevOuts = this.inputs.map(getPrevOut);
676
+ const prevOutScript = prevOuts.map((i) => i.script);
677
+ const amount = prevOuts.map((i) => i.amount);
678
+ let signed = false;
679
+ let schnorrPub = u.pubSchnorr(privateKey);
680
+ let merkleRoot = input.tapMerkleRoot || P.EMPTY;
681
+ if (input.tapInternalKey) {
682
+ // internal + tweak = tweaked key
683
+ // if internal key == current public key, we need to tweak private key,
684
+ // otherwise sign as is. bitcoinjs implementation always wants tweaked
685
+ // priv key to be provided
686
+ const { pubKey, privKey } = getTaprootKeys(privateKey, schnorrPub, input.tapInternalKey, merkleRoot);
687
+ const [taprootPubKey, _] = u.taprootTweakPubkey(input.tapInternalKey, merkleRoot);
688
+ if (P.equalBytes(taprootPubKey, pubKey)) {
689
+ const hash = this.preimageWitnessV1(idx, prevOutScript, sighash, amount);
690
+ const sig = concatBytes(u.signSchnorr(hash, privKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);
691
+ this.updateInput(idx, { tapKeySig: sig }, true);
692
+ signed = true;
693
+ }
694
+ }
695
+ if (input.tapLeafScript) {
696
+ input.tapScriptSig = input.tapScriptSig || [];
697
+ for (const [_, _script] of input.tapLeafScript) {
698
+ const script = _script.subarray(0, -1);
699
+ const scriptDecoded = Script.decode(script);
700
+ const ver = _script[_script.length - 1];
701
+ const hash = tapLeafHash(script, ver);
702
+ // NOTE: no need to tweak internal key here, since we don't support nested p2tr
703
+ const pos = scriptDecoded.findIndex((i) => isBytes(i) && P.equalBytes(i, schnorrPub));
704
+ // Skip if there is no public key in tapLeafScript
705
+ if (pos === -1)
706
+ continue;
707
+ const msg = this.preimageWitnessV1(idx, prevOutScript, sighash, amount, undefined, script, ver);
708
+ const sig = concatBytes(u.signSchnorr(msg, privateKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);
709
+ this.updateInput(idx, { tapScriptSig: [[{ pubKey: schnorrPub, leafHash: hash }, sig]] }, true);
710
+ signed = true;
711
+ }
712
+ }
713
+ if (!signed)
714
+ throw new Error('No taproot scripts signed');
715
+ return true;
716
+ }
717
+ else {
718
+ // only compressed keys are supported for now
719
+ const pubKey = u.pubECDSA(privateKey);
720
+ // TODO: replace with explicit checks
721
+ // Check if script has public key or its has inside
722
+ let hasPubkey = false;
723
+ const pubKeyHash = u.hash160(pubKey);
724
+ for (const i of Script.decode(inputType.lastScript)) {
725
+ if (isBytes(i) && (P.equalBytes(i, pubKey) || P.equalBytes(i, pubKeyHash)))
726
+ hasPubkey = true;
727
+ }
728
+ if (!hasPubkey)
729
+ throw new Error(`Input script doesn't have pubKey: ${inputType.lastScript}`);
730
+ let hash;
731
+ if (inputType.txType === 'legacy') {
732
+ hash = this.preimageLegacy(idx, inputType.lastScript, sighash);
733
+ }
734
+ else if (inputType.txType === 'segwit') {
735
+ let script = inputType.lastScript;
736
+ // If wpkh OR sh-wpkh, wsh-wpkh is impossible, so looks ok
737
+ if (inputType.last.type === 'wpkh')
738
+ script = OutScript.encode({ type: 'pkh', hash: inputType.last.hash });
739
+ hash = this.preimageWitnessV0(idx, script, sighash, prevOut.amount);
740
+ }
741
+ else
742
+ throw new Error(`Transaction/sign: unknown tx type: ${inputType.txType}`);
743
+ const sig = u.signECDSA(hash, privateKey, this.opts.lowR);
744
+ this.updateInput(idx, {
745
+ partialSig: [[pubKey, concatBytes(sig, new Uint8Array([sighash]))]],
746
+ }, true);
747
+ }
748
+ return true;
749
+ }
750
+ // This is bad API. Will work if user creates and signs tx, but if
751
+ // there is some complex workflow with exchanging PSBT and signing them,
752
+ // then it is better to validate which output user signs. How could a better API look like?
753
+ // Example: user adds input, sends to another party, then signs received input (mixer etc),
754
+ // another user can add different input for same key and user will sign it.
755
+ // Even worse: another user can add bip32 derivation, and spend money from different address.
756
+ // Better api: signIdx
757
+ sign(privateKey, allowedSighash, _auxRand) {
758
+ let num = 0;
759
+ for (let i = 0; i < this.inputs.length; i++) {
760
+ try {
761
+ if (this.signIdx(privateKey, i, allowedSighash, _auxRand))
762
+ num++;
763
+ }
764
+ catch (e) { }
765
+ }
766
+ if (!num)
767
+ throw new Error('No inputs signed');
768
+ return num;
769
+ }
770
+ finalizeIdx(idx) {
771
+ this.checkInputIdx(idx);
772
+ if (this.fee < 0n)
773
+ throw new Error('Outputs spends more than inputs amount');
774
+ const input = this.inputs[idx];
775
+ const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);
776
+ // Taproot finalize
777
+ if (inputType.txType === 'taproot') {
778
+ if (input.tapKeySig)
779
+ input.finalScriptWitness = [input.tapKeySig];
780
+ else if (input.tapLeafScript && input.tapScriptSig) {
781
+ // Sort leafs by control block length.
782
+ const leafs = input.tapLeafScript.sort((a, b) => psbt.TaprootControlBlock.encode(a[0]).length -
783
+ psbt.TaprootControlBlock.encode(b[0]).length);
784
+ for (const [cb, _script] of leafs) {
785
+ // Last byte is version
786
+ const script = _script.slice(0, -1);
787
+ const ver = _script[_script.length - 1];
788
+ const outScript = OutScript.decode(script);
789
+ const hash = tapLeafHash(script, ver);
790
+ const scriptSig = input.tapScriptSig.filter((i) => P.equalBytes(i[0].leafHash, hash));
791
+ let signatures = [];
792
+ if (outScript.type === 'tr_ms') {
793
+ const m = outScript.m;
794
+ const pubkeys = outScript.pubkeys;
795
+ let added = 0;
796
+ for (const pub of pubkeys) {
797
+ const sigIdx = scriptSig.findIndex((i) => P.equalBytes(i[0].pubKey, pub));
798
+ // Should have exact amount of signatures (more -- will fail)
799
+ if (added === m || sigIdx === -1) {
800
+ signatures.push(P.EMPTY);
801
+ continue;
802
+ }
803
+ signatures.push(scriptSig[sigIdx][1]);
804
+ added++;
805
+ }
806
+ // Should be exact same as m
807
+ if (added !== m)
808
+ continue;
809
+ }
810
+ else if (outScript.type === 'tr_ns') {
811
+ for (const pub of outScript.pubkeys) {
812
+ const sigIdx = scriptSig.findIndex((i) => P.equalBytes(i[0].pubKey, pub));
813
+ if (sigIdx === -1)
814
+ continue;
815
+ signatures.push(scriptSig[sigIdx][1]);
816
+ }
817
+ if (signatures.length !== outScript.pubkeys.length)
818
+ continue;
819
+ }
820
+ else if (outScript.type === 'unknown' && this.opts.allowUnknownInputs) {
821
+ // Trying our best to sign what we can
822
+ const scriptDecoded = Script.decode(script);
823
+ signatures = scriptSig
824
+ .map(([{ pubKey }, signature]) => {
825
+ const pos = scriptDecoded.findIndex((i) => isBytes(i) && P.equalBytes(i, pubKey));
826
+ if (pos === -1)
827
+ throw new Error('finalize/taproot: cannot find position of pubkey in script');
828
+ return { signature, pos };
829
+ })
830
+ // Reverse order (because witness is stack and we take last element first from it)
831
+ .sort((a, b) => a.pos - b.pos)
832
+ .map((i) => i.signature);
833
+ if (!signatures.length)
834
+ continue;
835
+ }
836
+ else {
837
+ const custom = this.opts.customScripts;
838
+ if (custom) {
839
+ for (const c of custom) {
840
+ if (!c.finalizeTaproot)
841
+ continue;
842
+ const scriptDecoded = Script.decode(script);
843
+ const csEncoded = c.encode(scriptDecoded);
844
+ if (csEncoded === undefined)
845
+ continue;
846
+ const finalized = c.finalizeTaproot(script, csEncoded, scriptSig);
847
+ if (!finalized)
848
+ continue;
849
+ input.finalScriptWitness = finalized.concat(psbt.TaprootControlBlock.encode(cb));
850
+ input.finalScriptSig = P.EMPTY;
851
+ cleanFinalInput(input);
852
+ return;
853
+ }
854
+ }
855
+ throw new Error('Finalize: Unknown tapLeafScript');
856
+ }
857
+ // Witness is stack, so last element will be used first
858
+ input.finalScriptWitness = signatures
859
+ .reverse()
860
+ .concat([script, psbt.TaprootControlBlock.encode(cb)]);
861
+ break;
862
+ }
863
+ if (!input.finalScriptWitness)
864
+ throw new Error('finalize/taproot: empty witness');
865
+ }
866
+ else
867
+ throw new Error('finalize/taproot: unknown input');
868
+ input.finalScriptSig = P.EMPTY;
869
+ cleanFinalInput(input);
870
+ return;
871
+ }
872
+ if (!input.partialSig || !input.partialSig.length)
873
+ throw new Error('Not enough partial sign');
874
+ let inputScript = P.EMPTY;
875
+ let witness = [];
876
+ // TODO: move input scripts closer to payments/output scripts
877
+ // Multisig
878
+ if (inputType.last.type === 'ms') {
879
+ const m = inputType.last.m;
880
+ const pubkeys = inputType.last.pubkeys;
881
+ let signatures = [];
882
+ // partial: [pubkey, sign]
883
+ for (const pub of pubkeys) {
884
+ const sign = input.partialSig.find((s) => P.equalBytes(pub, s[0]));
885
+ if (!sign)
886
+ continue;
887
+ signatures.push(sign[1]);
888
+ }
889
+ signatures = signatures.slice(0, m);
890
+ if (signatures.length !== m) {
891
+ throw new Error(`Multisig: wrong signatures count, m=${m} n=${pubkeys.length} signatures=${signatures.length}`);
892
+ }
893
+ inputScript = Script.encode([0, ...signatures]);
894
+ }
895
+ else if (inputType.last.type === 'pk') {
896
+ inputScript = Script.encode([input.partialSig[0][1]]);
897
+ }
898
+ else if (inputType.last.type === 'pkh') {
899
+ inputScript = Script.encode([input.partialSig[0][1], input.partialSig[0][0]]);
900
+ }
901
+ else if (inputType.last.type === 'wpkh') {
902
+ inputScript = P.EMPTY;
903
+ witness = [input.partialSig[0][1], input.partialSig[0][0]];
904
+ }
905
+ else if (inputType.last.type === 'unknown' && !this.opts.allowUnknownInputs)
906
+ throw new Error('Unknown inputs not allowed');
907
+ // Create final scripts (generic part)
908
+ let finalScriptSig, finalScriptWitness;
909
+ if (inputType.type.includes('wsh-')) {
910
+ // P2WSH
911
+ if (inputScript.length && inputType.lastScript.length) {
912
+ witness = Script.decode(inputScript).map((i) => {
913
+ if (i === 0)
914
+ return P.EMPTY;
915
+ if (isBytes(i))
916
+ return i;
917
+ throw new Error(`Wrong witness op=${i}`);
918
+ });
919
+ }
920
+ witness = witness.concat(inputType.lastScript);
921
+ }
922
+ if (inputType.txType === 'segwit')
923
+ finalScriptWitness = witness;
924
+ if (inputType.type.startsWith('sh-wsh-')) {
925
+ finalScriptSig = Script.encode([Script.encode([0, u.sha256(inputType.lastScript)])]);
926
+ }
927
+ else if (inputType.type.startsWith('sh-')) {
928
+ finalScriptSig = Script.encode([...Script.decode(inputScript), inputType.lastScript]);
929
+ }
930
+ else if (inputType.type.startsWith('wsh-')) {
931
+ }
932
+ else if (inputType.txType !== 'segwit')
933
+ finalScriptSig = inputScript;
934
+ if (!finalScriptSig && !finalScriptWitness)
935
+ throw new Error('Unknown error finalizing input');
936
+ if (finalScriptSig)
937
+ input.finalScriptSig = finalScriptSig;
938
+ if (finalScriptWitness)
939
+ input.finalScriptWitness = finalScriptWitness;
940
+ cleanFinalInput(input);
941
+ }
942
+ finalize() {
943
+ for (let i = 0; i < this.inputs.length; i++)
944
+ this.finalizeIdx(i);
945
+ }
946
+ extract() {
947
+ if (!this.isFinal)
948
+ throw new Error('Transaction has unfinalized inputs');
949
+ if (!this.outputs.length)
950
+ throw new Error('Transaction has no outputs');
951
+ if (this.fee < 0n)
952
+ throw new Error('Outputs spends more than inputs amount');
953
+ return this.toBytes(true, true);
954
+ }
955
+ combine(other) {
956
+ for (const k of ['PSBTVersion', 'version', 'lockTime']) {
957
+ if (this.opts[k] !== other.opts[k]) {
958
+ throw new Error(`Transaction/combine: different ${k} this=${this.opts[k]} other=${other.opts[k]}`);
959
+ }
960
+ }
961
+ for (const k of ['inputs', 'outputs']) {
962
+ if (this[k].length !== other[k].length) {
963
+ throw new Error(`Transaction/combine: different ${k} length this=${this[k].length} other=${other[k].length}`);
964
+ }
965
+ }
966
+ const thisUnsigned = this.global.unsignedTx ? RawTx.encode(this.global.unsignedTx) : P.EMPTY;
967
+ const otherUnsigned = other.global.unsignedTx ? RawTx.encode(other.global.unsignedTx) : P.EMPTY;
968
+ if (!P.equalBytes(thisUnsigned, otherUnsigned))
969
+ throw new Error(`Transaction/combine: different unsigned tx`);
970
+ this.global = psbt.mergeKeyMap(psbt.PSBTGlobal, this.global, other.global);
971
+ for (let i = 0; i < this.inputs.length; i++)
972
+ this.updateInput(i, other.inputs[i], true);
973
+ for (let i = 0; i < this.outputs.length; i++)
974
+ this.updateOutput(i, other.outputs[i], true);
975
+ return this;
976
+ }
977
+ clone() {
978
+ // deepClone probably faster, but this enforces that encoding is valid
979
+ return Transaction.fromPSBT(this.toPSBT(this.opts.PSBTVersion), this.opts);
980
+ }
981
+ }
982
+ export function PSBTCombine(psbts) {
983
+ if (!psbts || !Array.isArray(psbts) || !psbts.length)
984
+ throw new Error('PSBTCombine: wrong PSBT list');
985
+ const tx = Transaction.fromPSBT(psbts[0]);
986
+ for (let i = 1; i < psbts.length; i++)
987
+ tx.combine(Transaction.fromPSBT(psbts[i]));
988
+ return tx.toPSBT();
989
+ }
990
+ // Copy-pasted from bip32 derive, maybe do something like 'bip32.parsePath'?
991
+ const HARDENED_OFFSET = 0x80000000;
992
+ export function bip32Path(path) {
993
+ const out = [];
994
+ if (!/^[mM]'?/.test(path))
995
+ throw new Error('Path must start with "m" or "M"');
996
+ if (/^[mM]'?$/.test(path))
997
+ return out;
998
+ const parts = path.replace(/^[mM]'?\//, '').split('/');
999
+ for (const c of parts) {
1000
+ const m = /^(\d+)('?)$/.exec(c);
1001
+ if (!m || m.length !== 3)
1002
+ throw new Error(`Invalid child index: ${c}`);
1003
+ let idx = +m[1];
1004
+ if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET)
1005
+ throw new Error('Invalid index');
1006
+ // hardened key
1007
+ if (m[2] === "'")
1008
+ idx += HARDENED_OFFSET;
1009
+ out.push(idx);
1010
+ }
1011
+ return out;
1012
+ }
1013
+ //# sourceMappingURL=transaction.js.map