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