@scure/btc-signer 1.8.0 → 2.0.0-beta.1

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