ecash-lib 4.14.1 → 4.14.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.
package/src/unsignedTx.ts CHANGED
@@ -215,17 +215,21 @@ export class UnsignedTxInput {
215
215
  ? redeemScript
216
216
  : redeemScript.cutOutCodesep(nCodesep);
217
217
 
218
+ // If an input is signed with SIGHASH_SINGLE but there is no output at
219
+ // the same index, the signature commits to no output at all. Which
220
+ // means such a signature stays valid if the output is swapped, which is
221
+ // a footgun. So don't produce it.
222
+ if (
223
+ sigHashType.outputType == SigHashTypeOutputs.SINGLE &&
224
+ this.inputIdx >= tx.outputs.length
225
+ ) {
226
+ throw new Error(
227
+ 'Invalid usage of SINGLE, input has no corresponding output',
228
+ );
229
+ }
230
+
218
231
  // Sign LEGACY signatures that don't use SIGHASH_FORKID
219
232
  if (sigHashType.variant === SigHashTypeVariant.LEGACY) {
220
- if (
221
- sigHashType.outputType == SigHashTypeOutputs.SINGLE &&
222
- this.inputIdx >= tx.outputs.length
223
- ) {
224
- throw new Error(
225
- 'Invalid usage of SINGLE, input has no corresponding output',
226
- );
227
- }
228
-
229
233
  const writePreimage = (writer: Writer) => {
230
234
  writeLegacyPreimage(
231
235
  writer,
@@ -255,20 +259,15 @@ export class UnsignedTxInput {
255
259
  case SigHashTypeOutputs.NONE:
256
260
  hashOutputs = new Uint8Array(32);
257
261
  break;
258
- case SigHashTypeOutputs.SINGLE:
259
- if (this.inputIdx < tx.outputs.length) {
260
- const output = tx.outputs[this.inputIdx];
261
- const writerOutputLength = new WriterLength();
262
- writeTxOutput(output, writerOutputLength);
263
- const writerOutput = new WriterBytes(
264
- writerOutputLength.length,
265
- );
266
- writeTxOutput(output, writerOutput);
267
- hashOutputs = sha256d(writerOutput.data);
268
- } else {
269
- hashOutputs = new Uint8Array(32);
270
- }
262
+ case SigHashTypeOutputs.SINGLE: {
263
+ const output = tx.outputs[this.inputIdx];
264
+ const writerOutputLength = new WriterLength();
265
+ writeTxOutput(output, writerOutputLength);
266
+ const writerOutput = new WriterBytes(writerOutputLength.length);
267
+ writeTxOutput(output, writerOutput);
268
+ hashOutputs = sha256d(writerOutput.data);
271
269
  break;
270
+ }
272
271
  }
273
272
 
274
273
  const writePreimage = (writer: Writer) => {