ecash-lib 4.13.0 → 4.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +2 -0
  2. package/dist/blindSchnorr.d.ts +27 -0
  3. package/dist/blindSchnorr.d.ts.map +1 -0
  4. package/dist/blindSchnorr.js +206 -0
  5. package/dist/blindSchnorr.js.map +1 -0
  6. package/dist/ecc.d.ts +15 -0
  7. package/dist/ecc.d.ts.map +1 -1
  8. package/dist/ecc.js +36 -1
  9. package/dist/ecc.js.map +1 -1
  10. package/dist/eccScalar.d.ts +12 -0
  11. package/dist/eccScalar.d.ts.map +1 -0
  12. package/dist/eccScalar.js +42 -0
  13. package/dist/eccScalar.js.map +1 -0
  14. package/dist/ffi/ecash_lib_wasm_bg_browser.js +21408 -22085
  15. package/dist/ffi/ecash_lib_wasm_bg_browser.wasm +0 -0
  16. package/dist/ffi/ecash_lib_wasm_bg_browser.wasm.d.ts +5 -0
  17. package/dist/ffi/ecash_lib_wasm_browser.d.ts +39 -0
  18. package/dist/ffi/ecash_lib_wasm_browser.js +135 -0
  19. package/dist/index.d.ts +4 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +4 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/io/array.d.ts +16 -0
  24. package/dist/io/array.d.ts.map +1 -0
  25. package/dist/io/array.js +71 -0
  26. package/dist/io/array.js.map +1 -0
  27. package/dist/payment/action.d.ts +7 -0
  28. package/dist/payment/action.d.ts.map +1 -1
  29. package/dist/payment/action.js.map +1 -1
  30. package/dist/pedersen.d.ts +62 -0
  31. package/dist/pedersen.d.ts.map +1 -0
  32. package/dist/pedersen.js +257 -0
  33. package/dist/pedersen.js.map +1 -0
  34. package/dist/script.d.ts.map +1 -1
  35. package/dist/script.js +13 -0
  36. package/dist/script.js.map +1 -1
  37. package/package.json +3 -3
  38. package/src/blindSchnorr.ts +241 -0
  39. package/src/ecc.ts +61 -1
  40. package/src/eccScalar.ts +41 -0
  41. package/src/ffi/ecash_lib_wasm_bg_browser.js +21408 -22085
  42. package/src/ffi/ecash_lib_wasm_bg_browser.wasm +0 -0
  43. package/src/ffi/ecash_lib_wasm_bg_browser.wasm.d.ts +5 -0
  44. package/src/ffi/ecash_lib_wasm_browser.d.ts +39 -0
  45. package/src/ffi/ecash_lib_wasm_browser.js +135 -0
  46. package/src/index.ts +4 -0
  47. package/src/io/array.ts +70 -0
  48. package/src/payment/action.ts +7 -0
  49. package/src/pedersen.ts +280 -0
  50. package/src/script.ts +23 -0
@@ -9,7 +9,12 @@ export function ecc_schnorrSign(a: number, b: number, c: number, d: number, e: n
9
9
  export function ecc_schnorrVerify(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number): void;
10
10
  export function ecc_isValidSeckey(a: number, b: number, c: number): number;
11
11
  export function ecc_seckeyAdd(a: number, b: number, c: number, d: number, e: number, f: number): void;
12
+ export function ecc_seckeyMul(a: number, b: number, c: number, d: number, e: number, f: number): void;
13
+ export function ecc_seckeyNegate(a: number, b: number, c: number, d: number): void;
12
14
  export function ecc_pubkeyAdd(a: number, b: number, c: number, d: number, e: number, f: number): void;
15
+ export function ecc_pubkeyMul(a: number, b: number, c: number, d: number, e: number, f: number): void;
16
+ export function ecc_pubkeyCombine(a: number, b: number, c: number, d: number, e: number, f: number): void;
17
+ export function ecc_uncompressPk(a: number, b: number, c: number, d: number): void;
13
18
  export function ecc_signRecoverable(a: number, b: number, c: number, d: number, e: number, f: number): void;
14
19
  export function ecc_recoverSig(a: number, b: number, c: number, d: number, e: number, f: number): void;
15
20
  export function __wbg_ecc_free(a: number): void;
@@ -99,6 +99,19 @@ export class Ecc {
99
99
  */
100
100
  seckeyAdd(a: Uint8Array, b: Uint8Array): Uint8Array;
101
101
  /**
102
+ * Multiply a secret key by a scalar (a * b).
103
+ * @param {Uint8Array} a
104
+ * @param {Uint8Array} b
105
+ * @returns {Uint8Array}
106
+ */
107
+ seckeyMul(a: Uint8Array, b: Uint8Array): Uint8Array;
108
+ /**
109
+ * Negate a secret key (−a mod n).
110
+ * @param {Uint8Array} a
111
+ * @returns {Uint8Array}
112
+ */
113
+ seckeyNegate(a: Uint8Array): Uint8Array;
114
+ /**
102
115
  * Add a scalar to a public key (adding G*b).
103
116
  * @param {Uint8Array} a
104
117
  * @param {Uint8Array} b
@@ -106,6 +119,27 @@ export class Ecc {
106
119
  */
107
120
  pubkeyAdd(a: Uint8Array, b: Uint8Array): Uint8Array;
108
121
  /**
122
+ * Multiply a public key by a scalar (P * b).
123
+ * @param {Uint8Array} a
124
+ * @param {Uint8Array} b
125
+ * @returns {Uint8Array}
126
+ */
127
+ pubkeyMul(a: Uint8Array, b: Uint8Array): Uint8Array;
128
+ /**
129
+ * Add two public keys (P + Q). Errors if the sum is the point at infinity.
130
+ * @param {Uint8Array} a
131
+ * @param {Uint8Array} b
132
+ * @returns {Uint8Array}
133
+ */
134
+ pubkeyCombine(a: Uint8Array, b: Uint8Array): Uint8Array;
135
+ /**
136
+ * Decompress a compressed public key to 65-byte uncompressed form
137
+ * (0x04||x||y).
138
+ * @param {Uint8Array} pk
139
+ * @returns {Uint8Array}
140
+ */
141
+ uncompressPk(pk: Uint8Array): Uint8Array;
142
+ /**
109
143
  * Create a compact ECDSA signature (65 bytes), which allows reconstructing
110
144
  * the used public key.
111
145
  * The format is one header byte, followed by two times 32 bytes for the
@@ -191,7 +225,12 @@ export interface InitOutput {
191
225
  readonly ecc_schnorrVerify: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => void;
192
226
  readonly ecc_isValidSeckey: (a: number, b: number, c: number) => number;
193
227
  readonly ecc_seckeyAdd: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
228
+ readonly ecc_seckeyMul: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
229
+ readonly ecc_seckeyNegate: (a: number, b: number, c: number, d: number) => void;
194
230
  readonly ecc_pubkeyAdd: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
231
+ readonly ecc_pubkeyMul: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
232
+ readonly ecc_pubkeyCombine: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
233
+ readonly ecc_uncompressPk: (a: number, b: number, c: number, d: number) => void;
195
234
  readonly ecc_signRecoverable: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
196
235
  readonly ecc_recoverSig: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
197
236
  readonly __wbg_ecc_free: (a: number) => void;
@@ -467,6 +467,59 @@ export class Ecc {
467
467
  }
468
468
  }
469
469
  /**
470
+ * Multiply a secret key by a scalar (a * b).
471
+ * @param {Uint8Array} a
472
+ * @param {Uint8Array} b
473
+ * @returns {Uint8Array}
474
+ */
475
+ seckeyMul(a, b) {
476
+ try {
477
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
478
+ const ptr0 = passArray8ToWasm0(a, wasm.__wbindgen_export_0);
479
+ const len0 = WASM_VECTOR_LEN;
480
+ const ptr1 = passArray8ToWasm0(b, wasm.__wbindgen_export_0);
481
+ const len1 = WASM_VECTOR_LEN;
482
+ wasm.ecc_seckeyMul(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
483
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
484
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
485
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
486
+ var r3 = getInt32Memory0()[retptr / 4 + 3];
487
+ if (r3) {
488
+ throw takeObject(r2);
489
+ }
490
+ var v3 = getArrayU8FromWasm0(r0, r1).slice();
491
+ wasm.__wbindgen_export_1(r0, r1 * 1, 1);
492
+ return v3;
493
+ } finally {
494
+ wasm.__wbindgen_add_to_stack_pointer(16);
495
+ }
496
+ }
497
+ /**
498
+ * Negate a secret key (−a mod n).
499
+ * @param {Uint8Array} a
500
+ * @returns {Uint8Array}
501
+ */
502
+ seckeyNegate(a) {
503
+ try {
504
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
505
+ const ptr0 = passArray8ToWasm0(a, wasm.__wbindgen_export_0);
506
+ const len0 = WASM_VECTOR_LEN;
507
+ wasm.ecc_seckeyNegate(retptr, this.__wbg_ptr, ptr0, len0);
508
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
509
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
510
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
511
+ var r3 = getInt32Memory0()[retptr / 4 + 3];
512
+ if (r3) {
513
+ throw takeObject(r2);
514
+ }
515
+ var v2 = getArrayU8FromWasm0(r0, r1).slice();
516
+ wasm.__wbindgen_export_1(r0, r1 * 1, 1);
517
+ return v2;
518
+ } finally {
519
+ wasm.__wbindgen_add_to_stack_pointer(16);
520
+ }
521
+ }
522
+ /**
470
523
  * Add a scalar to a public key (adding G*b).
471
524
  * @param {Uint8Array} a
472
525
  * @param {Uint8Array} b
@@ -495,6 +548,88 @@ export class Ecc {
495
548
  }
496
549
  }
497
550
  /**
551
+ * Multiply a public key by a scalar (P * b).
552
+ * @param {Uint8Array} a
553
+ * @param {Uint8Array} b
554
+ * @returns {Uint8Array}
555
+ */
556
+ pubkeyMul(a, b) {
557
+ try {
558
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
559
+ const ptr0 = passArray8ToWasm0(a, wasm.__wbindgen_export_0);
560
+ const len0 = WASM_VECTOR_LEN;
561
+ const ptr1 = passArray8ToWasm0(b, wasm.__wbindgen_export_0);
562
+ const len1 = WASM_VECTOR_LEN;
563
+ wasm.ecc_pubkeyMul(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
564
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
565
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
566
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
567
+ var r3 = getInt32Memory0()[retptr / 4 + 3];
568
+ if (r3) {
569
+ throw takeObject(r2);
570
+ }
571
+ var v3 = getArrayU8FromWasm0(r0, r1).slice();
572
+ wasm.__wbindgen_export_1(r0, r1 * 1, 1);
573
+ return v3;
574
+ } finally {
575
+ wasm.__wbindgen_add_to_stack_pointer(16);
576
+ }
577
+ }
578
+ /**
579
+ * Add two public keys (P + Q). Errors if the sum is the point at infinity.
580
+ * @param {Uint8Array} a
581
+ * @param {Uint8Array} b
582
+ * @returns {Uint8Array}
583
+ */
584
+ pubkeyCombine(a, b) {
585
+ try {
586
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
587
+ const ptr0 = passArray8ToWasm0(a, wasm.__wbindgen_export_0);
588
+ const len0 = WASM_VECTOR_LEN;
589
+ const ptr1 = passArray8ToWasm0(b, wasm.__wbindgen_export_0);
590
+ const len1 = WASM_VECTOR_LEN;
591
+ wasm.ecc_pubkeyCombine(retptr, this.__wbg_ptr, ptr0, len0, ptr1, len1);
592
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
593
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
594
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
595
+ var r3 = getInt32Memory0()[retptr / 4 + 3];
596
+ if (r3) {
597
+ throw takeObject(r2);
598
+ }
599
+ var v3 = getArrayU8FromWasm0(r0, r1).slice();
600
+ wasm.__wbindgen_export_1(r0, r1 * 1, 1);
601
+ return v3;
602
+ } finally {
603
+ wasm.__wbindgen_add_to_stack_pointer(16);
604
+ }
605
+ }
606
+ /**
607
+ * Decompress a compressed public key to 65-byte uncompressed form
608
+ * (0x04||x||y).
609
+ * @param {Uint8Array} pk
610
+ * @returns {Uint8Array}
611
+ */
612
+ uncompressPk(pk) {
613
+ try {
614
+ const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
615
+ const ptr0 = passArray8ToWasm0(pk, wasm.__wbindgen_export_0);
616
+ const len0 = WASM_VECTOR_LEN;
617
+ wasm.ecc_uncompressPk(retptr, this.__wbg_ptr, ptr0, len0);
618
+ var r0 = getInt32Memory0()[retptr / 4 + 0];
619
+ var r1 = getInt32Memory0()[retptr / 4 + 1];
620
+ var r2 = getInt32Memory0()[retptr / 4 + 2];
621
+ var r3 = getInt32Memory0()[retptr / 4 + 3];
622
+ if (r3) {
623
+ throw takeObject(r2);
624
+ }
625
+ var v2 = getArrayU8FromWasm0(r0, r1).slice();
626
+ wasm.__wbindgen_export_1(r0, r1 * 1, 1);
627
+ return v2;
628
+ } finally {
629
+ wasm.__wbindgen_add_to_stack_pointer(16);
630
+ }
631
+ }
632
+ /**
498
633
  * Create a compact ECDSA signature (65 bytes), which allows reconstructing
499
634
  * the used public key.
500
635
  * The format is one header byte, followed by two times 32 bytes for the
package/src/index.ts CHANGED
@@ -6,6 +6,9 @@ import './initWasm.js';
6
6
 
7
7
  export * from './consts.js';
8
8
  export * from './ecc.js';
9
+ export * from './eccScalar.js';
10
+ export * from './blindSchnorr.js';
11
+ export * from './pedersen.js';
9
12
  export * from './hash.js';
10
13
  export * from './op.js';
11
14
  export * from './opcode.js';
@@ -20,6 +23,7 @@ export * from './psbt.js';
20
23
  export * from './signatories.js';
21
24
  export * from './txBuilder.js';
22
25
  export * from './unsignedTx.js';
26
+ export * from './io/array.js';
23
27
  export * from './io/bytes.js';
24
28
  export * from './io/hex.js';
25
29
  export * from './io/int.js';
@@ -0,0 +1,70 @@
1
+ // Copyright (c) 2026 The Bitcoin developers
2
+ // Distributed under the MIT software license, see the accompanying
3
+ // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
+
5
+ /**
6
+ * Byte-array equality without early-exit in the compare loop.
7
+ * Not a substitute for `crypto.timingSafeEqual` where available; JS cannot
8
+ * give strict constant-time guarantees (GC, etc.).
9
+ */
10
+ export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
11
+ const len = a.length;
12
+ if (len !== b.length) {
13
+ return false;
14
+ }
15
+ let diff = 0;
16
+ for (let i = 0; i < len; i++) {
17
+ diff |= a[i]! ^ b[i]!;
18
+ }
19
+ return diff === 0;
20
+ }
21
+
22
+ /** Overwrite a buffer with zeros (best-effort secret clearing). */
23
+ export function zeroBytes(buf: Uint8Array): void {
24
+ buf.fill(0);
25
+ }
26
+
27
+ export function concatBytes(...parts: Uint8Array[]): Uint8Array {
28
+ let len = 0;
29
+ for (const p of parts) {
30
+ len += p.length;
31
+ }
32
+ const out = new Uint8Array(len);
33
+ let offset = 0;
34
+ for (const p of parts) {
35
+ out.set(p, offset);
36
+ offset += p.length;
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /** Interpret bytes as a big-endian unsigned integer. */
42
+ export function bytesToScalar(buf: Uint8Array): bigint {
43
+ let n = 0n;
44
+ for (const b of buf) {
45
+ n = (n << 8n) + BigInt(b);
46
+ }
47
+ return n;
48
+ }
49
+
50
+ /** Big-endian uint32. Throws if `n` is not an integer in [0, 2^32). */
51
+ export function u32ToBe(n: number): Uint8Array {
52
+ if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) {
53
+ throw new Error(`u32ToBe: expected integer in [0, 2^32), got ${n}`);
54
+ }
55
+ const out = new Uint8Array(4);
56
+ new DataView(out.buffer).setUint32(0, n, false);
57
+ return out;
58
+ }
59
+
60
+ /** Big-endian uint64. Throws if `n` is not an integer in [0, 2^64). */
61
+ export function bigintToU64Be(n: bigint): Uint8Array {
62
+ if (n < 0n || n > 0xffffffffffffffffn) {
63
+ throw new Error(
64
+ `bigintToU64Be: expected integer in [0, 2^64), got ${n}`,
65
+ );
66
+ }
67
+ const out = new Uint8Array(8);
68
+ new DataView(out.buffer).setBigUint64(0, n, false);
69
+ return out;
70
+ }
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { GenesisInfo, TokenType } from '../token/common.js';
6
6
  import { PaymentOutput } from './output.js';
7
+ import type { Script } from '../script.js';
7
8
  import { OutPoint } from '../tx.js';
8
9
 
9
10
  /**
@@ -70,6 +71,12 @@ export interface Action {
70
71
  * token send txs, as we also want these to be deterministic
71
72
  */
72
73
  noChange?: boolean;
74
+ /**
75
+ * Script that receives XEC change instead of the spending wallet.
76
+ * Ignored when `noChange` is true. Cannot be combined with `noChange`.
77
+ * Intermediate chained-tx fuel still goes to the spender.
78
+ */
79
+ changeScript?: Script;
73
80
  /** Dust sats associated with this tx, defaults to DEFAULT_DUST_SATS */
74
81
  dustSats?: bigint;
75
82
  /** Fee per kb to be used for tx(s) of this action, defaults to DEFAULT_FEE_SATS_PER_KB */
@@ -0,0 +1,280 @@
1
+ // Copyright (c) 2026 The Bitcoin developers
2
+ // Distributed under the MIT software license, see the accompanying
3
+ // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
+
5
+ import { Ecc } from './ecc.js';
6
+ import {
7
+ CURVE_ORDER,
8
+ modCurveOrder,
9
+ randomScalarBytes,
10
+ scalarToBytes,
11
+ } from './eccScalar.js';
12
+ import { bytesToScalar, equalBytes, zeroBytes } from './io/array.js';
13
+ import { fromHex } from './io/hex.js';
14
+
15
+ const ecc = new Ecc();
16
+ const SCALAR_ONE = fromHex(
17
+ '0000000000000000000000000000000000000000000000000000000000000001',
18
+ );
19
+
20
+ export class NonceRangeError extends Error {
21
+ constructor(message = 'Invalid Pedersen nonce') {
22
+ super(message);
23
+ this.name = 'NonceRangeError';
24
+ }
25
+ }
26
+
27
+ export class InsecureHPoint extends Error {
28
+ constructor(message = 'InsecureHPoint') {
29
+ super(message);
30
+ this.name = 'InsecureHPoint';
31
+ }
32
+ }
33
+
34
+ /** Sum of commitment points is the point at infinity (cannot be serialized). */
35
+ export class ResultAtInfinity extends Error {
36
+ constructor(message = 'ResultAtInfinity') {
37
+ super(message);
38
+ this.name = 'ResultAtInfinity';
39
+ }
40
+ }
41
+
42
+ export interface PedersenCommitment {
43
+ amount: bigint;
44
+ /** 32-byte nonce scalar (may be zero for aggregate openings) */
45
+ nonce: Uint8Array;
46
+ /** Compressed (33-byte) commitment point */
47
+ point: Uint8Array;
48
+ /** Uncompressed (65-byte) commitment point */
49
+ pointUncompressed: Uint8Array;
50
+ }
51
+
52
+ /**
53
+ * Pedersen setup for commitments C = nonce*G + amount*H (same algebra as
54
+ * Electrum ABC).
55
+ *
56
+ * Rejects insecure H with a known discrete log vs G:
57
+ * - H = -G (HG at infinity), same as Electrum
58
+ * - H = G (then C = (nonce+amount)G and binding is lost)
59
+ *
60
+ * Callers supply a nothing-up-my-sleeve H (Electrum/ALP fixed domain strings).
61
+ * This API does not derive H itself.
62
+ *
63
+ * Implementation detail: we store H and H+G and evaluate the equivalent form
64
+ * C = (a - k)*H + k*(H + G)
65
+ * so the amount scalar multiply is blinded by the nonce (see Electrum
66
+ * `Commitment._calc_initial`). Expand to recover C = k*G + a*H.
67
+ *
68
+ * Fresh nonces from {@link commit} are in [1, n). A zero nonce is accepted when
69
+ * supplied explicitly (e.g. aggregate openings where nonces cancel): then
70
+ * C = amount*H. The (amount, nonce) = (0, 0) opening is the identity and cannot
71
+ * be serialized as a point — use {@link verifyCommitmentSum} for that case.
72
+ */
73
+ export class PedersenSetup {
74
+ /** Compressed H */
75
+ readonly H: Uint8Array;
76
+ /** Compressed H+G */
77
+ readonly HG: Uint8Array;
78
+
79
+ constructor(H: Uint8Array) {
80
+ // Accept compressed (33) or uncompressed (65), same as Electrum ABC.
81
+ let compressed: Uint8Array;
82
+ if (H.length === 33) {
83
+ try {
84
+ ecc.uncompressPk(H); // validate
85
+ } catch {
86
+ throw new Error('H could not be parsed');
87
+ }
88
+ compressed = H;
89
+ } else if (H.length === 65 && H[0] === 0x04) {
90
+ try {
91
+ compressed = ecc.compressPk(H);
92
+ } catch {
93
+ throw new Error('H could not be parsed');
94
+ }
95
+ } else {
96
+ throw new Error('H could not be parsed');
97
+ }
98
+ if (equalBytes(compressed, ecc.derivePubkey(SCALAR_ONE))) {
99
+ throw new InsecureHPoint('H = G');
100
+ }
101
+ try {
102
+ // HG = H + G. Fails if H = -G (result at infinity).
103
+ this.HG = ecc.pubkeyAdd(compressed, SCALAR_ONE);
104
+ } catch {
105
+ throw new InsecureHPoint();
106
+ }
107
+ this.H = new Uint8Array(compressed);
108
+ }
109
+
110
+ commit(amount: bigint, nonce?: Uint8Array): PedersenCommitment {
111
+ const amountMod = modCurveOrder(amount);
112
+ const amountBytes = scalarToBytes(amountMod);
113
+
114
+ let k: Uint8Array;
115
+ if (nonce === undefined) {
116
+ // Fresh nonce in [1, n) — never zero.
117
+ k = randomScalarBytes();
118
+ } else {
119
+ if (nonce.length !== 32) {
120
+ throw new NonceRangeError('nonce must be 32 bytes');
121
+ }
122
+ const kn = bytesToScalar(nonce);
123
+ if (kn < 0n || kn >= CURVE_ORDER) {
124
+ throw new NonceRangeError();
125
+ }
126
+ k = new Uint8Array(nonce);
127
+
128
+ // Zero nonce: C = a*H (aggregate opening when nonces cancel).
129
+ // For independent random nonces this is ~2^-256 unlikely; it is
130
+ // expected when deliberately summing complementary nonces.
131
+ // libsecp rejects 0*P, so this path is explicit.
132
+ if (kn === 0n) {
133
+ if (amountMod === 0n) {
134
+ throw new ResultAtInfinity(
135
+ 'commitment at infinity (zero amount and nonce)',
136
+ );
137
+ }
138
+ const point = ecc.pubkeyMul(this.H, amountBytes);
139
+ return {
140
+ amount,
141
+ nonce: k,
142
+ point,
143
+ pointUncompressed: ecc.uncompressPk(point),
144
+ };
145
+ }
146
+ }
147
+
148
+ // Electrum amount blinding: C = (a-k)*H + k*(H+G).
149
+ const kHG = ecc.pubkeyMul(this.HG, k);
150
+ let point = kHG;
151
+ const negK = ecc.seckeyNegate(k);
152
+ let aMinusK: Uint8Array | undefined;
153
+ try {
154
+ // seckeyAdd = secp256k1 seckey tweak add: (a + b) mod n.
155
+ // Here: (a - k) mod n. Throws when the result is 0 (invalid seckey),
156
+ // i.e. when (a - k) ≡ 0 (mod n) — Electrum's a_k == 0 fast path.
157
+ // For uniform random k that is ~2^-256 unlikely (a ≡ k mod n).
158
+ aMinusK = ecc.seckeyAdd(negK, amountBytes);
159
+ } catch {
160
+ // (a - k) ≡ 0 (mod n): C = k*(H+G) only (point already kHG).
161
+ } finally {
162
+ zeroBytes(negK);
163
+ }
164
+
165
+ if (aMinusK !== undefined) {
166
+ try {
167
+ const akH = ecc.pubkeyMul(this.H, aMinusK);
168
+ try {
169
+ point = ecc.pubkeyCombine(kHG, akH);
170
+ } catch {
171
+ // Point at infinity ⇒ discrete log of H is known.
172
+ throw new InsecureHPoint();
173
+ }
174
+ } finally {
175
+ zeroBytes(aMinusK);
176
+ }
177
+ }
178
+
179
+ return {
180
+ amount,
181
+ nonce: k,
182
+ point,
183
+ pointUncompressed: ecc.uncompressPk(point),
184
+ };
185
+ }
186
+ }
187
+
188
+ /** Compress and validate a commitment point (33-byte compressed or 65-byte). */
189
+ function normalizeCommitmentPoint(p: Uint8Array): Uint8Array {
190
+ if (p.length === 65) {
191
+ if (p[0] !== 0x04) {
192
+ throw new Error('Invalid uncompressed commitment point');
193
+ }
194
+ const compressed = ecc.compressPk(p);
195
+ // compressPk only packs bytes; require a valid curve point.
196
+ ecc.uncompressPk(compressed);
197
+ return compressed;
198
+ }
199
+ if (p.length === 33) {
200
+ if (p[0] !== 0x02 && p[0] !== 0x03) {
201
+ throw new Error('Invalid compressed commitment point');
202
+ }
203
+ ecc.uncompressPk(p);
204
+ return p;
205
+ }
206
+ throw new Error('Invalid commitment point length');
207
+ }
208
+
209
+ export function addCommitmentPoints(points: Uint8Array[]): Uint8Array {
210
+ if (points.length === 0) {
211
+ throw new Error('No points to add');
212
+ }
213
+ // Validate each point before combining so malformed input is not mistaken
214
+ // for the point at infinity.
215
+ const compressed = points.map(normalizeCommitmentPoint);
216
+ let sum: Uint8Array;
217
+ try {
218
+ sum = compressed
219
+ .slice(1)
220
+ .reduce((acc, p) => ecc.pubkeyCombine(acc, p), compressed[0]);
221
+ } catch {
222
+ throw new ResultAtInfinity();
223
+ }
224
+ return ecc.uncompressPk(sum);
225
+ }
226
+
227
+ /**
228
+ * Verify that commitments open to (totalAmount, totalNonce).
229
+ * Returns a boolean (does not throw for the identity aggregate): when the
230
+ * points sum to infinity, the only valid opening is amount ≡ 0 and nonce = 0.
231
+ * Ill-formed commitments or nonce always return false (never true).
232
+ */
233
+ export function verifyCommitmentSum(
234
+ setup: PedersenSetup,
235
+ commitments: Uint8Array[],
236
+ totalAmount: bigint,
237
+ totalNonce: Uint8Array,
238
+ ): boolean {
239
+ if (totalNonce.length !== 32) {
240
+ return false;
241
+ }
242
+ const amountMod = modCurveOrder(totalAmount);
243
+ const nonceIsZero = bytesToScalar(totalNonce) === 0n;
244
+
245
+ let sum: Uint8Array;
246
+ try {
247
+ sum = addCommitmentPoints(commitments);
248
+ } catch (e) {
249
+ // Genuine infinity only after points were validated.
250
+ if (e instanceof ResultAtInfinity) {
251
+ return nonceIsZero && amountMod === 0n;
252
+ }
253
+ return false;
254
+ }
255
+
256
+ // Claimed (0, 0) opening but the sum is a concrete point.
257
+ if (nonceIsZero && amountMod === 0n) {
258
+ return false;
259
+ }
260
+
261
+ try {
262
+ const expected = setup.commit(totalAmount, totalNonce);
263
+ return equalBytes(sum, expected.pointUncompressed);
264
+ } catch {
265
+ return false;
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Sum two 32-byte seckeys/nonces mod n (wasm seckeyAdd).
271
+ * When (a + b) ≡ 0 (mod n), seckeyAdd throws — return canonical zero.
272
+ */
273
+ export function addScalars(a: Uint8Array, b: Uint8Array): Uint8Array {
274
+ try {
275
+ return ecc.seckeyAdd(a, b);
276
+ } catch {
277
+ // (a + b) ≡ 0 (mod n)
278
+ return new Uint8Array(32);
279
+ }
280
+ }
package/src/script.ts CHANGED
@@ -399,6 +399,29 @@ export class Script {
399
399
  `Invalid multisig redeem script: expected ${numPubkeys} pubkeys, got ${pubkeys.length}`,
400
400
  );
401
401
  }
402
+ if (
403
+ !Number.isSafeInteger(numSignatures) ||
404
+ !Number.isSafeInteger(numPubkeys)
405
+ ) {
406
+ throw new Error(
407
+ `Invalid multisig redeem script: m and n must be safe integers (got m=${numSignatures}, n=${numPubkeys})`,
408
+ );
409
+ }
410
+ if (numSignatures < 1 || numPubkeys < 1) {
411
+ throw new Error(
412
+ `Invalid multisig redeem script: m and n must be >= 1 (got m=${numSignatures}, n=${numPubkeys})`,
413
+ );
414
+ }
415
+ if (numSignatures > numPubkeys) {
416
+ throw new Error(
417
+ `Invalid multisig redeem script: m must be <= n (got ${numSignatures} of ${numPubkeys})`,
418
+ );
419
+ }
420
+ if (numPubkeys > MAX_PUBKEYS_PER_MULTISIG) {
421
+ throw new Error(
422
+ `Invalid multisig redeem script: n must be <= ${MAX_PUBKEYS_PER_MULTISIG} (got ${numPubkeys})`,
423
+ );
424
+ }
402
425
  return { numSignatures, numPubkeys, pubkeys };
403
426
  }
404
427