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