@btc-vision/bitcoin 7.0.0-alpha.1 → 7.0.0-alpha.3

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 (180) hide show
  1. package/README.md +334 -161
  2. package/browser/address.d.ts +5 -1
  3. package/browser/address.d.ts.map +1 -1
  4. package/browser/branded.d.ts +3 -14
  5. package/browser/branded.d.ts.map +1 -1
  6. package/browser/ecc/context.d.ts +22 -21
  7. package/browser/ecc/context.d.ts.map +1 -1
  8. package/browser/ecc/index.d.ts +1 -1
  9. package/browser/ecc/index.d.ts.map +1 -1
  10. package/browser/ecc/types.d.ts +10 -123
  11. package/browser/ecc/types.d.ts.map +1 -1
  12. package/browser/index.d.ts +3 -2
  13. package/browser/index.d.ts.map +1 -1
  14. package/browser/index.js +6465 -4692
  15. package/browser/opcodes.d.ts +11 -0
  16. package/browser/opcodes.d.ts.map +1 -1
  17. package/browser/payments/p2tr.d.ts.map +1 -1
  18. package/browser/psbt/PsbtCache.d.ts +54 -0
  19. package/browser/psbt/PsbtCache.d.ts.map +1 -0
  20. package/browser/psbt/PsbtFinalizer.d.ts +21 -0
  21. package/browser/psbt/PsbtFinalizer.d.ts.map +1 -0
  22. package/browser/psbt/PsbtSigner.d.ts +32 -0
  23. package/browser/psbt/PsbtSigner.d.ts.map +1 -0
  24. package/browser/psbt/PsbtTransaction.d.ts +25 -0
  25. package/browser/psbt/PsbtTransaction.d.ts.map +1 -0
  26. package/browser/psbt/types.d.ts +4 -70
  27. package/browser/psbt/types.d.ts.map +1 -1
  28. package/browser/psbt/validation.d.ts +1 -1
  29. package/browser/psbt/validation.d.ts.map +1 -1
  30. package/browser/psbt.d.ts +26 -40
  31. package/browser/psbt.d.ts.map +1 -1
  32. package/browser/script.d.ts.map +1 -1
  33. package/browser/transaction.d.ts +4 -4
  34. package/browser/transaction.d.ts.map +1 -1
  35. package/browser/types.d.ts +5 -3
  36. package/browser/types.d.ts.map +1 -1
  37. package/browser/workers/index.d.ts +3 -50
  38. package/browser/workers/index.d.ts.map +1 -1
  39. package/browser/workers/index.node.d.ts +24 -0
  40. package/browser/workers/index.node.d.ts.map +1 -0
  41. package/build/address.d.ts +5 -1
  42. package/build/address.d.ts.map +1 -1
  43. package/build/address.js +29 -17
  44. package/build/address.js.map +1 -1
  45. package/build/branded.d.ts +3 -14
  46. package/build/branded.d.ts.map +1 -1
  47. package/build/branded.js +0 -5
  48. package/build/branded.js.map +1 -1
  49. package/build/ecc/context.d.ts +22 -21
  50. package/build/ecc/context.d.ts.map +1 -1
  51. package/build/ecc/context.js +23 -95
  52. package/build/ecc/context.js.map +1 -1
  53. package/build/ecc/index.d.ts +1 -1
  54. package/build/ecc/index.d.ts.map +1 -1
  55. package/build/ecc/types.d.ts +7 -126
  56. package/build/ecc/types.d.ts.map +1 -1
  57. package/build/ecc/types.js +4 -1
  58. package/build/ecc/types.js.map +1 -1
  59. package/build/index.d.ts +3 -2
  60. package/build/index.d.ts.map +1 -1
  61. package/build/index.js +1 -1
  62. package/build/index.js.map +1 -1
  63. package/build/opcodes.d.ts +11 -0
  64. package/build/opcodes.d.ts.map +1 -1
  65. package/build/opcodes.js +19 -4
  66. package/build/opcodes.js.map +1 -1
  67. package/build/payments/p2tr.d.ts.map +1 -1
  68. package/build/payments/p2tr.js +2 -3
  69. package/build/payments/p2tr.js.map +1 -1
  70. package/build/psbt/PsbtCache.d.ts +54 -0
  71. package/build/psbt/PsbtCache.d.ts.map +1 -0
  72. package/build/psbt/PsbtCache.js +249 -0
  73. package/build/psbt/PsbtCache.js.map +1 -0
  74. package/build/psbt/PsbtFinalizer.d.ts +21 -0
  75. package/build/psbt/PsbtFinalizer.d.ts.map +1 -0
  76. package/build/psbt/PsbtFinalizer.js +157 -0
  77. package/build/psbt/PsbtFinalizer.js.map +1 -0
  78. package/build/psbt/PsbtSigner.d.ts +32 -0
  79. package/build/psbt/PsbtSigner.d.ts.map +1 -0
  80. package/build/psbt/PsbtSigner.js +192 -0
  81. package/build/psbt/PsbtSigner.js.map +1 -0
  82. package/build/psbt/PsbtTransaction.d.ts +25 -0
  83. package/build/psbt/PsbtTransaction.d.ts.map +1 -0
  84. package/build/psbt/PsbtTransaction.js +61 -0
  85. package/build/psbt/PsbtTransaction.js.map +1 -0
  86. package/build/psbt/types.d.ts +4 -70
  87. package/build/psbt/types.d.ts.map +1 -1
  88. package/build/psbt/validation.d.ts +1 -1
  89. package/build/psbt/validation.d.ts.map +1 -1
  90. package/build/psbt.d.ts +26 -40
  91. package/build/psbt.d.ts.map +1 -1
  92. package/build/psbt.js +177 -799
  93. package/build/psbt.js.map +1 -1
  94. package/build/script.d.ts.map +1 -1
  95. package/build/script.js +2 -2
  96. package/build/script.js.map +1 -1
  97. package/build/transaction.d.ts +4 -4
  98. package/build/transaction.d.ts.map +1 -1
  99. package/build/transaction.js +5 -4
  100. package/build/transaction.js.map +1 -1
  101. package/build/tsconfig.build.tsbuildinfo +1 -1
  102. package/build/types.d.ts +5 -3
  103. package/build/types.d.ts.map +1 -1
  104. package/build/types.js +9 -0
  105. package/build/types.js.map +1 -1
  106. package/build/workers/WorkerSigningPool.js +1 -1
  107. package/build/workers/WorkerSigningPool.js.map +1 -1
  108. package/build/workers/index.d.ts +3 -3
  109. package/build/workers/index.d.ts.map +1 -1
  110. package/build/workers/index.js +0 -3
  111. package/build/workers/index.js.map +1 -1
  112. package/build/workers/index.node.d.ts +24 -0
  113. package/build/workers/index.node.d.ts.map +1 -0
  114. package/build/workers/index.node.js +26 -0
  115. package/build/workers/index.node.js.map +1 -0
  116. package/package.json +27 -8
  117. package/src/address.ts +41 -18
  118. package/src/branded.ts +15 -13
  119. package/src/ecc/context.ts +30 -133
  120. package/src/ecc/index.ts +2 -2
  121. package/src/ecc/types.ts +7 -138
  122. package/src/index.ts +36 -2
  123. package/src/opcodes.ts +21 -4
  124. package/src/payments/p2tr.ts +2 -2
  125. package/src/psbt/PsbtCache.ts +325 -0
  126. package/src/psbt/PsbtFinalizer.ts +213 -0
  127. package/src/psbt/PsbtSigner.ts +302 -0
  128. package/src/psbt/PsbtTransaction.ts +82 -0
  129. package/src/psbt/types.ts +4 -86
  130. package/src/psbt/validation.ts +1 -1
  131. package/src/psbt.ts +348 -1197
  132. package/src/script.ts +2 -2
  133. package/src/transaction.ts +9 -8
  134. package/src/types.ts +14 -1
  135. package/src/workers/WorkerSigningPool.ts +1 -1
  136. package/src/workers/index.node.ts +27 -0
  137. package/src/workers/index.ts +7 -9
  138. package/test/address.spec.ts +2 -2
  139. package/test/bitcoin.core.spec.ts +5 -2
  140. package/test/browser/payments.spec.ts +151 -0
  141. package/test/browser/psbt.spec.ts +1510 -0
  142. package/test/browser/script.spec.ts +223 -0
  143. package/test/browser/setup.ts +13 -0
  144. package/test/browser/workers-signing.spec.ts +537 -0
  145. package/test/crypto.spec.ts +2 -2
  146. package/test/fixtures/core/base58_encode_decode.json +12 -48
  147. package/test/fixtures/core/base58_keys_invalid.json +50 -150
  148. package/test/fixtures/core/sighash.json +1 -3
  149. package/test/fixtures/core/tx_valid.json +133 -501
  150. package/test/fixtures/embed.json +3 -11
  151. package/test/fixtures/p2ms.json +21 -91
  152. package/test/fixtures/p2pk.json +5 -24
  153. package/test/fixtures/p2pkh.json +7 -36
  154. package/test/fixtures/p2sh.json +8 -54
  155. package/test/fixtures/p2tr.json +2 -6
  156. package/test/fixtures/p2wpkh.json +7 -36
  157. package/test/fixtures/p2wsh.json +14 -59
  158. package/test/fixtures/psbt.json +2 -6
  159. package/test/fixtures/script.json +12 -48
  160. package/test/integration/addresses.spec.ts +11 -5
  161. package/test/integration/bip32.spec.ts +1 -1
  162. package/test/integration/cltv.spec.ts +10 -6
  163. package/test/integration/csv.spec.ts +10 -9
  164. package/test/integration/payments.spec.ts +8 -4
  165. package/test/integration/taproot.spec.ts +26 -6
  166. package/test/integration/transactions.spec.ts +22 -8
  167. package/test/payments.spec.ts +1 -1
  168. package/test/payments.utils.ts +1 -1
  169. package/test/psbt.spec.ts +250 -64
  170. package/test/script_signature.spec.ts +1 -1
  171. package/test/transaction.spec.ts +18 -5
  172. package/test/tsconfig.json +6 -20
  173. package/test/workers-pool.spec.ts +22 -23
  174. package/test/workers-signing.spec.ts +7 -3
  175. package/test/workers.spec.ts +6 -7
  176. package/typedoc.json +11 -1
  177. package/vitest.config.browser.ts +68 -0
  178. package/browser/ecpair.d.ts +0 -99
  179. package/src/ecpair.d.ts +0 -99
  180. package/test/taproot-cache.spec.ts +0 -694
package/build/psbt.js CHANGED
@@ -1,32 +1,44 @@
1
1
  import { checkForInput, checkForOutput, Psbt as PsbtBase } from 'bip174';
2
- import { clone, equals, fromBase64, fromHex, reverse, toHex } from './io/index.js';
3
- import { fromOutputScript, isUnknownSegwitVersion, toOutputScript } from './address.js';
2
+ import { clone, equals, fromBase64, fromHex, toHex } from './io/index.js';
3
+ import { fromOutputScript, toOutputScript } from './address.js';
4
4
  import { bitcoin as btcNetwork } from './networks.js';
5
5
  import * as payments from './payments/index.js';
6
- import { tapleafHash } from './payments/bip341.js';
7
6
  import { checkTaprootInputFields, checkTaprootOutputFields, isTaprootInput, serializeTaprootSignature, tapScriptFinalizer, } from './psbt/bip371.js';
8
7
  import { toXOnly } from './pubkey.js';
9
- import { isP2TR, isP2WPKH, pubkeyInScript, witnessStackToScriptWitness } from './psbt/psbtutils.js';
10
- import { check32Bit, checkCache, checkInputsForPartialSig, checkPartialSigSighashes, checkScriptForPubkey, checkTxEmpty, checkTxForDupeIns, checkTxInputCache, isFinalized, } from './psbt/validation.js';
11
- import { checkInvalidP2WSH, classifyScript, compressPubkey, getMeaningfulScript, isPubkeyLike, isSigLike, range, scriptWitnessToWitnessStack, sighashTypeToString, } from './psbt/utils.js';
12
8
  import * as bscript from './script.js';
13
9
  import { Transaction } from './transaction.js';
10
+ // Import composition classes
11
+ import { PsbtCache } from './psbt/PsbtCache.js';
12
+ import { PsbtSigner } from './psbt/PsbtSigner.js';
13
+ import { getFinalScripts as _getFinalScripts, prepareFinalScripts as _prepareFinalScripts, PsbtFinalizer, } from './psbt/PsbtFinalizer.js';
14
+ import { PsbtTransaction, transactionFromBuffer } from './psbt/PsbtTransaction.js';
15
+ import { check32Bit, checkCache, checkInputsForPartialSig, checkPartialSigSighashes, checkScriptForPubkey, checkTxForDupeIns, checkTxInputCache, isFinalized, } from './psbt/validation.js';
16
+ import { checkInvalidP2WSH, classifyScript, getMeaningfulScript, range } from './psbt/utils.js';
17
+ import { witnessStackToScriptWitness } from './psbt/psbtutils.js';
18
+ // Re-export for backwards compatibility
19
+ export { getFinalScripts, prepareFinalScripts };
20
+ export { PsbtCache } from './psbt/PsbtCache.js';
21
+ export { PsbtSigner } from './psbt/PsbtSigner.js';
22
+ export { PsbtFinalizer } from './psbt/PsbtFinalizer.js';
23
+ export { PsbtTransaction, transactionFromBuffer } from './psbt/PsbtTransaction.js';
14
24
  /**
15
25
  * These are the default arguments for a Psbt instance.
16
26
  */
17
27
  const DEFAULT_OPTS = {
18
- /**
19
- * A bitcoinjs Network object. This is only used if you pass an `address`
20
- * parameter to addOutput. Otherwise it is not needed and can be left default.
21
- */
22
28
  network: btcNetwork,
23
- /**
24
- * When extractTransaction is called, the fee rate is checked.
25
- * THIS IS NOT TO BE RELIED ON.
26
- * It is only here as a last ditch effort to prevent sending a 500 BTC fee etc.
27
- */
28
- maximumFeeRate: 5000, // satoshi per byte
29
+ maximumFeeRate: 5000,
29
30
  };
31
+ /** Helper to create a Transaction from a buffer */
32
+ function txFromBuffer(buf) {
33
+ return Transaction.fromBuffer(buf);
34
+ }
35
+ // Standalone exports that delegate to PsbtFinalizer
36
+ function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks = true, solution) {
37
+ return _getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks, solution);
38
+ }
39
+ function prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution) {
40
+ return _prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution);
41
+ }
30
42
  /**
31
43
  * Psbt class can parse and generate a PSBT binary based off of the BIP174.
32
44
  * There are 6 roles that this class fulfills. (Explained in BIP174)
@@ -64,39 +76,23 @@ const DEFAULT_OPTS = {
64
76
  * Transaction Extractor: This role will perform some checks before returning a
65
77
  * Transaction object. Such as fee rate not being larger than maximumFeeRate etc.
66
78
  */
67
- /**
68
- * Psbt class can parse and generate a PSBT binary based off of the BIP174.
69
- */
70
79
  export class Psbt {
71
80
  data;
72
81
  #cache;
82
+ #signer;
83
+ #finalizer;
73
84
  #opts;
74
85
  constructor(opts = {}, data = new PsbtBase(new PsbtTransaction())) {
75
86
  this.data = data;
76
87
  this.#opts = Object.assign({}, DEFAULT_OPTS, opts);
77
- this.#cache = {
78
- nonWitnessUtxoTxCache: [],
79
- nonWitnessUtxoBufCache: [],
80
- txInCache: {},
81
- // unsignedTx.tx property is dynamically added by PsbtBase
82
- tx: this.data.globalMap.unsignedTx.tx,
83
- unsafeSignNonSegwit: false,
84
- hasSignatures: false,
85
- };
88
+ const tx = this.data.globalMap.unsignedTx.tx;
89
+ this.#cache = new PsbtCache(tx);
86
90
  if (opts.version === 3) {
87
91
  this.setVersionTRUC();
88
92
  }
89
93
  else if (this.data.inputs.length === 0)
90
94
  this.setVersion(2);
91
95
  }
92
- /** @internal - Exposed for testing. Do not use in production code. */
93
- get __CACHE() {
94
- return this.#cache;
95
- }
96
- /** @internal - Exposed for testing. Do not use in production code. */
97
- get opts() {
98
- return this.#opts;
99
- }
100
96
  get inputCount() {
101
97
  return this.data.inputs.length;
102
98
  }
@@ -125,7 +121,9 @@ export class Psbt {
125
121
  try {
126
122
  address = fromOutputScript(output.script, this.#opts.network);
127
123
  }
128
- catch (_) { }
124
+ catch (_) {
125
+ // Not all scripts can be converted to an address
126
+ }
129
127
  return {
130
128
  script: clone(output.script),
131
129
  value: output.value,
@@ -133,6 +131,20 @@ export class Psbt {
133
131
  };
134
132
  });
135
133
  }
134
+ /** Lazily initialized signer - created on first access */
135
+ get #lazySigner() {
136
+ if (!this.#signer) {
137
+ this.#signer = new PsbtSigner(this.#cache, txFromBuffer);
138
+ }
139
+ return this.#signer;
140
+ }
141
+ /** Lazily initialized finalizer - created on first access */
142
+ get #lazyFinalizer() {
143
+ if (!this.#finalizer) {
144
+ this.#finalizer = new PsbtFinalizer(this.#cache, txFromBuffer);
145
+ }
146
+ return this.#finalizer;
147
+ }
136
148
  static fromBase64(data, opts = {}) {
137
149
  const buffer = fromBase64(data);
138
150
  return this.fromBuffer(buffer, opts);
@@ -145,7 +157,6 @@ export class Psbt {
145
157
  const psbtBase = PsbtBase.fromBuffer(buffer, transactionFromBuffer);
146
158
  const psbt = new Psbt(opts, psbtBase);
147
159
  checkTxForDupeIns(psbt.#cache.tx, psbt.#cache);
148
- // Check if restored PSBT has any signatures (partial or finalized)
149
160
  psbt.#cache.hasSignatures = psbt.data.inputs.some((input) => input.partialSig?.length ||
150
161
  input.tapKeySig ||
151
162
  input.tapScriptSig?.length ||
@@ -158,20 +169,21 @@ export class Psbt {
158
169
  return this;
159
170
  }
160
171
  clone() {
161
- // TODO: more efficient cloning
162
- const clonedOpts = JSON.parse(JSON.stringify(this.#opts));
172
+ const clonedOpts = structuredClone(this.#opts);
163
173
  return Psbt.fromBuffer(new Uint8Array(this.data.toBuffer()), clonedOpts);
164
174
  }
175
+ get maximumFeeRate() {
176
+ return this.#opts.maximumFeeRate;
177
+ }
165
178
  setMaximumFeeRate(satoshiPerByte) {
166
- check32Bit(satoshiPerByte); // 42.9 BTC per byte IS excessive... so throw
179
+ check32Bit(satoshiPerByte);
167
180
  this.#opts.maximumFeeRate = satoshiPerByte;
168
181
  }
169
182
  setVersion(version) {
170
183
  check32Bit(version);
171
184
  checkInputsForPartialSig(this.data.inputs, 'setVersion', this.#cache.hasSignatures);
172
- const c = this.#cache;
173
- c.tx.version = version;
174
- c.extractedTx = undefined;
185
+ this.#cache.tx.version = version;
186
+ this.#cache.invalidate('outputs');
175
187
  return this;
176
188
  }
177
189
  setVersionTRUC() {
@@ -180,20 +192,18 @@ export class Psbt {
180
192
  setLocktime(locktime) {
181
193
  check32Bit(locktime);
182
194
  checkInputsForPartialSig(this.data.inputs, 'setLocktime', this.#cache.hasSignatures);
183
- const c = this.#cache;
184
- c.tx.locktime = locktime;
185
- c.extractedTx = undefined;
195
+ this.#cache.tx.locktime = locktime;
196
+ this.#cache.invalidate('outputs');
186
197
  return this;
187
198
  }
188
199
  setInputSequence(inputIndex, sequence) {
189
200
  check32Bit(sequence);
190
201
  checkInputsForPartialSig(this.data.inputs, 'setInputSequence', this.#cache.hasSignatures);
191
- const c = this.#cache;
192
- if (c.tx.ins.length <= inputIndex) {
202
+ if (this.#cache.tx.ins.length <= inputIndex) {
193
203
  throw new Error('Input index too high');
194
204
  }
195
- c.tx.ins[inputIndex].sequence = sequence;
196
- c.extractedTx = undefined;
205
+ this.#cache.tx.ins[inputIndex].sequence = sequence;
206
+ this.#cache.invalidate('outputs');
197
207
  return this;
198
208
  }
199
209
  addInputs(inputDatas, checkPartialSigs = true) {
@@ -211,7 +221,6 @@ export class Psbt {
211
221
  }
212
222
  if (inputData.witnessScript)
213
223
  checkInvalidP2WSH(inputData.witnessScript);
214
- // Convert witnessUtxo for bip174 v3 compatibility (value: bigint, script: Uint8Array)
215
224
  const normalizedInputData = inputData.witnessUtxo
216
225
  ? {
217
226
  ...inputData,
@@ -223,39 +232,21 @@ export class Psbt {
223
232
  },
224
233
  }
225
234
  : inputData;
226
- const c = this.#cache;
227
235
  this.data.addInput(normalizedInputData);
228
- const txIn = c.tx.ins[c.tx.ins.length - 1];
229
- checkTxInputCache(c, txIn);
236
+ const txIn = this.#cache.tx.ins[this.#cache.tx.ins.length - 1];
237
+ checkTxInputCache(this.#cache, txIn);
230
238
  const inputIndex = this.data.inputs.length - 1;
231
239
  const input = this.data.inputs[inputIndex];
232
240
  if (input.nonWitnessUtxo) {
233
- addNonWitnessTxCache(this.#cache, input, inputIndex);
241
+ this.#cache.addNonWitnessTxCache(input, inputIndex, txFromBuffer);
234
242
  }
235
- c.fee = undefined;
236
- c.feeRate = undefined;
237
- c.extractedTx = undefined;
238
- c.prevOuts = undefined;
239
- c.signingScripts = undefined;
240
- c.values = undefined;
241
- c.taprootHashCache = undefined;
243
+ this.#cache.invalidate('full');
242
244
  return this;
243
245
  }
244
246
  addOutputs(outputDatas, checkPartialSigs = true) {
245
247
  outputDatas.forEach((outputData) => this.addOutput(outputData, checkPartialSigs));
246
248
  return this;
247
249
  }
248
- /**
249
- * Add an output to the PSBT.
250
- *
251
- * **PERFORMANCE WARNING:** Passing an `address` string is ~10x slower than passing
252
- * a `script` directly due to address parsing overhead (bech32 decode, etc.).
253
- * For high-performance use cases with many outputs, pre-compute the script using
254
- * `toOutputScript(address, network)` and pass `{ script, value }` instead.
255
- *
256
- * @param outputData - Output data with either `address` or `script`, and `value`
257
- * @param checkPartialSigs - Whether to check for existing signatures (default: true)
258
- */
259
250
  addOutput(outputData, checkPartialSigs = true) {
260
251
  const hasAddress = 'address' in outputData;
261
252
  const hasScript = 'script' in outputData;
@@ -273,12 +264,8 @@ export class Psbt {
273
264
  outputData = Object.assign({}, outputData, { script });
274
265
  }
275
266
  checkTaprootOutputFields(outputData, outputData, 'addOutput');
276
- const c = this.#cache;
277
267
  this.data.addOutput(outputData);
278
- c.fee = undefined;
279
- c.feeRate = undefined;
280
- c.extractedTx = undefined;
281
- c.taprootHashCache = undefined;
268
+ this.#cache.invalidate('outputs');
282
269
  return this;
283
270
  }
284
271
  extractTransaction(disableFeeCheck, disableOutputChecks) {
@@ -287,24 +274,24 @@ export class Psbt {
287
274
  }
288
275
  if (!this.data.inputs.every(isFinalized))
289
276
  throw new Error('Not finalized');
290
- const c = this.#cache;
291
277
  if (!disableFeeCheck) {
292
- checkFees(this, c, this.#opts);
278
+ this.#cache.computeFeeRate(this.data.inputs, disableOutputChecks, txFromBuffer);
279
+ this.#cache.checkFees(this.#opts);
293
280
  }
294
- if (c.extractedTx)
295
- return c.extractedTx;
296
- const tx = c.tx.clone();
297
- inputFinalizeGetAmts(this.data.inputs, tx, c, true, disableOutputChecks);
281
+ if (this.#cache.extractedTx)
282
+ return this.#cache.extractedTx;
283
+ const tx = this.#cache.tx.clone();
284
+ this.#cache.finalizeAndComputeAmounts(this.data.inputs, tx, true, disableOutputChecks, txFromBuffer);
298
285
  return tx;
299
286
  }
300
287
  getFeeRate(disableOutputChecks = false) {
301
- return getTxCacheValue('feeRate', 'fee rate', this.data.inputs, this.#cache, disableOutputChecks);
288
+ return this.#cache.computeFeeRate(this.data.inputs, disableOutputChecks, txFromBuffer);
302
289
  }
303
290
  getFee(disableOutputChecks = false) {
304
- return getTxCacheValue('fee', 'fee', this.data.inputs, this.#cache, disableOutputChecks);
291
+ return this.#cache.computeFee(this.data.inputs, disableOutputChecks, txFromBuffer);
305
292
  }
306
293
  finalizeAllInputs() {
307
- checkForInput(this.data.inputs, 0); // making sure we have at least one
294
+ checkForInput(this.data.inputs, 0);
308
295
  range(this.data.inputs.length).forEach((idx) => this.finalizeInput(idx));
309
296
  return this;
310
297
  }
@@ -323,34 +310,35 @@ export class Psbt {
323
310
  }
324
311
  getInputType(inputIndex) {
325
312
  const input = checkForInput(this.data.inputs, inputIndex);
326
- const script = getScriptFromUtxo(inputIndex, input, this.#cache);
327
- const result = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript || redeemFromFinalScriptSig(input.finalScriptSig), input.witnessScript || redeemFromFinalWitnessScript(input.finalScriptWitness));
313
+ const script = this.#cache.getScriptFromUtxo(inputIndex, input, txFromBuffer);
314
+ const result = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript || this.#cache.redeemFromFinalScriptSig(input.finalScriptSig), input.witnessScript ||
315
+ this.#cache.redeemFromFinalWitnessScript(input.finalScriptWitness));
328
316
  const type = result.type === 'raw' ? '' : result.type + '-';
329
317
  const mainType = classifyScript(result.meaningfulScript);
330
318
  return (type + mainType);
331
319
  }
332
320
  inputHasPubkey(inputIndex, pubkey) {
333
321
  const input = checkForInput(this.data.inputs, inputIndex);
334
- return pubkeyInInput(pubkey, input, inputIndex, this.#cache);
322
+ return this.#cache.pubkeyInInput(pubkey, input, inputIndex, txFromBuffer);
335
323
  }
336
324
  inputHasHDKey(inputIndex, root) {
337
325
  const input = checkForInput(this.data.inputs, inputIndex);
338
- const derivationIsMine = bip32DerivationIsMine(root);
326
+ const derivationIsMine = this.#lazySigner.bip32DerivationIsMine(root);
339
327
  return !!input.bip32Derivation && input.bip32Derivation.some(derivationIsMine);
340
328
  }
341
329
  outputHasPubkey(outputIndex, pubkey) {
342
330
  const output = checkForOutput(this.data.outputs, outputIndex);
343
- return pubkeyInOutput(pubkey, output, outputIndex, this.#cache);
331
+ return this.#cache.pubkeyInOutput(pubkey, output, outputIndex);
344
332
  }
345
333
  outputHasHDKey(outputIndex, root) {
346
334
  const output = checkForOutput(this.data.outputs, outputIndex);
347
- const derivationIsMine = bip32DerivationIsMine(root);
335
+ const derivationIsMine = this.#lazySigner.bip32DerivationIsMine(root);
348
336
  return !!output.bip32Derivation && output.bip32Derivation.some(derivationIsMine);
349
337
  }
350
338
  validateSignaturesOfAllInputs(validator) {
351
- checkForInput(this.data.inputs, 0); // making sure we have at least one
339
+ checkForInput(this.data.inputs, 0);
352
340
  const results = range(this.data.inputs.length).map((idx) => this.validateSignaturesOfInput(idx, validator));
353
- return results.reduce((final, res) => res && final, true);
341
+ return results.every((res) => res);
354
342
  }
355
343
  validateSignaturesOfInput(inputIndex, validator, pubkey) {
356
344
  const input = this.data.inputs[inputIndex];
@@ -377,56 +365,43 @@ export class Psbt {
377
365
  }
378
366
  return this;
379
367
  }
380
- signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
381
- return new Promise((resolve, reject) => {
382
- if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
383
- return reject(new Error('Need HDSigner to sign input'));
384
- }
385
- const results = [];
386
- const promises = [];
387
- for (const i of range(this.data.inputs.length)) {
388
- promises.push(this.signInputHDAsync(i, hdKeyPair, sighashTypes).then(() => {
389
- results.push(true);
390
- }, () => {
391
- results.push(false);
392
- }));
393
- }
394
- return Promise.all(promises).then(() => {
395
- if (results.every((v) => !v)) {
396
- return reject(new Error('No inputs were signed'));
397
- }
398
- resolve();
399
- });
400
- });
368
+ async signAllInputsHDAsync(hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
369
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
370
+ throw new Error('Need HDSigner to sign input');
371
+ }
372
+ const results = [];
373
+ const promises = [];
374
+ for (const i of range(this.data.inputs.length)) {
375
+ promises.push(this.signInputHDAsync(i, hdKeyPair, sighashTypes).then(() => {
376
+ results.push(true);
377
+ }, () => {
378
+ results.push(false);
379
+ }));
380
+ }
381
+ await Promise.all(promises);
382
+ if (results.every((v) => !v)) {
383
+ throw new Error('No inputs were signed');
384
+ }
401
385
  }
402
386
  signInputHD(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
403
387
  if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
404
388
  throw new Error('Need HDSigner to sign input');
405
389
  }
406
- const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
390
+ const signers = this.#lazySigner.getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
407
391
  signers.forEach((signer) => this.signInput(inputIndex, signer, sighashTypes));
408
392
  return this;
409
393
  }
410
- signInputHDAsync(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
411
- return new Promise((resolve, reject) => {
412
- if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
413
- return reject(new Error('Need HDSigner to sign input'));
414
- }
415
- const signers = getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
416
- const promises = signers.map((signer) => this.signInputAsync(inputIndex, signer, sighashTypes));
417
- return Promise.all(promises)
418
- .then(() => {
419
- resolve();
420
- })
421
- .catch(reject);
422
- });
394
+ async signInputHDAsync(inputIndex, hdKeyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
395
+ if (!hdKeyPair || !hdKeyPair.publicKey || !hdKeyPair.fingerprint) {
396
+ throw new Error('Need HDSigner to sign input');
397
+ }
398
+ const signers = this.#lazySigner.getSignersFromHD(inputIndex, this.data.inputs, hdKeyPair);
399
+ const promises = signers.map((signer) => this.signInputAsync(inputIndex, signer, sighashTypes));
400
+ await Promise.all(promises);
423
401
  }
424
402
  signAllInputs(keyPair, sighashTypes) {
425
403
  if (!keyPair || !keyPair.publicKey)
426
404
  throw new Error('Need Signer to sign input');
427
- // TODO: Add a pubkey/pubkeyhash cache to each input
428
- // as input information is added, then eventually
429
- // optimize this method.
430
405
  const results = [];
431
406
  for (const i of range(this.data.inputs.length)) {
432
407
  try {
@@ -442,29 +417,22 @@ export class Psbt {
442
417
  }
443
418
  return this;
444
419
  }
445
- signAllInputsAsync(keyPair, sighashTypes) {
446
- return new Promise((resolve, reject) => {
447
- if (!keyPair || !keyPair.publicKey)
448
- return reject(new Error('Need Signer to sign input'));
449
- // TODO: Add a pubkey/pubkeyhash cache to each input
450
- // as input information is added, then eventually
451
- // optimize this method.
452
- const results = [];
453
- const promises = [];
454
- for (const [i] of this.data.inputs.entries()) {
455
- promises.push(this.signInputAsync(i, keyPair, sighashTypes).then(() => {
456
- results.push(true);
457
- }, () => {
458
- results.push(false);
459
- }));
460
- }
461
- return Promise.all(promises).then(() => {
462
- if (results.every((v) => !v)) {
463
- return reject(new Error('No inputs were signed'));
464
- }
465
- resolve();
466
- });
467
- });
420
+ async signAllInputsAsync(keyPair, sighashTypes) {
421
+ if (!keyPair || !keyPair.publicKey)
422
+ throw new Error('Need Signer to sign input');
423
+ const results = [];
424
+ const promises = [];
425
+ for (const [i] of this.data.inputs.entries()) {
426
+ promises.push(this.signInputAsync(i, keyPair, sighashTypes).then(() => {
427
+ results.push(true);
428
+ }, () => {
429
+ results.push(false);
430
+ }));
431
+ }
432
+ await Promise.all(promises);
433
+ if (results.every((v) => !v)) {
434
+ throw new Error('No inputs were signed');
435
+ }
468
436
  }
469
437
  signInput(inputIndex, keyPair, sighashTypes) {
470
438
  if (!keyPair || !keyPair.publicKey) {
@@ -486,25 +454,21 @@ export class Psbt {
486
454
  }
487
455
  throw new Error(`Input #${inputIndex} is not of type Taproot.`);
488
456
  }
489
- signInputAsync(inputIndex, keyPair, sighashTypes) {
490
- return Promise.resolve().then(() => {
491
- if (!keyPair || !keyPair.publicKey)
492
- throw new Error('Need Signer to sign input');
493
- const input = checkForInput(this.data.inputs, inputIndex);
494
- if (isTaprootInput(input))
495
- return this.#signTaprootInputAsync(inputIndex, input, keyPair, undefined, sighashTypes);
496
- return this.#signInputAsync(inputIndex, keyPair, sighashTypes);
497
- });
457
+ async signInputAsync(inputIndex, keyPair, sighashTypes) {
458
+ if (!keyPair || !keyPair.publicKey)
459
+ throw new Error('Need Signer to sign input');
460
+ const input = checkForInput(this.data.inputs, inputIndex);
461
+ if (isTaprootInput(input))
462
+ return this.#signTaprootInputAsync(inputIndex, input, keyPair, undefined, sighashTypes);
463
+ return this.#signInputAsync(inputIndex, keyPair, sighashTypes);
498
464
  }
499
- signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) {
500
- return Promise.resolve().then(() => {
501
- if (!keyPair || !keyPair.publicKey)
502
- throw new Error('Need Signer to sign input');
503
- const input = checkForInput(this.data.inputs, inputIndex);
504
- if (isTaprootInput(input))
505
- return this.#signTaprootInputAsync(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
506
- throw new Error(`Input #${inputIndex} is not of type Taproot.`);
507
- });
465
+ async signTaprootInputAsync(inputIndex, keyPair, tapLeafHash, sighashTypes) {
466
+ if (!keyPair || !keyPair.publicKey)
467
+ throw new Error('Need Signer to sign input');
468
+ const input = checkForInput(this.data.inputs, inputIndex);
469
+ if (isTaprootInput(input))
470
+ return this.#signTaprootInputAsync(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
471
+ throw new Error(`Input #${inputIndex} is not of type Taproot.`);
508
472
  }
509
473
  toBuffer() {
510
474
  checkCache(this.#cache);
@@ -526,7 +490,6 @@ export class Psbt {
526
490
  if (updateData.witnessScript)
527
491
  checkInvalidP2WSH(updateData.witnessScript);
528
492
  checkTaprootInputFields(this.data.inputs[inputIndex], updateData, 'updateInput');
529
- // Convert witnessUtxo for bip174 v3 compatibility (value: bigint, script: Uint8Array)
530
493
  const normalizedUpdate = updateData.witnessUtxo
531
494
  ? {
532
495
  ...updateData,
@@ -540,7 +503,7 @@ export class Psbt {
540
503
  : updateData;
541
504
  this.data.updateInput(inputIndex, normalizedUpdate);
542
505
  if (updateData.nonWitnessUtxo) {
543
- addNonWitnessTxCache(this.#cache, this.data.inputs[inputIndex], inputIndex);
506
+ this.#cache.addNonWitnessTxCache(this.data.inputs[inputIndex], inputIndex, txFromBuffer);
544
507
  }
545
508
  return this;
546
509
  }
@@ -572,13 +535,13 @@ export class Psbt {
572
535
  const pubkey = keyPair.publicKey instanceof Uint8Array
573
536
  ? keyPair.publicKey
574
537
  : new Uint8Array(keyPair.publicKey);
575
- const hashesForSig = getTaprootHashesForSig(inputIndex, input, this.data.inputs, pubkey, this.#cache, tapLeafHashToSign, allowedSighashTypes);
538
+ const hashesForSig = this.#lazySigner.getTaprootHashesForSig(inputIndex, input, this.data.inputs, pubkey, tapLeafHashToSign, allowedSighashTypes);
576
539
  if (!hashesForSig || !hashesForSig.length)
577
540
  throw new Error(`Can not sign for input #${inputIndex} with the key ${toHex(pubkey)}`);
578
541
  return hashesForSig;
579
542
  }
580
543
  #finalizeInput(inputIndex, input, finalScriptsFunc = getFinalScripts, canRunChecks = true) {
581
- const { script, isP2SH, isP2WSH, isSegwit } = getScriptFromInput(inputIndex, input, this.#cache);
544
+ const { script, isP2SH, isP2WSH, isSegwit } = this.#lazyFinalizer.getScriptFromInput(inputIndex, input);
582
545
  if (!script)
583
546
  throw new Error(`No script found for input #${inputIndex}`);
584
547
  checkPartialSigSighashes(input);
@@ -595,7 +558,6 @@ export class Psbt {
595
558
  #finalizeTaprootInput(inputIndex, input, tapLeafHashToFinalize, finalScriptsFunc = tapScriptFinalizer) {
596
559
  if (!input.witnessUtxo)
597
560
  throw new Error(`Cannot finalize input #${inputIndex}. Missing witness utxo.`);
598
- // Check key spend first. Increased privacy and reduced block space.
599
561
  if (input.tapKeySig) {
600
562
  const payment = payments.p2tr({
601
563
  output: input.witnessUtxo.script,
@@ -615,7 +577,7 @@ export class Psbt {
615
577
  }
616
578
  #validateSignaturesOfInput(inputIndex, validator, pubkey) {
617
579
  const input = this.data.inputs[inputIndex];
618
- const partialSig = (input || {}).partialSig;
580
+ const partialSig = input?.partialSig;
619
581
  if (!input || !partialSig || partialSig.length < 1)
620
582
  throw new Error('No signatures to validate');
621
583
  if (typeof validator !== 'function')
@@ -632,9 +594,9 @@ export class Psbt {
632
594
  const pSigPubkey = pSig.pubkey;
633
595
  const sig = bscript.signature.decode(pSigSignature);
634
596
  const { hash, script } = sighashCache !== sig.hashType || !hashCache || !scriptCache
635
- ? getHashForSig(inputIndex, Object.assign({}, input, {
597
+ ? this.#lazySigner.getHashForSig(inputIndex, Object.assign({}, input, {
636
598
  sighashType: sig.hashType,
637
- }), this.#cache, true)
599
+ }), true)
638
600
  : { hash: hashCache, script: scriptCache };
639
601
  sighashCache = sig.hashType;
640
602
  hashCache = hash;
@@ -646,22 +608,22 @@ export class Psbt {
646
608
  }
647
609
  #validateSignaturesOfTaprootInput(inputIndex, validator, pubkey) {
648
610
  const input = this.data.inputs[inputIndex];
649
- const tapKeySig = (input || {}).tapKeySig;
650
- const tapScriptSig = (input || {}).tapScriptSig;
611
+ const tapKeySig = input?.tapKeySig;
612
+ const tapScriptSig = input?.tapScriptSig;
651
613
  if (!input && !tapKeySig && !(tapScriptSig && !tapScriptSig.length))
652
614
  throw new Error('No signatures to validate');
653
615
  if (typeof validator !== 'function')
654
616
  throw new Error('Need validator function to validate signatures');
655
617
  const xPubkey = pubkey ? toXOnly(pubkey) : undefined;
656
618
  const allHashses = xPubkey
657
- ? getTaprootHashesForSig(inputIndex, input, this.data.inputs, xPubkey, this.#cache)
658
- : getAllTaprootHashesForSig(inputIndex, input, this.data.inputs, this.#cache);
619
+ ? this.#lazySigner.getTaprootHashesForSig(inputIndex, input, this.data.inputs, xPubkey)
620
+ : this.#lazySigner.getAllTaprootHashesForSig(inputIndex, input, this.data.inputs);
659
621
  if (!allHashses.length)
660
622
  throw new Error('No signatures for this pubkey');
661
623
  const tapKeyHash = allHashses.find((h) => !h.leafHash);
662
624
  let validationResultCount = 0;
663
625
  if (tapKeySig && tapKeyHash) {
664
- const isValidTapkeySig = validator(tapKeyHash.pubkey, tapKeyHash.hash, trimTaprootSig(tapKeySig));
626
+ const isValidTapkeySig = validator(tapKeyHash.pubkey, tapKeyHash.hash, this.#lazySigner.trimTaprootSig(tapKeySig));
665
627
  if (!isValidTapkeySig)
666
628
  return false;
667
629
  validationResultCount++;
@@ -671,7 +633,7 @@ export class Psbt {
671
633
  const tapSigPubkey = tapSig.pubkey;
672
634
  const tapSigHash = allHashses.find((h) => equals(tapSigPubkey, h.pubkey));
673
635
  if (tapSigHash) {
674
- const isValidTapScriptSig = validator(tapSigPubkey, tapSigHash.hash, trimTaprootSig(tapSig.signature));
636
+ const isValidTapScriptSig = validator(tapSigPubkey, tapSigHash.hash, this.#lazySigner.trimTaprootSig(tapSig.signature));
675
637
  if (!isValidTapScriptSig)
676
638
  return false;
677
639
  validationResultCount++;
@@ -684,7 +646,7 @@ export class Psbt {
684
646
  const pubkey = keyPair.publicKey instanceof Uint8Array
685
647
  ? keyPair.publicKey
686
648
  : new Uint8Array(keyPair.publicKey);
687
- const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, pubkey, this.#cache, sighashTypes);
649
+ const { hash, sighashType } = this.#lazySigner.getHashAndSighashType(this.data.inputs, inputIndex, pubkey, sighashTypes);
688
650
  const sig = keyPair.sign(hash);
689
651
  const partialSig = [
690
652
  {
@@ -702,7 +664,6 @@ export class Psbt {
702
664
  : new Uint8Array(keyPair.publicKey));
703
665
  if (!('signSchnorr' in keyPair) || typeof keyPair.signSchnorr !== 'function')
704
666
  throw new Error(`Need Schnorr Signer to sign taproot input #${inputIndex}.`);
705
- // checkTaprootHashesForSig validates signSchnorr exists
706
667
  const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHashToSign, allowedSighashTypes);
707
668
  const signSchnorr = keyPair.signSchnorr.bind(keyPair);
708
669
  const tapKeySig = hashesForSig
@@ -725,22 +686,21 @@ export class Psbt {
725
686
  }
726
687
  return this;
727
688
  }
728
- #signInputAsync(inputIndex, keyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
689
+ async #signInputAsync(inputIndex, keyPair, sighashTypes = [Transaction.SIGHASH_ALL]) {
729
690
  const pubkey = keyPair.publicKey instanceof Uint8Array
730
691
  ? keyPair.publicKey
731
692
  : new Uint8Array(keyPair.publicKey);
732
- const { hash, sighashType } = getHashAndSighashType(this.data.inputs, inputIndex, pubkey, this.#cache, sighashTypes);
733
- return Promise.resolve(keyPair.sign(hash)).then((signature) => {
734
- const sig = signature instanceof Uint8Array ? signature : new Uint8Array(signature);
735
- const partialSig = [
736
- {
737
- pubkey,
738
- signature: bscript.signature.encode(sig, sighashType),
739
- },
740
- ];
741
- this.data.updateInput(inputIndex, { partialSig });
742
- this.#cache.hasSignatures = true;
743
- });
693
+ const { hash, sighashType } = this.#lazySigner.getHashAndSighashType(this.data.inputs, inputIndex, pubkey, sighashTypes);
694
+ const signature = await keyPair.sign(hash);
695
+ const sig = signature instanceof Uint8Array ? signature : new Uint8Array(signature);
696
+ const partialSig = [
697
+ {
698
+ pubkey,
699
+ signature: bscript.signature.encode(sig, sighashType),
700
+ },
701
+ ];
702
+ this.data.updateInput(inputIndex, { partialSig });
703
+ this.#cache.hasSignatures = true;
744
704
  }
745
705
  async #signTaprootInputAsync(inputIndex, input, keyPair, tapLeafHash, sighashTypes = [Transaction.SIGHASH_DEFAULT]) {
746
706
  const pubkey = (keyPair.publicKey instanceof Uint8Array
@@ -748,610 +708,28 @@ export class Psbt {
748
708
  : new Uint8Array(keyPair.publicKey));
749
709
  if (!('signSchnorr' in keyPair) || typeof keyPair.signSchnorr !== 'function')
750
710
  throw new Error(`Need Schnorr Signer to sign taproot input #${inputIndex}.`);
751
- // checkTaprootHashesForSig validates signSchnorr exists
752
711
  const hashesForSig = this.checkTaprootHashesForSig(inputIndex, input, keyPair, tapLeafHash, sighashTypes);
753
712
  const signSchnorr = keyPair.signSchnorr.bind(keyPair);
754
- const signaturePromises = [];
755
- const tapKeyHash = hashesForSig.filter((h) => !h.leafHash)[0];
713
+ const tapKeyHash = hashesForSig.find((h) => !h.leafHash);
756
714
  if (tapKeyHash) {
757
- const tapKeySigPromise = Promise.resolve(signSchnorr(tapKeyHash.hash)).then((sig) => {
758
- return {
759
- tapKeySig: serializeTaprootSignature(sig, input.sighashType),
760
- };
761
- });
762
- signaturePromises.push(tapKeySigPromise);
715
+ const sig = await signSchnorr(tapKeyHash.hash);
716
+ const tapKeySig = serializeTaprootSignature(sig, input.sighashType);
717
+ this.data.updateInput(inputIndex, { tapKeySig });
718
+ this.#cache.hasSignatures = true;
763
719
  }
764
720
  const tapScriptHashes = hashesForSig.filter((h) => !!h.leafHash);
765
721
  if (tapScriptHashes.length) {
766
- const tapScriptSigPromises = tapScriptHashes.map(async (tsh) => {
722
+ const tapScriptSigs = await Promise.all(tapScriptHashes.map(async (tsh) => {
767
723
  const signature = await signSchnorr(tsh.hash);
768
- const tapScriptSig = [
769
- {
770
- pubkey: toXOnly(pubkey),
771
- signature: serializeTaprootSignature(signature, input.sighashType),
772
- leafHash: tsh.leafHash,
773
- },
774
- ];
775
- return { tapScriptSig };
776
- });
777
- signaturePromises.push(...tapScriptSigPromises);
778
- }
779
- const results = await Promise.all(signaturePromises);
780
- for (const v of results) {
781
- this.data.updateInput(inputIndex, v);
724
+ return {
725
+ pubkey: toXOnly(pubkey),
726
+ signature: serializeTaprootSignature(signature, input.sighashType),
727
+ leafHash: tsh.leafHash,
728
+ };
729
+ }));
730
+ this.data.updateInput(inputIndex, { tapScriptSig: tapScriptSigs });
782
731
  this.#cache.hasSignatures = true;
783
732
  }
784
733
  }
785
734
  }
786
- /**
787
- * This function is needed to pass to the bip174 base class's fromBuffer.
788
- * It takes the "transaction buffer" portion of the psbt buffer and returns a
789
- * Transaction (From the bip174 library) interface.
790
- */
791
- const transactionFromBuffer = (buffer) => new PsbtTransaction(buffer);
792
- /**
793
- * This class implements the Transaction interface from bip174 library.
794
- * It contains a bitcoinjs-lib Transaction object.
795
- */
796
- class PsbtTransaction {
797
- tx;
798
- constructor(buffer = new Uint8Array([2, 0, 0, 0, 0, 0, 0, 0, 0, 0])) {
799
- this.tx = Transaction.fromBuffer(buffer);
800
- checkTxEmpty(this.tx);
801
- Object.defineProperty(this, 'tx', {
802
- enumerable: false,
803
- writable: true,
804
- });
805
- }
806
- getInputOutputCounts() {
807
- return {
808
- inputCount: this.tx.ins.length,
809
- outputCount: this.tx.outs.length,
810
- };
811
- }
812
- addInput(input) {
813
- if (input.hash === undefined ||
814
- input.index === undefined ||
815
- (!(input.hash instanceof Uint8Array) && typeof input.hash !== 'string') ||
816
- typeof input.index !== 'number') {
817
- throw new Error('Error adding input.');
818
- }
819
- const hash = (typeof input.hash === 'string' ? reverse(fromHex(input.hash)) : input.hash);
820
- this.tx.addInput(hash, input.index, input.sequence);
821
- }
822
- addOutput(output) {
823
- if (output.script === undefined ||
824
- output.value === undefined ||
825
- !(output.script instanceof Uint8Array) ||
826
- typeof output.value !== 'bigint') {
827
- throw new Error('Error adding output.');
828
- }
829
- this.tx.addOutput(output.script, output.value);
830
- }
831
- toBuffer() {
832
- return this.tx.toBuffer();
833
- }
834
- }
835
- function canFinalize(input, script, scriptType) {
836
- switch (scriptType) {
837
- case 'pubkey':
838
- case 'pubkeyhash':
839
- case 'witnesspubkeyhash':
840
- return hasSigs(1, input.partialSig);
841
- case 'multisig': {
842
- const p2ms = payments.p2ms({
843
- output: script,
844
- });
845
- if (p2ms.m === undefined)
846
- throw new Error('Cannot determine m for multisig');
847
- return hasSigs(p2ms.m, input.partialSig, p2ms.pubkeys);
848
- }
849
- case 'nonstandard':
850
- return true;
851
- default:
852
- return false;
853
- }
854
- }
855
- function hasSigs(neededSigs, partialSig, pubkeys) {
856
- if (!partialSig)
857
- return false;
858
- let sigs;
859
- if (pubkeys) {
860
- sigs = pubkeys
861
- .map((pkey) => {
862
- const pubkey = compressPubkey(pkey);
863
- return partialSig.find((pSig) => equals(pSig.pubkey, pubkey));
864
- })
865
- .filter((v) => !!v);
866
- }
867
- else {
868
- sigs = partialSig;
869
- }
870
- if (sigs.length > neededSigs)
871
- throw new Error('Too many signatures');
872
- return sigs.length === neededSigs;
873
- }
874
- function bip32DerivationIsMine(root) {
875
- return (d) => {
876
- const fingerprint = root.fingerprint instanceof Uint8Array
877
- ? root.fingerprint
878
- : new Uint8Array(root.fingerprint);
879
- if (!equals(d.masterFingerprint, fingerprint))
880
- return false;
881
- const derivedPubkey = root.derivePath(d.path).publicKey;
882
- const pubkey = derivedPubkey instanceof Uint8Array ? derivedPubkey : new Uint8Array(derivedPubkey);
883
- if (!equals(pubkey, d.pubkey))
884
- return false;
885
- return true;
886
- };
887
- }
888
- function checkFees(psbt, cache, opts) {
889
- const feeRate = cache.feeRate || psbt.getFeeRate();
890
- if (!cache.extractedTx)
891
- throw new Error('Transaction not extracted');
892
- const vsize = cache.extractedTx.virtualSize();
893
- const satoshis = feeRate * vsize;
894
- if (feeRate >= opts.maximumFeeRate) {
895
- throw new Error(`Warning: You are paying around ${(satoshis / 1e8).toFixed(8)} in ` +
896
- `fees, which is ${feeRate} satoshi per byte for a transaction ` +
897
- `with a VSize of ${vsize} bytes (segwit counted as 0.25 byte per ` +
898
- `byte). Use setMaximumFeeRate method to raise your threshold, or ` +
899
- `pass true to the first arg of extractTransaction.`);
900
- }
901
- }
902
- function getTxCacheValue(key, name, inputs, c, disableOutputChecks = false) {
903
- if (!inputs.every(isFinalized))
904
- throw new Error(`PSBT must be finalized to calculate ${name}`);
905
- if (key === 'feeRate' && c.feeRate)
906
- return c.feeRate;
907
- if (key === 'fee' && c.fee)
908
- return c.fee;
909
- let tx;
910
- let mustFinalize = true;
911
- if (c.extractedTx) {
912
- tx = c.extractedTx;
913
- mustFinalize = false;
914
- }
915
- else {
916
- tx = c.tx.clone();
917
- }
918
- inputFinalizeGetAmts(inputs, tx, c, mustFinalize, disableOutputChecks);
919
- const value = key === 'feeRate' ? c.feeRate : c.fee;
920
- if (value === undefined)
921
- throw new Error(`Failed to calculate ${name}`);
922
- return value;
923
- }
924
- export function getFinalScripts(inputIndex, input, script, isSegwit, isP2SH, isP2WSH, canRunChecks = true, solution) {
925
- const scriptType = classifyScript(script);
926
- if (!canFinalize(input, script, scriptType) && canRunChecks) {
927
- throw new Error(`Can not finalize input #${inputIndex}`);
928
- }
929
- if (!input.partialSig)
930
- throw new Error('Input missing partial signatures');
931
- return prepareFinalScripts(script, scriptType, input.partialSig, isSegwit, isP2SH, isP2WSH, solution);
932
- }
933
- export function prepareFinalScripts(script, scriptType, partialSig, isSegwit, isP2SH, isP2WSH, solution) {
934
- let finalScriptSig;
935
- let finalScriptWitness;
936
- // Wow, the payments API is very handy
937
- const payment = getPayment(script, scriptType, partialSig);
938
- const p2wsh = !isP2WSH ? null : payments.p2wsh({ redeem: payment });
939
- const p2sh = !isP2SH ? null : payments.p2sh({ redeem: p2wsh || payment });
940
- if (isSegwit) {
941
- if (p2wsh && p2wsh.witness) {
942
- finalScriptWitness = witnessStackToScriptWitness(p2wsh.witness);
943
- }
944
- else if (payment && payment.witness) {
945
- finalScriptWitness = witnessStackToScriptWitness(payment.witness);
946
- }
947
- else {
948
- // nonstandard segwit script
949
- finalScriptWitness = witnessStackToScriptWitness(solution ?? [new Uint8Array([0x00])]);
950
- }
951
- if (p2sh) {
952
- finalScriptSig = p2sh?.input;
953
- }
954
- }
955
- else {
956
- if (p2sh) {
957
- finalScriptSig = p2sh?.input;
958
- }
959
- else {
960
- if (!payment) {
961
- finalScriptSig = (Array.isArray(solution) && solution[0] ? solution[0] : new Uint8Array([0x01]));
962
- }
963
- else {
964
- finalScriptSig = payment.input;
965
- }
966
- }
967
- }
968
- return {
969
- finalScriptSig,
970
- finalScriptWitness,
971
- };
972
- }
973
- function getHashAndSighashType(inputs, inputIndex, pubkey, cache, sighashTypes) {
974
- const input = checkForInput(inputs, inputIndex);
975
- const { hash, sighashType, script } = getHashForSig(inputIndex, input, cache, false, sighashTypes);
976
- checkScriptForPubkey(pubkey, script, 'sign');
977
- return {
978
- hash,
979
- sighashType,
980
- };
981
- }
982
- function getHashForSig(inputIndex, input, cache, forValidate, sighashTypes) {
983
- const unsignedTx = cache.tx;
984
- const sighashType = input.sighashType || Transaction.SIGHASH_ALL;
985
- checkSighashTypeAllowed(sighashType, sighashTypes);
986
- let hash;
987
- let prevout;
988
- if (input.nonWitnessUtxo) {
989
- const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
990
- const prevoutHash = unsignedTx.ins[inputIndex].hash;
991
- const utxoHash = nonWitnessUtxoTx.getHash();
992
- // If a non-witness UTXO is provided, its hash must match the hash specified in the prevout
993
- if (!equals(prevoutHash, utxoHash)) {
994
- throw new Error(`Non-witness UTXO hash for input #${inputIndex} doesn't match the hash specified in the prevout`);
995
- }
996
- const prevoutIndex = unsignedTx.ins[inputIndex].index;
997
- prevout = nonWitnessUtxoTx.outs[prevoutIndex];
998
- }
999
- else if (input.witnessUtxo) {
1000
- prevout = {
1001
- script: input.witnessUtxo.script,
1002
- value: input.witnessUtxo.value,
1003
- };
1004
- }
1005
- else {
1006
- throw new Error('Need a Utxo input item for signing');
1007
- }
1008
- const { meaningfulScript, type } = getMeaningfulScript(prevout.script, inputIndex, 'input', input.redeemScript, input.witnessScript);
1009
- const script = meaningfulScript;
1010
- if (['p2sh-p2wsh', 'p2wsh'].indexOf(type) >= 0) {
1011
- hash = unsignedTx.hashForWitnessV0(inputIndex, script, prevout.value, sighashType);
1012
- }
1013
- else if (isP2WPKH(meaningfulScript)) {
1014
- // P2WPKH uses the P2PKH template for prevoutScript when signing
1015
- const p2pkhPayment = payments.p2pkh({
1016
- hash: meaningfulScript.subarray(2),
1017
- });
1018
- if (!p2pkhPayment.output)
1019
- throw new Error('Unable to create signing script');
1020
- hash = unsignedTx.hashForWitnessV0(inputIndex, p2pkhPayment.output, prevout.value, sighashType);
1021
- }
1022
- else {
1023
- // non-segwit
1024
- if (input.nonWitnessUtxo === undefined && !cache.unsafeSignNonSegwit)
1025
- throw new Error(`Input #${inputIndex} has witnessUtxo but non-segwit script: ` +
1026
- toHex(meaningfulScript));
1027
- if (!forValidate && cache.unsafeSignNonSegwit)
1028
- console.warn('Warning: Signing non-segwit inputs without the full parent transaction ' +
1029
- 'means there is a chance that a miner could feed you incorrect information ' +
1030
- "to trick you into paying large fees. This behavior is the same as Psbt's predecessor " +
1031
- '(TransactionBuilder - now removed) when signing non-segwit scripts. You are not ' +
1032
- 'able to export this Psbt with toBuffer|toBase64|toHex since it is not ' +
1033
- 'BIP174 compliant.\n*********************\nPROCEED WITH CAUTION!\n' +
1034
- '*********************');
1035
- hash = unsignedTx.hashForSignature(inputIndex, script, sighashType);
1036
- }
1037
- return {
1038
- script,
1039
- sighashType,
1040
- hash,
1041
- };
1042
- }
1043
- function getAllTaprootHashesForSig(inputIndex, input, inputs, cache) {
1044
- const allPublicKeys = [];
1045
- if (input.tapInternalKey) {
1046
- const key = getPrevoutTaprootKey(inputIndex, input, cache);
1047
- if (key) {
1048
- allPublicKeys.push(key);
1049
- }
1050
- }
1051
- if (input.tapScriptSig) {
1052
- const tapScriptPubkeys = input.tapScriptSig.map((tss) => tss.pubkey);
1053
- allPublicKeys.push(...tapScriptPubkeys);
1054
- }
1055
- const allHashes = allPublicKeys.map((pubicKey) => getTaprootHashesForSig(inputIndex, input, inputs, pubicKey, cache));
1056
- return allHashes.flat();
1057
- }
1058
- function getPrevoutTaprootKey(inputIndex, input, cache) {
1059
- const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
1060
- return isP2TR(script) ? script.subarray(2, 34) : null;
1061
- }
1062
- function trimTaprootSig(signature) {
1063
- return signature.length === 64 ? signature : signature.subarray(0, 64);
1064
- }
1065
- function getTaprootHashesForSig(inputIndex, input, inputs, pubkey, cache, tapLeafHashToSign, allowedSighashTypes) {
1066
- const unsignedTx = cache.tx;
1067
- const sighashType = input.sighashType || Transaction.SIGHASH_DEFAULT;
1068
- checkSighashTypeAllowed(sighashType, allowedSighashTypes);
1069
- if (!cache.prevOuts) {
1070
- const prevOuts = inputs.map((i, index) => getScriptAndAmountFromUtxo(index, i, cache));
1071
- cache.prevOuts = prevOuts;
1072
- cache.signingScripts = prevOuts.map((o) => o.script);
1073
- cache.values = prevOuts.map((o) => o.value);
1074
- }
1075
- const signingScripts = cache.signingScripts;
1076
- const values = cache.values;
1077
- // Compute taproot hash cache once for all inputs (O(n) -> O(1) per input)
1078
- if (!cache.taprootHashCache) {
1079
- cache.taprootHashCache = unsignedTx.getTaprootHashCache(signingScripts, values);
1080
- }
1081
- const taprootCache = cache.taprootHashCache;
1082
- const hashes = [];
1083
- if (input.tapInternalKey && !tapLeafHashToSign) {
1084
- const outputKey = getPrevoutTaprootKey(inputIndex, input, cache) || new Uint8Array(0);
1085
- if (equals(toXOnly(pubkey), outputKey)) {
1086
- const tapKeyHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType, undefined, undefined, taprootCache);
1087
- hashes.push({ pubkey: pubkey, hash: tapKeyHash });
1088
- }
1089
- }
1090
- const tapLeafHashes = (input.tapLeafScript || [])
1091
- .filter((tapLeaf) => pubkeyInScript(pubkey, tapLeaf.script))
1092
- .map((tapLeaf) => {
1093
- const hash = tapleafHash({
1094
- output: tapLeaf.script,
1095
- version: tapLeaf.leafVersion,
1096
- });
1097
- return Object.assign({ hash }, tapLeaf);
1098
- })
1099
- .filter((tapLeaf) => !tapLeafHashToSign || equals(tapLeafHashToSign, tapLeaf.hash))
1100
- .map((tapLeaf) => {
1101
- const tapScriptHash = unsignedTx.hashForWitnessV1(inputIndex, signingScripts, values, sighashType, tapLeaf.hash, undefined, taprootCache);
1102
- return {
1103
- pubkey: pubkey,
1104
- hash: tapScriptHash,
1105
- leafHash: tapLeaf.hash,
1106
- };
1107
- });
1108
- return hashes.concat(tapLeafHashes);
1109
- }
1110
- function checkSighashTypeAllowed(sighashType, sighashTypes) {
1111
- if (sighashTypes && sighashTypes.indexOf(sighashType) < 0) {
1112
- const str = sighashTypeToString(sighashType);
1113
- throw new Error(`Sighash type is not allowed. Retry the sign method passing the ` +
1114
- `sighashTypes array of whitelisted types. Sighash type: ${str}`);
1115
- }
1116
- }
1117
- function getPayment(script, scriptType, partialSig) {
1118
- const scriptBranded = script;
1119
- switch (scriptType) {
1120
- case 'multisig': {
1121
- const sigs = getSortedSigs(script, partialSig);
1122
- return payments.p2ms({
1123
- output: scriptBranded,
1124
- signatures: sigs,
1125
- });
1126
- }
1127
- case 'pubkey':
1128
- return payments.p2pk({
1129
- output: scriptBranded,
1130
- signature: partialSig[0].signature,
1131
- });
1132
- case 'pubkeyhash':
1133
- return payments.p2pkh({
1134
- output: scriptBranded,
1135
- pubkey: partialSig[0].pubkey,
1136
- signature: partialSig[0].signature,
1137
- });
1138
- case 'witnesspubkeyhash':
1139
- return payments.p2wpkh({
1140
- output: scriptBranded,
1141
- pubkey: partialSig[0].pubkey,
1142
- signature: partialSig[0].signature,
1143
- });
1144
- default:
1145
- throw new Error(`Unknown script type: ${scriptType}`);
1146
- }
1147
- }
1148
- function getScriptFromInput(inputIndex, input, cache) {
1149
- const unsignedTx = cache.tx;
1150
- const res = {
1151
- script: null,
1152
- isSegwit: false,
1153
- isP2SH: false,
1154
- isP2WSH: false,
1155
- };
1156
- res.isP2SH = !!input.redeemScript;
1157
- res.isP2WSH = !!input.witnessScript;
1158
- if (input.witnessScript) {
1159
- res.script = input.witnessScript;
1160
- }
1161
- else if (input.redeemScript) {
1162
- res.script = input.redeemScript;
1163
- }
1164
- else {
1165
- if (input.nonWitnessUtxo) {
1166
- const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
1167
- const prevoutIndex = unsignedTx.ins[inputIndex].index;
1168
- res.script = nonWitnessUtxoTx.outs[prevoutIndex].script;
1169
- }
1170
- else if (input.witnessUtxo) {
1171
- res.script = input.witnessUtxo.script;
1172
- }
1173
- }
1174
- if (input.witnessScript || (res.script && isP2WPKH(res.script))) {
1175
- res.isSegwit = true;
1176
- }
1177
- else {
1178
- try {
1179
- const output = res.script;
1180
- if (!output)
1181
- throw new TypeError('Invalid script for segwit address');
1182
- res.isSegwit = isUnknownSegwitVersion(output);
1183
- }
1184
- catch (e) { }
1185
- }
1186
- return res;
1187
- }
1188
- function getSignersFromHD(inputIndex, inputs, hdKeyPair) {
1189
- const input = checkForInput(inputs, inputIndex);
1190
- if (!input.bip32Derivation || input.bip32Derivation.length === 0) {
1191
- throw new Error('Need bip32Derivation to sign with HD');
1192
- }
1193
- const myDerivations = input.bip32Derivation
1194
- .map((bipDv) => {
1195
- if (equals(bipDv.masterFingerprint, hdKeyPair.fingerprint)) {
1196
- return bipDv;
1197
- }
1198
- else {
1199
- return;
1200
- }
1201
- })
1202
- .filter((v) => !!v);
1203
- if (myDerivations.length === 0) {
1204
- throw new Error('Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint');
1205
- }
1206
- return myDerivations.map((bipDv) => {
1207
- const node = hdKeyPair.derivePath(bipDv.path);
1208
- if (!equals(bipDv.pubkey, node.publicKey)) {
1209
- throw new Error('pubkey did not match bip32Derivation');
1210
- }
1211
- return node;
1212
- });
1213
- }
1214
- function getSortedSigs(script, partialSig) {
1215
- const p2ms = payments.p2ms({ output: script });
1216
- if (!p2ms.pubkeys)
1217
- throw new Error('Cannot extract pubkeys from multisig script');
1218
- // for each pubkey in order of p2ms script
1219
- const result = [];
1220
- for (const pk of p2ms.pubkeys) {
1221
- // filter partialSig array by pubkey being equal
1222
- const matched = partialSig.filter((ps) => {
1223
- return equals(ps.pubkey, pk);
1224
- })[0];
1225
- if (matched) {
1226
- result.push(new Uint8Array(matched.signature));
1227
- }
1228
- }
1229
- return result;
1230
- }
1231
- function addNonWitnessTxCache(cache, input, inputIndex) {
1232
- if (!input.nonWitnessUtxo)
1233
- throw new Error('nonWitnessUtxo is required');
1234
- // Prevent prototype pollution - ensure input is a valid object
1235
- if (input === null || input === Object.prototype) {
1236
- throw new Error('Invalid input object');
1237
- }
1238
- const nonWitnessUtxoBuf = input.nonWitnessUtxo;
1239
- cache.nonWitnessUtxoBufCache[inputIndex] = nonWitnessUtxoBuf;
1240
- cache.nonWitnessUtxoTxCache[inputIndex] = Transaction.fromBuffer(nonWitnessUtxoBuf);
1241
- const self = cache;
1242
- const selfIndex = inputIndex;
1243
- delete input.nonWitnessUtxo;
1244
- // Using Reflect.defineProperty to avoid prototype pollution concerns
1245
- Reflect.defineProperty(input, 'nonWitnessUtxo', {
1246
- enumerable: true,
1247
- get() {
1248
- const buf = self.nonWitnessUtxoBufCache[selfIndex];
1249
- const txCache = self.nonWitnessUtxoTxCache[selfIndex];
1250
- if (buf !== undefined) {
1251
- return buf;
1252
- }
1253
- else {
1254
- const newBuf = txCache.toBuffer();
1255
- self.nonWitnessUtxoBufCache[selfIndex] = newBuf;
1256
- return newBuf;
1257
- }
1258
- },
1259
- set(data) {
1260
- self.nonWitnessUtxoBufCache[selfIndex] = data;
1261
- },
1262
- });
1263
- }
1264
- function inputFinalizeGetAmts(inputs, tx, cache, mustFinalize, disableOutputChecks) {
1265
- let inputAmount = 0n;
1266
- inputs.forEach((input, idx) => {
1267
- if (mustFinalize && input.finalScriptSig)
1268
- tx.ins[idx].script = input.finalScriptSig;
1269
- if (mustFinalize && input.finalScriptWitness) {
1270
- tx.ins[idx].witness = scriptWitnessToWitnessStack(input.finalScriptWitness);
1271
- }
1272
- if (input.witnessUtxo) {
1273
- inputAmount += input.witnessUtxo.value;
1274
- }
1275
- else if (input.nonWitnessUtxo) {
1276
- const nwTx = nonWitnessUtxoTxFromCache(cache, input, idx);
1277
- const vout = tx.ins[idx].index;
1278
- const out = nwTx.outs[vout];
1279
- inputAmount += out.value;
1280
- }
1281
- });
1282
- const outputAmount = tx.outs.reduce((total, o) => total + o.value, 0n);
1283
- const fee = inputAmount - outputAmount;
1284
- if (!disableOutputChecks) {
1285
- if (fee < 0n) {
1286
- throw new Error(`Outputs are spending more than Inputs ${inputAmount} < ${outputAmount}`);
1287
- }
1288
- }
1289
- const bytes = tx.virtualSize();
1290
- cache.fee = Number(fee);
1291
- cache.extractedTx = tx;
1292
- cache.feeRate = Math.floor(Number(fee) / bytes);
1293
- }
1294
- function nonWitnessUtxoTxFromCache(cache, input, inputIndex) {
1295
- const c = cache.nonWitnessUtxoTxCache;
1296
- if (!c[inputIndex]) {
1297
- addNonWitnessTxCache(cache, input, inputIndex);
1298
- }
1299
- return c[inputIndex];
1300
- }
1301
- function getScriptFromUtxo(inputIndex, input, cache) {
1302
- const { script } = getScriptAndAmountFromUtxo(inputIndex, input, cache);
1303
- return script;
1304
- }
1305
- function getScriptAndAmountFromUtxo(inputIndex, input, cache) {
1306
- if (input.witnessUtxo !== undefined) {
1307
- return {
1308
- script: input.witnessUtxo.script,
1309
- value: input.witnessUtxo.value,
1310
- };
1311
- }
1312
- else if (input.nonWitnessUtxo !== undefined) {
1313
- const nonWitnessUtxoTx = nonWitnessUtxoTxFromCache(cache, input, inputIndex);
1314
- const o = nonWitnessUtxoTx.outs[cache.tx.ins[inputIndex].index];
1315
- return { script: o.script, value: o.value };
1316
- }
1317
- else {
1318
- throw new Error("Can't find pubkey in input without Utxo data");
1319
- }
1320
- }
1321
- function pubkeyInInput(pubkey, input, inputIndex, cache) {
1322
- const script = getScriptFromUtxo(inputIndex, input, cache);
1323
- const { meaningfulScript } = getMeaningfulScript(script, inputIndex, 'input', input.redeemScript, input.witnessScript);
1324
- return pubkeyInScript(pubkey, meaningfulScript);
1325
- }
1326
- function pubkeyInOutput(pubkey, output, outputIndex, cache) {
1327
- const script = cache.tx.outs[outputIndex].script;
1328
- const { meaningfulScript } = getMeaningfulScript(script, outputIndex, 'output', output.redeemScript, output.witnessScript);
1329
- return pubkeyInScript(pubkey, meaningfulScript);
1330
- }
1331
- function redeemFromFinalScriptSig(finalScript) {
1332
- if (!finalScript)
1333
- return;
1334
- const decomp = bscript.decompile(finalScript);
1335
- if (!decomp)
1336
- return;
1337
- const lastItem = decomp[decomp.length - 1];
1338
- if (!(lastItem instanceof Uint8Array) || isPubkeyLike(lastItem) || isSigLike(lastItem))
1339
- return;
1340
- const sDecomp = bscript.decompile(lastItem);
1341
- if (!sDecomp)
1342
- return;
1343
- return lastItem;
1344
- }
1345
- function redeemFromFinalWitnessScript(finalScript) {
1346
- if (!finalScript)
1347
- return;
1348
- const decomp = scriptWitnessToWitnessStack(finalScript);
1349
- const lastItem = decomp[decomp.length - 1];
1350
- if (isPubkeyLike(lastItem))
1351
- return;
1352
- const sDecomp = bscript.decompile(lastItem);
1353
- if (!sDecomp)
1354
- return;
1355
- return lastItem;
1356
- }
1357
735
  //# sourceMappingURL=psbt.js.map