@scure/btc-signer 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/musig2.js CHANGED
@@ -6,8 +6,17 @@ import { compareBytes, hasEven } from "./utils.js";
6
6
  /**
7
7
  * Represents an error indicating an invalid contribution from a signer.
8
8
  * This allows pointing out which participant is malicious and what specifically is wrong.
9
+ * @param idx - signer index with the invalid contribution
10
+ * @param m - error message
11
+ * @example
12
+ * Create an error that points to the participant who sent invalid data.
13
+ * ```ts
14
+ * new InvalidContributionErr(0, 'pubkey');
15
+ * ```
9
16
  */
10
17
  export class InvalidContributionErr extends Error {
18
+ // BIP327 identifiable aborts blame exactly one signer by participant index in the
19
+ // caller's session ordering, so callers interpret idx using the same ordering they signed with.
11
20
  idx; // Indice of participant
12
21
  constructor(idx, m) {
13
22
  super(m);
@@ -15,65 +24,136 @@ export class InvalidContributionErr extends Error {
15
24
  }
16
25
  }
17
26
  // Utils
18
- const { taggedHash, pointToBytes } = schnorr.utils;
19
- const Point = secp256k1.Point;
20
- const Fn = Point.Fn;
21
- const PUBKEY_LEN = secp256k1.lengths.publicKey;
22
- const ZERO = new Uint8Array(PUBKEY_LEN); // Compressed zero point
27
+ // MuSig2 reuses BIP340 tagged hashing, i.e. SHA256(SHA256(tag) || SHA256(tag) || msg...),
28
+ // for all of the domain-separated hashes below (KeyAgg list, noncecoef, challenge, aux, ...).
29
+ const taggedHash = /* @__PURE__ */ (() => schnorr.utils.taggedHash)();
30
+ // BIP327 uses xbytes(P) = bytes(32, x(P)) for aggregate keys, nonce/challenge hashes,
31
+ // and final signatures, so this alias is intentionally x-only instead of 33-byte SEC1.
32
+ const pointToBytes = /* @__PURE__ */ (() => schnorr.utils.pointToBytes)();
33
+ // MuSig2 keeps aggregate keys/nonces as full secp256k1 points so it can represent infinity
34
+ // and inspect parity before exporting compressed or x-only encodings at the API boundaries.
35
+ const Point = /* @__PURE__ */ (() => secp256k1.Point)();
36
+ // MuSig2 scalars live in Z_n with fixed 32-byte encodings: strict inputs like secret keys
37
+ // use Fn.fromBytes(...), tweak bytes allow 0 per ApplyTweak, and hash-derived values are
38
+ // intentionally reduced mod n.
39
+ const Fn = /* @__PURE__ */ (() => Point.Fn)();
40
+ // BIP327 signer keys are plain compressed pubkeys (33 bytes); only aggregate exports switch
41
+ // to BIP340's 32-byte x-only format, so the internal input length stays on secp256k1.publicKey.
42
+ const PUBKEY_LEN = /* @__PURE__ */ (() => secp256k1.lengths.publicKey)();
43
+ // BIP327 uses bytes(33, 0) both as cbytes_ext(Point.ZERO) for infinity and as GetSecondKey's
44
+ // "no second distinct key" sentinel, so this all-zero compressed slot is intentionally out-of-band.
45
+ const ZERO = /* @__PURE__ */ new Uint8Array(PUBKEY_LEN); // Compressed zero point
23
46
  // Encoding
24
47
  // TODO: re-use in PSBT?
25
- const compressed = P.apply(P.bytes(33), {
48
+ // This is BIP327's cbytes_ext/cpoint_ext adapter: normal points stay in compressed SEC1,
49
+ // while Point.ZERO maps to bytes(33, 0) as the out-of-band infinity sentinel for aggnonce.
50
+ const compressed = /* @__PURE__ */ (() => P.apply(P.bytes(33), {
26
51
  decode: (p) => (isZero(p) ? ZERO : p.toBytes(true)),
27
52
  encode: (b) => (equalBytes(b, ZERO) ? Point.ZERO : Point.fromBytes(b)),
28
- });
29
- const scalar = P.validate(P.U256BE, (n) => {
53
+ }))();
54
+ // This coder is only for stored secnonce limbs k1/k2, which BIP327 requires to be
55
+ // nonzero scalars in [1, n); tweak scalars use different validation because 0 is allowed there.
56
+ const scalar = /* @__PURE__ */ (() => P.validate(P.U256BE, (n) => {
30
57
  aInRange('n', n, 1n, Fn.ORDER);
31
58
  return n;
32
- });
33
- const PubNonce = P.struct({ R1: compressed, R2: compressed });
34
- const SecretNonce = P.struct({ k1: scalar, k2: scalar, publicKey: P.bytes(PUBKEY_LEN) });
59
+ }))();
60
+ // Shared for both per-signer pubnonce bytes and aggregate aggnonce bytes. Because it accepts
61
+ // the BIP327 infinity sentinel, so individual pubnonce callers still need
62
+ // an explicit zero-point check.
63
+ const PubNonce = /* @__PURE__ */ (() => P.struct({ R1: compressed, R2: compressed }))();
64
+ // BIP327 stores secnonce as k1 || k2 || pk so Sign can reject reused or
65
+ // invalid nonce limbs and detect when the caller pairs the nonce with a
66
+ // different individual public key than NonceGen used.
67
+ const SecretNonce = /* @__PURE__ */ (() => P.struct({
68
+ k1: scalar,
69
+ k2: scalar,
70
+ publicKey: P.bytes(PUBKEY_LEN),
71
+ }))();
35
72
  function abytesOptional(b, ...lengths) {
73
+ // Optional-byte helper: exact-length checks only happen when callers pass them explicitly.
36
74
  if (b !== undefined)
37
75
  abytes(b, ...lengths);
38
76
  }
39
77
  function abytesArray(lst, ...lengths) {
78
+ // Element-shape helper only: callers still enforce list-size rules like BIP327's 0 < u < 2^32.
40
79
  if (!Array.isArray(lst))
41
- throw new Error('expected array');
80
+ throw new TypeError('expected array');
42
81
  lst.forEach((i) => abytes(i, ...lengths));
43
82
  }
44
83
  function aXonly(lst) {
84
+ // BIP327 tweak modes are strict booleans; callers should run this before
85
+ // branching on isXonly values because plain JS truthiness would accept invalid inputs.
45
86
  if (!Array.isArray(lst))
46
- throw new Error('expected array');
87
+ throw new TypeError('expected array');
47
88
  lst.forEach((i, j) => {
48
89
  if (typeof i !== 'boolean')
49
- throw new Error('expected boolean in xOnly array, got' + i + '(' + j + ')');
90
+ throw new TypeError('expected boolean in xOnly array, got' + i + '(' + j + ')');
50
91
  });
51
92
  }
93
+ // BIP327/BIP340 treat tagged-hash outputs as big-endian integers reduced mod n for
94
+ // coefficients, nonce scalars, and challenges; this helper is that int(hash_tag(...)) mod n step.
52
95
  const taggedInt = (tag, ...messages) => Fn.create(Fn.fromBytes(taggedHash(tag, ...messages), true));
96
+ // BIP327 repeatedly says "use x if the point has even Y, otherwise use n - x"; this
97
+ // helper is that parity-conditioned scalar negation for nonce limbs and Q-dependent signs.
53
98
  const evenScalar = (p, n) => (hasEven(p.y) ? n : Fn.neg(n));
54
99
  // Short utility for compat with reference implementation
100
+ /**
101
+ * Derives a compressed secp256k1 public key from a private key.
102
+ * @param seckey - signer private key
103
+ * @returns Compressed public key bytes.
104
+ * @example
105
+ * Turn a signer's secret key into the compressed key format MuSig2 expects.
106
+ * ```ts
107
+ * import { schnorr } from '@noble/curves/secp256k1.js';
108
+ * import { IndividualPubkey } from '@scure/btc-signer/musig2.js';
109
+ * IndividualPubkey(schnorr.utils.randomSecretKey());
110
+ * ```
111
+ */
112
+ // BIP327 IndividualPubkey is cbytes(d*G): the 33-byte compressed signer key.
113
+ // Aggregate exports use separate x-only encoding and should not call this helper.
55
114
  export function IndividualPubkey(seckey) {
56
115
  return secp256k1.getPublicKey(seckey, true);
57
116
  }
58
117
  // Same, but returns Point
118
+ // Base-point multiply helper for the BIP327 x*G steps below. Point.BASE.multiply rejects 0,
119
+ // so call sites that allow zero scalars need to handle that case explicitly instead of using this.
59
120
  function mulBase(n) {
60
121
  return Point.BASE.multiply(n);
61
122
  }
123
+ // Local alias for BIP327's is_infinite(P): used both for rejecting infinity where cpoint(...)
124
+ // must never yield it and for the "if R' is infinite, use G" nonce-aggregation fallback.
62
125
  function isZero(point) {
63
126
  return point.equals(Point.ZERO);
64
127
  }
65
128
  /**
66
129
  * Lexicographically sorts an array of public keys.
67
- * @param publicKeys An array of public keys (Uint8Array).
130
+ * @param publicKeys - array of public keys
68
131
  * @returns A new array containing the sorted public keys.
69
- * @throws {Error} If the input is not an array or if any element is not a Uint8Array of the correct length.
132
+ * @throws On wrong argument types. {@link TypeError}
133
+ * @throws On wrong argument ranges or values. {@link RangeError}
134
+ * @example
135
+ * Sort participant public keys before building the aggregate MuSig2 key.
136
+ * ```ts
137
+ * import { IndividualPubkey, sortKeys } from '@scure/btc-signer/musig2.js';
138
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
139
+ * sortKeys([
140
+ * IndividualPubkey(randomPrivateKeyBytes()),
141
+ * IndividualPubkey(randomPrivateKeyBytes()),
142
+ * ]);
143
+ * ```
70
144
  */
71
145
  export function sortKeys(publicKeys) {
146
+ // BIP327 KeySort is defined for non-empty signer-key lists, and this helper returns a sorted copy
147
+ // so callers do not lose their original participant ordering as a side effect of key aggregation.
72
148
  abytesArray(publicKeys, PUBKEY_LEN);
73
- return publicKeys.sort(compareBytes);
149
+ if (!publicKeys.length)
150
+ throw new RangeError('sortKeys: expected non-empty signer key list');
151
+ return Array.from(publicKeys).sort(compareBytes);
74
152
  }
75
153
  // Finds second distinct key (to make coefficient 1)
76
154
  function getSecondKey(publicKeys) {
155
+ // BIP327 GetSecondKey returns bytes(33, 0) when all signer keys are equal; that sentinel
156
+ // means no key hits the special pk' = pk2 coefficient-1 shortcut in the all-equal case.
77
157
  abytesArray(publicKeys, PUBKEY_LEN);
78
158
  for (let j = 1; j < publicKeys.length; j++)
79
159
  if (!equalBytes(publicKeys[j], publicKeys[0]))
@@ -81,10 +161,14 @@ function getSecondKey(publicKeys) {
81
161
  return ZERO;
82
162
  }
83
163
  function keyAggL(publicKeys) {
164
+ // BIP327 HashKeys hashes keys in the caller-provided order. Run KeySort first when
165
+ // the surrounding protocol requires the canonical lexicographic participant ordering.
84
166
  abytesArray(publicKeys, PUBKEY_LEN);
85
167
  return taggedHash('KeyAgg list', ...publicKeys);
86
168
  }
87
169
  function keyAggCoeffInternal(publicKey1, publicKey2, L) {
170
+ // BIP327 only short-circuits to coefficient 1 for pk' = pk2. When all keys are equal,
171
+ // pk2 is the all-zero sentinel from GetSecondKey, so every real signer key still hashes.
88
172
  abytes(publicKey1, PUBKEY_LEN);
89
173
  abytes(publicKey2, PUBKEY_LEN);
90
174
  if (equalBytes(publicKey1, publicKey2))
@@ -93,18 +177,38 @@ function keyAggCoeffInternal(publicKey1, publicKey2, L) {
93
177
  }
94
178
  /**
95
179
  * Aggregates multiple public keys using the MuSig2 key aggregation algorithm.
96
- * @param publicKeys An array of individual public keys (Uint8Array).
97
- * @param tweaks An optional array of tweaks (Uint8Array) to apply to the aggregate public key.
98
- * @param isXonly An optional array of booleans indicating whether each tweak is an X-only tweak.
99
- * @returns An object containing the aggregate public key, accumulated sign, and accumulated tweak.
100
- * @throws {Error} If the input is invalid, such as non array publicKeys, tweaks and isXonly array length not matching.
101
- * @throws {InvalidContributionErr} If any of the public keys are invalid and cannot be processed.
180
+ * @param publicKeys - individual participant public keys
181
+ * @param tweaks - optional tweaks applied to the aggregate key
182
+ * @param isXonly - whether each tweak uses x-only semantics
183
+ * @returns An object containing the aggregate public key, accumulated sign,
184
+ * and accumulated tweak.
185
+ * @throws If the input is invalid, such as non-array public keys or mismatched
186
+ * tweak metadata. {@link Error}
187
+ * @throws On wrong argument types. {@link TypeError}
188
+ * @throws On wrong argument ranges or values. {@link RangeError}
189
+ * @throws If any of the public keys are invalid and cannot be processed.
190
+ * {@link InvalidContributionErr}
191
+ * @example
192
+ * Combine all participant public keys into the shared MuSig2 context.
193
+ * ```ts
194
+ * import { IndividualPubkey, keyAggregate } from '@scure/btc-signer/musig2.js';
195
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
196
+ * keyAggregate([
197
+ * IndividualPubkey(randomPrivateKeyBytes()),
198
+ * IndividualPubkey(randomPrivateKeyBytes()),
199
+ * ]);
200
+ * ```
102
201
  */
103
202
  export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
203
+ // BIP327 KeyAgg inputs require `0 < u < 2^32`, and ApplyTweak consumes a one-for-one
204
+ // list of boolean tweak modes; callers should enforce that public contract here.
104
205
  abytesArray(publicKeys, PUBKEY_LEN);
206
+ if (publicKeys.length < 1)
207
+ throw new RangeError('keyAggregate: expected at least 1 public key');
105
208
  abytesArray(tweaks, 32);
209
+ aXonly(isXonly);
106
210
  if (tweaks.length !== isXonly.length)
107
- throw new Error('The tweaks and isXonly arrays must have the same length');
211
+ throw new RangeError('The tweaks and isXonly arrays must have the same length');
108
212
  // Aggregate
109
213
  const pk2 = getSecondKey(publicKeys);
110
214
  const L = keyAggL(publicKeys);
@@ -124,8 +228,11 @@ export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
124
228
  // Apply tweaks
125
229
  for (let i = 0; i < tweaks.length; i++) {
126
230
  const g = isXonly[i] && !hasEven(aggPublicKey.y) ? Fn.neg(Fn.ONE) : Fn.ONE;
127
- const t = Fn.fromBytes(tweaks[i]);
128
- aggPublicKey = aggPublicKey.multiply(g).add(mulBase(t));
231
+ // BIP327 ApplyTweak: `Let t = int(tweak); fail if t >= n`, so 32-byte zero tweaks are valid.
232
+ const t = Fn.fromBytes(tweaks[i], true);
233
+ if (!Fn.isValid(t))
234
+ throw new RangeError('invalid scalar: out of range');
235
+ aggPublicKey = aggPublicKey.multiply(g).add(Fn.is0(t) ? Point.ZERO : mulBase(t));
129
236
  if (isZero(aggPublicKey))
130
237
  throw new Error('The result of tweaking cannot be infinity');
131
238
  gAcc = Fn.mul(g, gAcc);
@@ -135,13 +242,28 @@ export function keyAggregate(publicKeys, tweaks = [], isXonly = []) {
135
242
  }
136
243
  /**
137
244
  * Exports the aggregate public key to a byte array.
138
- * @param ctx The result of the keyAggregate function.
245
+ * @param ctx - result of {@link keyAggregate}
139
246
  * @returns The aggregate public key as a byte array.
247
+ * @example
248
+ * Serialize the aggregate key after building the MuSig2 context.
249
+ * ```ts
250
+ * import { IndividualPubkey, keyAggregate, keyAggExport } from '@scure/btc-signer/musig2.js';
251
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
252
+ * const ctx = keyAggregate([
253
+ * IndividualPubkey(randomPrivateKeyBytes()),
254
+ * IndividualPubkey(randomPrivateKeyBytes()),
255
+ * ]);
256
+ * keyAggExport(ctx);
257
+ * ```
140
258
  */
141
259
  export function keyAggExport(ctx) {
260
+ // BIP327 GetXonlyPubkey returns xbytes(Q), so this is the 32-byte x-only aggregate key
261
+ // instead of the 33-byte compressed SEC1 form.
142
262
  return pointToBytes(ctx.aggPublicKey);
143
263
  }
144
264
  function aux(secret, rand) {
265
+ // BIP327 NonceGen and DeterministicSign blind the caller-provided 32-byte randomness with
266
+ // hash_MuSig/aux(rand) before hashing the session inputs into nonce scalars.
145
267
  const rand2 = taggedHash('MuSig/aux', rand);
146
268
  if (secret.length !== rand2.length)
147
269
  throw new Error('Cannot XOR arrays of different lengths');
@@ -150,29 +272,44 @@ function aux(secret, rand) {
150
272
  res[i] = secret[i] ^ rand2[i];
151
273
  return res;
152
274
  }
153
- const nonceHash = (rand, publicKey, aggPublicKey, i, msgPrefixed, extraIn) => taggedInt('MuSig/nonce', rand, new Uint8Array([publicKey.length]), publicKey, new Uint8Array([aggPublicKey.length]), aggPublicKey, msgPrefixed, numberToBytesBE(extraIn.length, 4), extraIn, new Uint8Array([i]));
275
+ const nonceHash = (rand, publicKey, aggPublicKey, i, msgPrefixed, extraIn) =>
276
+ // BIP327 NonceGen hashes rand || len(pk) || pk || len(aggpk) || aggpk || m_prefixed ||
277
+ // len(extra_in) || extra_in || bytes(1, i - 1), so callers pass i = 0/1 here.
278
+ taggedInt('MuSig/nonce', rand, new Uint8Array([publicKey.length]), publicKey, new Uint8Array([aggPublicKey.length]), aggPublicKey, msgPrefixed, numberToBytesBE(extraIn.length, 4), extraIn, new Uint8Array([i]));
154
279
  /**
155
280
  * Generates a nonce pair (public and secret) for MuSig2 signing.
156
- * @param publicKey The individual public key of the signer (Uint8Array).
157
- * @param secretKey The secret key of the signer (Uint8Array). Optional, included to xor randomness
158
- * @param aggPublicKey The aggregate public key of all signers (Uint8Array).
159
- * @param msg The message to be signed (Uint8Array).
160
- * @param extraIn Extra input for nonce generation (Uint8Array).
161
- * @param rand Random 32-bytes for generating the nonces (Uint8Array).
281
+ * @param publicKey - individual public key of the signer
282
+ * @param secretKey - optional secret key, mixed in to blind the randomness source
283
+ * @param aggPublicKey - aggregate public key of all signers
284
+ * @param msg - message to be signed
285
+ * @param extraIn - extra input mixed into nonce generation
286
+ * @param rand - random 32-byte seed for the nonce derivation
162
287
  * @returns An object containing the public and secret nonces.
163
- * @throws {Error} If the input is invalid, such as non array publicKey, secretKey, aggPublicKey.
288
+ * @throws If the input is invalid, such as non-array public keys or malformed
289
+ * nonce inputs. {@link Error}
290
+ * @throws On wrong argument ranges or values. {@link RangeError}
291
+ * @example
292
+ * Generate the signer-local nonce pair before sharing the public nonce with peers.
293
+ * ```ts
294
+ * import { IndividualPubkey, nonceGen } from '@scure/btc-signer/musig2.js';
295
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
296
+ * const secretKey = randomPrivateKeyBytes();
297
+ * nonceGen(IndividualPubkey(secretKey), secretKey);
298
+ * ```
164
299
  */
165
300
  export function nonceGen(publicKey, secretKey, aggPublicKey = new Uint8Array(0), msg, extraIn = new Uint8Array(0), rand = randomBytes(32)) {
166
301
  abytes(publicKey, PUBKEY_LEN);
167
302
  abytesOptional(secretKey, 32);
168
303
  abytes(aggPublicKey);
169
304
  if (![0, 32].includes(aggPublicKey.length))
170
- throw new Error('wrong aggPublicKey');
305
+ throw new RangeError('wrong aggPublicKey');
171
306
  abytesOptional(msg);
172
307
  abytes(extraIn);
173
308
  abytes(rand, 32);
174
309
  if (secretKey !== undefined)
175
310
  rand = aux(secretKey, rand);
311
+ // BIP327 distinguishes an omitted message from an explicitly empty one so the two cases
312
+ // derive different nonces even when every other session parameter matches.
176
313
  const msgPrefixed = msg !== undefined
177
314
  ? concatBytes(Uint8Array.of(1), numberToBytesBE(msg.length, 8), msg)
178
315
  : Uint8Array.of(0);
@@ -185,13 +322,33 @@ export function nonceGen(publicKey, secretKey, aggPublicKey = new Uint8Array(0),
185
322
  }
186
323
  /**
187
324
  * Aggregates public nonces from multiple signers into a single aggregate nonce.
188
- * @param pubNonces An array of public nonces from each signer (Uint8Array). Each pubnonce is assumed to be 66 bytes (two 33‐byte parts).
325
+ * @param pubNonces - public nonces from each signer
189
326
  * @returns The aggregate nonce (Uint8Array).
190
- * @throws {Error} If the input is not an array or if any element is not a Uint8Array of the correct length.
191
- * @throws {InvalidContributionErr} If any of the public nonces are invalid and cannot be processed.
327
+ * @throws If the nonce payloads are malformed or contain infinity points. {@link Error}
328
+ * @throws On wrong argument types. {@link TypeError}
329
+ * @throws On wrong argument ranges or values. {@link RangeError}
330
+ * @throws If any of the public nonces are invalid and cannot be processed.
331
+ * {@link InvalidContributionErr}
332
+ * @example
333
+ * Combine all participant public nonces before building the session.
334
+ * ```ts
335
+ * import { IndividualPubkey, nonceAggregate, nonceGen } from '@scure/btc-signer/musig2.js';
336
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
337
+ * const alice = randomPrivateKeyBytes();
338
+ * const bob = randomPrivateKeyBytes();
339
+ * nonceAggregate([
340
+ * nonceGen(IndividualPubkey(alice), alice).public,
341
+ * nonceGen(IndividualPubkey(bob), bob).public,
342
+ * ]);
343
+ * ```
192
344
  */
193
345
  export function nonceAggregate(pubNonces) {
194
346
  abytesArray(pubNonces, 66);
347
+ // BIP327 NonceAgg input: "The number u of pubnonces with 0 < u < 2^32".
348
+ // cbytes_ext uses bytes(33, 0) as the infinity sentinel for summed real contributions,
349
+ // not as an "empty aggregate" encoding.
350
+ if (pubNonces.length < 1)
351
+ throw new RangeError('nonceAggregate: expected at least 1 public nonce');
195
352
  let R1 = Point.ZERO;
196
353
  let R2 = Point.ZERO;
197
354
  for (let i = 0; i < pubNonces.length; i++) {
@@ -210,8 +367,41 @@ export function nonceAggregate(pubNonces) {
210
367
  return PubNonce.encode({ R1, R2 });
211
368
  }
212
369
  // Class allows us re-use pre-computed stuff
213
- // NOTE: it would be nice to aggregate nonce in construdctor, but there is test that passes already aggregated nonce here.
370
+ // NOTE: it would be nice to aggregate nonce in constructor, but there is a
371
+ // test that passes an already aggregated nonce here.
372
+ /**
373
+ * MuSig2 session context for partial signing and aggregation.
374
+ * @param aggNonce - aggregate nonce from all participants combined
375
+ * @param publicKeys - all participant public keys
376
+ * @param msg - message to be signed
377
+ * @param tweaks - optional tweaks applied to the aggregate public key
378
+ * @param isXonly - whether each tweak uses x-only semantics
379
+ * @example
380
+ * Build one session object and reuse it for all partial-signature steps.
381
+ * ```ts
382
+ * import {
383
+ * IndividualPubkey,
384
+ * Session,
385
+ * keyAggregate,
386
+ * keyAggExport,
387
+ * nonceAggregate,
388
+ * nonceGen,
389
+ * } from '@scure/btc-signer/musig2.js';
390
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
391
+ * const alice = randomPrivateKeyBytes();
392
+ * const bob = randomPrivateKeyBytes();
393
+ * const publicKeys = [IndividualPubkey(alice), IndividualPubkey(bob)];
394
+ * const agg = keyAggregate(publicKeys);
395
+ * const aggNonce = nonceAggregate([
396
+ * nonceGen(publicKeys[0], alice, keyAggExport(agg)).public,
397
+ * nonceGen(publicKeys[1], bob, keyAggExport(agg)).public,
398
+ * ]);
399
+ * const msg = new TextEncoder().encode('hello musig2');
400
+ * new Session(aggNonce, publicKeys, msg);
401
+ * ```
402
+ */
214
403
  export class Session {
404
+ aggNonce;
215
405
  publicKeys;
216
406
  Q;
217
407
  gAcc;
@@ -227,12 +417,12 @@ export class Session {
227
417
  * Constructor for the Session class.
228
418
  * It precomputes and stores values derived from the aggregate nonce, public keys,
229
419
  * message, and optional tweaks, optimizing the signing process.
230
- * @param aggNonce The aggregate nonce (Uint8Array) from all participants combined, must be 66 bytes.
231
- * @param publicKeys An array of public keys (Uint8Array) from each participant, must be 33 bytes.
232
- * @param msg The message (Uint8Array) to be signed.
233
- * @param tweaks Optional array of tweaks (Uint8Array) to be applied to the aggregate public key, each must be 32 bytes. Defaults to [].
234
- * @param isXonly Optional array of booleans indicating whether each tweak is an X-only tweak. Defaults to [].
235
- * @throws {Error} If the input is invalid, such as wrong array sizes or lengths.
420
+ * @param aggNonce - aggregate nonce from all participants combined
421
+ * @param publicKeys - participant public keys
422
+ * @param msg - message to be signed
423
+ * @param tweaks - tweaks applied to the aggregate public key
424
+ * @param isXonly - whether each tweak uses x-only semantics
425
+ * @throws If the input is invalid, such as wrong array sizes or lengths. {@link Error}
236
426
  */
237
427
  constructor(aggNonce, publicKeys, msg, tweaks = [], isXonly = []) {
238
428
  abytesArray(publicKeys, 33);
@@ -240,10 +430,15 @@ export class Session {
240
430
  aXonly(isXonly);
241
431
  abytes(msg);
242
432
  if (tweaks.length !== isXonly.length)
243
- throw new Error('The tweaks and isXonly arrays must have the same length');
433
+ throw new RangeError('The tweaks and isXonly arrays must have the same length');
244
434
  const { aggPublicKey, gAcc, tweakAcc } = keyAggregate(publicKeys, tweaks, isXonly);
245
435
  const { R1, R2 } = PubNonce.decode(aggNonce);
246
- this.publicKeys = publicKeys;
436
+ // BIP327 requires cached session-context state to be protected from third-party mutation,
437
+ // so Session must own detached copies of the caller-provided arrays and byte entries.
438
+ // Use Uint8Array.from(...) here instead of .slice() because Node Buffer overrides slice()
439
+ // to return a shared-memory view, which would let later caller mutation rewrite session state.
440
+ this.aggNonce = Uint8Array.from(aggNonce);
441
+ this.publicKeys = publicKeys.map((pk) => Uint8Array.from(pk));
247
442
  this.Q = aggPublicKey;
248
443
  this.gAcc = gAcc;
249
444
  this.tweakAcc = tweakAcc;
@@ -251,21 +446,23 @@ export class Session {
251
446
  const R = R1.add(R2.multiply(this.b));
252
447
  this.R = isZero(R) ? Point.BASE : R;
253
448
  this.e = taggedInt('BIP0340/challenge', pointToBytes(this.R), pointToBytes(aggPublicKey), msg);
254
- this.tweaks = tweaks;
255
- this.isXonly = isXonly;
256
- this.L = keyAggL(publicKeys);
257
- this.secondKey = getSecondKey(publicKeys);
449
+ this.tweaks = tweaks.map((t) => Uint8Array.from(t));
450
+ this.isXonly = isXonly.slice();
451
+ this.L = keyAggL(this.publicKeys);
452
+ this.secondKey = getSecondKey(this.publicKeys);
258
453
  }
259
454
  /**
260
455
  * Calculates the key aggregation coefficient for a given point.
261
456
  * @private
262
- * @param P The point to calculate the coefficient for.
457
+ * @param P - point to calculate the coefficient for
263
458
  * @returns The key aggregation coefficient as a bigint.
264
- * @throws {Error} If the provided public key is not included in the list of pubkeys.
459
+ * @throws If the provided public key is not included in the list of pubkeys. {@link Error}
265
460
  */
266
461
  getSessionKeyAggCoeff(P) {
267
462
  const { publicKeys } = this;
268
463
  const pk = P.toBytes(true);
464
+ // BIP327 GetSessionKeyAggCoeff fails if cbytes(P) is not one of the session pubkeys;
465
+ // once membership is confirmed, the cached L/secondKey state is enough to derive KeyAggCoeff.
269
466
  const found = publicKeys.some((p) => equalBytes(p, pk));
270
467
  if (!found)
271
468
  throw new Error("The signer's pubkey must be included in the list of pubkeys");
@@ -276,33 +473,39 @@ export class Session {
276
473
  const s = Fn.fromBytes(partialSig, true);
277
474
  if (!Fn.isValid(s))
278
475
  return false;
476
+ // BIP327 PartialSigVerifyInternal: `Let s = int(psig); fail if s >= n`, so s=0 must stay
477
+ // in the public verification equation and return false on mismatch instead of throwing.
279
478
  const { R1, R2 } = PubNonce.decode(publicNonce);
280
479
  const Re_s_ = R1.add(R2.multiply(b));
281
480
  const Re_s = hasEven(R.y) ? Re_s_ : Re_s_.negate();
282
481
  const P = Point.fromBytes(publicKey);
283
482
  const a = this.getSessionKeyAggCoeff(P);
284
483
  const g = Fn.mul(evenScalar(Q, 1n), gAcc);
285
- const left = mulBase(s);
484
+ const left = Point.BASE.multiplyUnsafe(s);
286
485
  const right = Re_s.add(P.multiply(Fn.mul(e, Fn.mul(a, g))));
287
486
  return left.equals(right);
288
487
  }
289
488
  /**
290
- * Generates a partial signature for a given message, secret nonce, secret key, and session context.
291
- * @param secretNonce The secret nonce for this signing session (Uint8Array). MUST be securely erased after use.
292
- * @param secret The secret key of the signer (Uint8Array).
293
- * @param sessionCtx The session context containing all necessary information for signing.
294
- * @param fastSign if set to true, the signature is created without checking validity.
489
+ * Generates a partial signature for a given message, secret nonce,
490
+ * secret key, and session context.
491
+ * @param secretNonce - secret nonce for this signing session; it is zeroed after use
492
+ * @param secret - secret key of the signer
493
+ * @param fastSign - if `true`, skip the self-verification pass
295
494
  * @returns The partial signature (Uint8Array).
296
- * @throws {Error} If the input is invalid, such as wrong array sizes, invalid nonce or secret key.
495
+ * @throws If the input is invalid, such as wrong array sizes,
496
+ * invalid nonce, or invalid secret key. {@link Error}
297
497
  */
298
498
  sign(secretNonce, secret, fastSign = false) {
299
499
  abytes(secret, 32);
300
500
  if (typeof fastSign !== 'boolean')
301
- throw new Error('expected boolean');
501
+ throw new TypeError('expected boolean');
302
502
  const { Q, gAcc, b, R, e } = this;
303
503
  const { k1: k1_, k2: k2_, publicKey: originalPk } = SecretNonce.decode(secretNonce);
304
504
  // zero-out the first 64 bytes of secretNonce so it cannot be reused
305
- // TODO: this was in reference implementation, but feels very broken. Modifying input arguments is pretty bad.
505
+ // BIP327 permits overwriting the first 64 secnonce bytes after reading k1/k2 so
506
+ // accidental reuse fails fast instead of reusing the same nonce scalars.
507
+ // TODO: this was in the reference implementation, but feels very broken.
508
+ // Modifying input arguments is pretty bad.
306
509
  secretNonce.fill(0, 0, 64);
307
510
  if (!Fn.isValid(k1_))
308
511
  throw new Error('wrong k1');
@@ -336,15 +539,12 @@ export class Session {
336
539
  }
337
540
  /**
338
541
  * Verifies a partial signature against the aggregate public key and other session parameters.
339
- * @param partialSig The partial signature to verify (Uint8Array).
340
- * @param pubNonces An array of public nonces from each signer (Uint8Array).
341
- * @param pubKeys An array of public keys from each signer (Uint8Array).
342
- * @param tweaks An array of tweaks applied to the aggregate public key.
343
- * @param isXonly An array of booleans indicating whether each tweak is an X-only tweak.
344
- * @param msg The message that was signed (Uint8Array).
345
- * @param i The index of the signer whose partial signature is being verified.
346
- * @returns True if the partial signature is valid, false otherwise.
347
- * @throws {Error} If the input is invalid, such as non array partialSig, pubNonces, pubKeys, tweaks.
542
+ * @param partialSig - partial signature to verify
543
+ * @param pubNonces - public nonces from each signer
544
+ * @param i - index of the signer whose partial signature is being verified
545
+ * @returns `true` if the partial signature is valid.
546
+ * @throws If the input is invalid, such as non-array partial signatures
547
+ * or mismatched nonce counts. {@link Error}
348
548
  */
349
549
  partialSigVerify(partialSig, pubNonces, i) {
350
550
  const { publicKeys, tweaks, isXonly } = this;
@@ -355,22 +555,32 @@ export class Session {
355
555
  aXonly(isXonly);
356
556
  anumber(i);
357
557
  if (pubNonces.length !== publicKeys.length)
358
- throw new Error('The pubNonces and publicKeys arrays must have the same length');
558
+ throw new RangeError('The pubNonces and publicKeys arrays must have the same length');
359
559
  if (tweaks.length !== isXonly.length)
360
- throw new Error('The tweaks and isXonly arrays must have the same length');
560
+ throw new RangeError('The tweaks and isXonly arrays must have the same length');
561
+ // BIP327 PartialSigVerify rebuilds session_ctx from aggnonce = NonceAgg(pubnonce_1..u),
562
+ // and GetSessionValues derives b and R from that aggnonce. This Session caches b/R/e from
563
+ // the constructor aggNonce, so a stale Session would otherwise accept mismatched pubNonces
564
+ // as long as pubNonces[i] still matched the signer slot.
361
565
  if (i >= pubNonces.length)
362
- throw new Error('index outside of pubKeys/pubNonces');
566
+ throw new RangeError('index outside of pubKeys/pubNonces');
567
+ if (!equalBytes(this.aggNonce, nonceAggregate(pubNonces)))
568
+ return false;
363
569
  return this.partialSigVerifyInternal(partialSig, pubNonces[i], publicKeys[i]);
364
570
  }
365
571
  /**
366
572
  * Aggregates partial signatures from multiple signers into a single final signature.
367
- * @param partialSigs An array of partial signatures from each signer (Uint8Array).
368
- * @param sessionCtx The session context containing all necessary information for signing.
573
+ * @param partialSigs - partial signatures from each signer
369
574
  * @returns The final aggregate signature (Uint8Array).
370
- * @throws {Error} If the input is invalid, such as wrong array sizes, invalid signature.
575
+ * @throws If the input is invalid, such as wrong array sizes or malformed
576
+ * signatures. {@link Error}
371
577
  */
372
578
  partialSigAgg(partialSigs) {
373
579
  abytesArray(partialSigs, 32);
580
+ // BIP327 PartialSigAgg is defined for a non-empty psig_1..u list tied to this session_ctx;
581
+ // [] is not a valid aggregate-signature input even though the sum starts from zero.
582
+ if (partialSigs.length < 1)
583
+ throw new RangeError('partialSigs.length must be >= 1');
374
584
  const { Q, tweakAcc, R, e } = this;
375
585
  let s = 0n;
376
586
  for (let i = 0; i < partialSigs.length; i++) {
@@ -384,17 +594,42 @@ export class Session {
384
594
  return concatBytes(pointToBytes(R), Fn.toBytes(s));
385
595
  }
386
596
  }
387
- const deterministicNonceHash = (secret, aggOtherNonce, aggPublicKey, msg, i) => taggedInt('MuSig/deterministic/nonce', secret, aggOtherNonce, aggPublicKey, numberToBytesBE(msg.length, 8), msg, new Uint8Array([i]));
597
+ const deterministicNonceHash = (secret, aggOtherNonce, aggPublicKey, msg, i) => taggedInt('MuSig/deterministic/nonce', secret, aggOtherNonce, aggPublicKey, numberToBytesBE(msg.length, 8), msg,
598
+ // BIP327 hashes bytes(1, i - 1) for i=1,2; callers pass 0/1 directly here.
599
+ new Uint8Array([i]));
388
600
  /**
389
601
  * Generates a nonce pair and partial signature deterministically for a single signer.
390
- * @param secret The secret key of the signer (Uint8Array).
391
- * @param aggOtherNonce The aggregate public nonce of all other signers (Uint8Array).
392
- * @param publicKeys An array of all signers' public keys (Uint8Array).
393
- * @param tweaks An array of tweaks to apply to the aggregate public key.
394
- * @param isXonly An array of booleans indicating whether each tweak is an X-only tweak.
395
- * @param msg The message to be signed (Uint8Array).
396
- * @param rand Optional extra randomness (Uint8Array).
602
+ * @param secret - secret key of the signer
603
+ * @param aggOtherNonce - aggregate public nonce of the other signers
604
+ * @param publicKeys - public keys of all signers
605
+ * @param msg - message to be signed
606
+ * @param tweaks - tweaks applied to the aggregate public key
607
+ * @param isXonly - whether each tweak uses x-only semantics
608
+ * @param rand - optional extra randomness
609
+ * @param fastSign - whether to skip partial-signature self-verification
397
610
  * @returns An object containing the public nonce and partial signature.
611
+ * @throws If MuSig2 session setup or signing fails. {@link Error}
612
+ * @throws On wrong argument types. {@link TypeError}
613
+ * @throws On wrong argument ranges or values. {@link RangeError}
614
+ * @throws If one of the aggregated public keys or nonces is invalid. {@link InvalidContributionErr}
615
+ * @example
616
+ * Generate one signer's deterministic nonce and partial signature in one step.
617
+ * ```ts
618
+ * import {
619
+ * IndividualPubkey,
620
+ * deterministicSign,
621
+ * keyAggregate,
622
+ * keyAggExport,
623
+ * nonceGen,
624
+ * } from '@scure/btc-signer/musig2.js';
625
+ * import { randomPrivateKeyBytes } from '@scure/btc-signer/utils.js';
626
+ * const alice = randomPrivateKeyBytes();
627
+ * const bob = randomPrivateKeyBytes();
628
+ * const publicKeys = [IndividualPubkey(alice), IndividualPubkey(bob)];
629
+ * const agg = keyAggregate(publicKeys);
630
+ * const otherNonce = nonceGen(publicKeys[1], bob, keyAggExport(agg)).public;
631
+ * deterministicSign(alice, otherNonce, publicKeys, new TextEncoder().encode('hello musig2'));
632
+ * ```
398
633
  */
399
634
  export function deterministicSign(secret, aggOtherNonce, publicKeys, msg, tweaks = [], isXonly = [], rand, fastSign = false) {
400
635
  abytes(secret, 32);
@@ -402,7 +637,9 @@ export function deterministicSign(secret, aggOtherNonce, publicKeys, msg, tweaks
402
637
  abytesArray(publicKeys, PUBKEY_LEN);
403
638
  abytesArray(tweaks, 32);
404
639
  abytes(msg);
405
- abytesOptional(rand);
640
+ abytesOptional(rand, 32);
641
+ // BIP327 DeterministicSign input bullet: `The auxiliary randomness rand: a 32-byte array`
642
+ // when present, so this optional argument still needs the exact-length check here.
406
643
  const sk = rand !== undefined ? aux(secret, rand) : secret;
407
644
  const aggPublicKey = keyAggExport(keyAggregate(publicKeys, tweaks, isXonly));
408
645
  const k1 = deterministicNonceHash(sk, aggOtherNonce, aggPublicKey, msg, 0);