@abraca/dabra 2.0.3 → 2.0.5

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.
@@ -1236,7 +1236,7 @@ var AbracadabraWS = class extends EventEmitter {
1236
1236
  this.receivedOnOpenPayload = void 0;
1237
1237
  this.closeTries = 0;
1238
1238
  this.setConfiguration(configuration);
1239
- this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : WebSocket;
1239
+ this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill ? configuration.WebSocketPolyfill : globalThis.WebSocket;
1240
1240
  this.on("open", this.configuration.onOpen);
1241
1241
  this.on("open", this.onOpen.bind(this));
1242
1242
  this.on("connect", this.configuration.onConnect);
@@ -3170,136 +3170,447 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3170
3170
  };
3171
3171
 
3172
3172
  //#endregion
3173
- //#region node_modules/@noble/hashes/esm/utils.js
3174
- /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
3173
+ //#region node_modules/@noble/hashes/utils.js
3174
+ /**
3175
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
3176
+ * @param a - value to test
3177
+ * @returns `true` when the value is a Uint8Array-compatible view.
3178
+ * @example
3179
+ * Check whether a value is a Uint8Array-compatible view.
3180
+ * ```ts
3181
+ * isBytes(new Uint8Array([1, 2, 3]));
3182
+ * ```
3183
+ */
3175
3184
  function isBytes$1(a) {
3176
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
3185
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
3177
3186
  }
3178
- /** Asserts something is positive integer. */
3179
- function anumber$1(n) {
3180
- if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
3187
+ /**
3188
+ * Asserts something is a non-negative integer.
3189
+ * @param n - number to validate
3190
+ * @param title - label included in thrown errors
3191
+ * @throws On wrong argument types. {@link TypeError}
3192
+ * @throws On wrong argument ranges or values. {@link RangeError}
3193
+ * @example
3194
+ * Validate a non-negative integer option.
3195
+ * ```ts
3196
+ * anumber(32, 'length');
3197
+ * ```
3198
+ */
3199
+ function anumber$1(n, title = "") {
3200
+ if (typeof n !== "number") {
3201
+ const prefix = title && `"${title}" `;
3202
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
3203
+ }
3204
+ if (!Number.isSafeInteger(n) || n < 0) {
3205
+ const prefix = title && `"${title}" `;
3206
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
3207
+ }
3181
3208
  }
3182
- /** Asserts something is Uint8Array. */
3183
- function abytes$1(b, ...lengths) {
3184
- if (!isBytes$1(b)) throw new Error("Uint8Array expected");
3185
- if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
3209
+ /**
3210
+ * Asserts something is Uint8Array.
3211
+ * @param value - value to validate
3212
+ * @param length - optional exact length constraint
3213
+ * @param title - label included in thrown errors
3214
+ * @returns The validated byte array.
3215
+ * @throws On wrong argument types. {@link TypeError}
3216
+ * @throws On wrong argument ranges or values. {@link RangeError}
3217
+ * @example
3218
+ * Validate that a value is a byte array.
3219
+ * ```ts
3220
+ * abytes(new Uint8Array([1, 2, 3]));
3221
+ * ```
3222
+ */
3223
+ function abytes$1(value, length, title = "") {
3224
+ const bytes = isBytes$1(value);
3225
+ const len = value?.length;
3226
+ const needsLen = length !== void 0;
3227
+ if (!bytes || needsLen && len !== length) {
3228
+ const prefix = title && `"${title}" `;
3229
+ const ofLen = needsLen ? ` of length ${length}` : "";
3230
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
3231
+ const message = prefix + "expected Uint8Array" + ofLen + ", got " + got;
3232
+ if (!bytes) throw new TypeError(message);
3233
+ throw new RangeError(message);
3234
+ }
3235
+ return value;
3186
3236
  }
3187
- /** Asserts something is hash */
3237
+ /**
3238
+ * Asserts something is a wrapped hash constructor.
3239
+ * @param h - hash constructor to validate
3240
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
3241
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
3242
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
3243
+ * @example
3244
+ * Validate a callable hash wrapper.
3245
+ * ```ts
3246
+ * import { ahash } from '@noble/hashes/utils.js';
3247
+ * import { sha256 } from '@noble/hashes/sha2.js';
3248
+ * ahash(sha256);
3249
+ * ```
3250
+ */
3188
3251
  function ahash(h) {
3189
- if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
3252
+ if (typeof h !== "function" || typeof h.create !== "function") throw new TypeError("Hash must wrapped by utils.createHasher");
3190
3253
  anumber$1(h.outputLen);
3191
3254
  anumber$1(h.blockLen);
3255
+ if (h.outputLen < 1) throw new Error("\"outputLen\" must be >= 1");
3256
+ if (h.blockLen < 1) throw new Error("\"blockLen\" must be >= 1");
3192
3257
  }
3193
- /** Asserts a hash instance has not been destroyed / finished */
3194
- function aexists$1(instance, checkFinished = true) {
3258
+ /**
3259
+ * Asserts a hash instance has not been destroyed or finished.
3260
+ * @param instance - hash instance to validate
3261
+ * @param checkFinished - whether to reject finalized instances
3262
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
3263
+ * @example
3264
+ * Validate that a hash instance is still usable.
3265
+ * ```ts
3266
+ * import { aexists } from '@noble/hashes/utils.js';
3267
+ * import { sha256 } from '@noble/hashes/sha2.js';
3268
+ * const hash = sha256.create();
3269
+ * aexists(hash);
3270
+ * ```
3271
+ */
3272
+ function aexists(instance, checkFinished = true) {
3195
3273
  if (instance.destroyed) throw new Error("Hash instance has been destroyed");
3196
3274
  if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
3197
3275
  }
3198
- /** Asserts output is properly-sized byte array */
3199
- function aoutput$1(out, instance) {
3200
- abytes$1(out);
3276
+ /**
3277
+ * Asserts output is a sufficiently-sized byte array.
3278
+ * @param out - destination buffer
3279
+ * @param instance - hash instance providing output length
3280
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
3281
+ * @throws On wrong argument types. {@link TypeError}
3282
+ * @throws On wrong argument ranges or values. {@link RangeError}
3283
+ * @example
3284
+ * Validate a caller-provided digest buffer.
3285
+ * ```ts
3286
+ * import { aoutput } from '@noble/hashes/utils.js';
3287
+ * import { sha256 } from '@noble/hashes/sha2.js';
3288
+ * const hash = sha256.create();
3289
+ * aoutput(new Uint8Array(hash.outputLen), hash);
3290
+ * ```
3291
+ */
3292
+ function aoutput(out, instance) {
3293
+ abytes$1(out, void 0, "digestInto() output");
3201
3294
  const min = instance.outputLen;
3202
- if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
3295
+ if (out.length < min) throw new RangeError("\"digestInto() output\" expected to be of length >=" + min);
3203
3296
  }
3204
- /** Zeroize a byte array. Warning: JS provides no guarantees. */
3205
- function clean$1(...arrays) {
3297
+ /**
3298
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
3299
+ * @param arrays - arrays to overwrite with zeros
3300
+ * @example
3301
+ * Zeroize sensitive buffers in place.
3302
+ * ```ts
3303
+ * clean(new Uint8Array([1, 2, 3]));
3304
+ * ```
3305
+ */
3306
+ function clean(...arrays) {
3206
3307
  for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
3207
3308
  }
3208
- /** Create DataView of an array for easy byte-level manipulation. */
3209
- function createView$1(arr) {
3309
+ /**
3310
+ * Creates a DataView for byte-level manipulation.
3311
+ * @param arr - source typed array
3312
+ * @returns DataView over the same buffer region.
3313
+ * @example
3314
+ * Create a DataView over an existing buffer.
3315
+ * ```ts
3316
+ * createView(new Uint8Array(4));
3317
+ * ```
3318
+ */
3319
+ function createView(arr) {
3210
3320
  return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3211
3321
  }
3212
- /** The rotate right (circular right shift) operation for uint32 */
3322
+ /**
3323
+ * Rotate-right operation for uint32 values.
3324
+ * @param word - source word
3325
+ * @param shift - shift amount in bits
3326
+ * @returns Rotated word.
3327
+ * @example
3328
+ * Rotate a 32-bit word to the right.
3329
+ * ```ts
3330
+ * rotr(0x12345678, 8);
3331
+ * ```
3332
+ */
3213
3333
  function rotr(word, shift) {
3214
3334
  return word << 32 - shift | word >>> shift;
3215
3335
  }
3216
- /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
3217
- const isLE$1 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
3218
- const hasHexBuiltin$1 = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
3336
+ /** Whether the current platform is little-endian. */
3337
+ const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
3338
+ const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
3339
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
3340
+ /**
3341
+ * Convert byte array to hex string.
3342
+ * Uses the built-in function when available and assumes it matches the tested
3343
+ * fallback semantics.
3344
+ * @param bytes - bytes to encode
3345
+ * @returns Lowercase hexadecimal string.
3346
+ * @throws On wrong argument types. {@link TypeError}
3347
+ * @example
3348
+ * Convert bytes to lowercase hexadecimal.
3349
+ * ```ts
3350
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
3351
+ * ```
3352
+ */
3353
+ function bytesToHex$2(bytes) {
3354
+ abytes$1(bytes);
3355
+ if (hasHexBuiltin) return bytes.toHex();
3356
+ let hex = "";
3357
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
3358
+ return hex;
3359
+ }
3360
+ const asciis = {
3361
+ _0: 48,
3362
+ _9: 57,
3363
+ A: 65,
3364
+ F: 70,
3365
+ a: 97,
3366
+ f: 102
3367
+ };
3368
+ function asciiToBase16(ch) {
3369
+ if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
3370
+ if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
3371
+ if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
3372
+ }
3373
+ /**
3374
+ * Convert hex string to byte array. Uses built-in function, when available.
3375
+ * @param hex - hexadecimal string to decode
3376
+ * @returns Decoded bytes.
3377
+ * @throws On wrong argument types. {@link TypeError}
3378
+ * @throws On wrong argument ranges or values. {@link RangeError}
3379
+ * @example
3380
+ * Decode lowercase hexadecimal into bytes.
3381
+ * ```ts
3382
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
3383
+ * ```
3384
+ */
3385
+ function hexToBytes$2(hex) {
3386
+ if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
3387
+ if (hasHexBuiltin) try {
3388
+ return Uint8Array.fromHex(hex);
3389
+ } catch (error) {
3390
+ if (error instanceof SyntaxError) throw new RangeError(error.message);
3391
+ throw error;
3392
+ }
3393
+ const hl = hex.length;
3394
+ const al = hl / 2;
3395
+ if (hl % 2) throw new RangeError("hex string expected, got unpadded hex of length " + hl);
3396
+ const array = new Uint8Array(al);
3397
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
3398
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
3399
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
3400
+ if (n1 === void 0 || n2 === void 0) {
3401
+ const char = hex[hi] + hex[hi + 1];
3402
+ throw new RangeError("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
3403
+ }
3404
+ array[ai] = n1 * 16 + n2;
3405
+ }
3406
+ return array;
3407
+ }
3219
3408
  /**
3220
3409
  * Converts string to bytes using UTF8 encoding.
3221
- * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
3410
+ * Built-in doesn't validate input to be string: we do the check.
3411
+ * Non-ASCII details are delegated to the platform `TextEncoder`.
3412
+ * @param str - string to encode
3413
+ * @returns UTF-8 encoded bytes.
3414
+ * @throws On wrong argument types. {@link TypeError}
3415
+ * @example
3416
+ * Encode a string as UTF-8 bytes.
3417
+ * ```ts
3418
+ * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
3419
+ * ```
3222
3420
  */
3223
3421
  function utf8ToBytes(str) {
3224
- if (typeof str !== "string") throw new Error("string expected");
3422
+ if (typeof str !== "string") throw new TypeError("string expected");
3225
3423
  return new Uint8Array(new TextEncoder().encode(str));
3226
3424
  }
3227
3425
  /**
3228
- * Normalizes (non-hex) string or Uint8Array to Uint8Array.
3229
- * Warning: when Uint8Array is passed, it would NOT get copied.
3230
- * Keep in mind for future mutable operations.
3426
+ * Copies several Uint8Arrays into one.
3427
+ * @param arrays - arrays to concatenate
3428
+ * @returns Concatenated byte array.
3429
+ * @throws On wrong argument types. {@link TypeError}
3430
+ * @example
3431
+ * Concatenate multiple byte arrays.
3432
+ * ```ts
3433
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
3434
+ * ```
3231
3435
  */
3232
- function toBytes(data) {
3233
- if (typeof data === "string") data = utf8ToBytes(data);
3234
- abytes$1(data);
3235
- return data;
3436
+ function concatBytes$1(...arrays) {
3437
+ let sum = 0;
3438
+ for (let i = 0; i < arrays.length; i++) {
3439
+ const a = arrays[i];
3440
+ abytes$1(a);
3441
+ sum += a.length;
3442
+ }
3443
+ const res = new Uint8Array(sum);
3444
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
3445
+ const a = arrays[i];
3446
+ res.set(a, pad);
3447
+ pad += a.length;
3448
+ }
3449
+ return res;
3236
3450
  }
3237
- /** For runtime check if class implements interface */
3238
- var Hash = class {};
3239
- /** Wraps hash function, creating an interface on top of it */
3240
- function createHasher$2(hashCons) {
3241
- const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
3242
- const tmp = hashCons();
3451
+ /**
3452
+ * Creates a callable hash function from a stateful class constructor.
3453
+ * @param hashCons - hash constructor or factory
3454
+ * @param info - optional metadata such as DER OID
3455
+ * @returns Frozen callable hash wrapper with `.create()`.
3456
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
3457
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
3458
+ * init time.
3459
+ * @example
3460
+ * Wrap a stateful hash constructor into a callable helper.
3461
+ * ```ts
3462
+ * import { createHasher } from '@noble/hashes/utils.js';
3463
+ * import { sha256 } from '@noble/hashes/sha2.js';
3464
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
3465
+ * wrapped(new Uint8Array([1]));
3466
+ * ```
3467
+ */
3468
+ function createHasher$1(hashCons, info = {}) {
3469
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
3470
+ const tmp = hashCons(void 0);
3243
3471
  hashC.outputLen = tmp.outputLen;
3244
3472
  hashC.blockLen = tmp.blockLen;
3245
- hashC.create = () => hashCons();
3246
- return hashC;
3473
+ hashC.canXOF = tmp.canXOF;
3474
+ hashC.create = (opts) => hashCons(opts);
3475
+ Object.assign(hashC, info);
3476
+ return Object.freeze(hashC);
3477
+ }
3478
+ /**
3479
+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
3480
+ * @param bytesLength - number of random bytes to generate
3481
+ * @returns Random bytes.
3482
+ * The platform `getRandomValues()` implementation still defines any
3483
+ * single-call length cap, and this helper rejects oversize requests
3484
+ * with a stable library `RangeError` instead of host-specific errors.
3485
+ * @throws On wrong argument types. {@link TypeError}
3486
+ * @throws On wrong argument ranges or values. {@link RangeError}
3487
+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
3488
+ * @example
3489
+ * Generate a fresh random key or nonce.
3490
+ * ```ts
3491
+ * const key = randomBytes(16);
3492
+ * ```
3493
+ */
3494
+ function randomBytes$1(bytesLength = 32) {
3495
+ anumber$1(bytesLength, "bytesLength");
3496
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
3497
+ if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
3498
+ if (bytesLength > 65536) throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
3499
+ return cr.getRandomValues(new Uint8Array(bytesLength));
3247
3500
  }
3501
+ /**
3502
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
3503
+ * @param suffix - final OID byte for the selected hash.
3504
+ * The helper accepts any byte even though only the documented NIST hash
3505
+ * suffixes are meaningful downstream.
3506
+ * @returns Object containing the DER-encoded OID.
3507
+ * @example
3508
+ * Build OID metadata for a NIST hash.
3509
+ * ```ts
3510
+ * oidNist(0x01);
3511
+ * ```
3512
+ */
3513
+ const oidNist = (suffix) => ({ oid: Uint8Array.from([
3514
+ 6,
3515
+ 9,
3516
+ 96,
3517
+ 134,
3518
+ 72,
3519
+ 1,
3520
+ 101,
3521
+ 3,
3522
+ 4,
3523
+ 2,
3524
+ suffix
3525
+ ]) });
3248
3526
 
3249
3527
  //#endregion
3250
- //#region node_modules/@noble/hashes/esm/_md.js
3528
+ //#region node_modules/@noble/hashes/_md.js
3251
3529
  /**
3252
3530
  * Internal Merkle-Damgard hash utils.
3253
3531
  * @module
3254
3532
  */
3255
- /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
3256
- function setBigUint64(view, byteOffset, value, isLE) {
3257
- if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
3258
- const _32n = BigInt(32);
3259
- const _u32_max = BigInt(4294967295);
3260
- const wh = Number(value >> _32n & _u32_max);
3261
- const wl = Number(value & _u32_max);
3262
- const h = isLE ? 4 : 0;
3263
- const l = isLE ? 0 : 4;
3264
- view.setUint32(byteOffset + h, wh, isLE);
3265
- view.setUint32(byteOffset + l, wl, isLE);
3266
- }
3267
- /** Choice: a ? b : c */
3533
+ /**
3534
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
3535
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
3536
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
3537
+ * set the same bit.
3538
+ * @param a - selector word
3539
+ * @param b - word chosen when selector bit is set
3540
+ * @param c - word chosen when selector bit is clear
3541
+ * @returns Mixed 32-bit word.
3542
+ * @example
3543
+ * Combine three words with the shared 32-bit choice primitive.
3544
+ * ```ts
3545
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
3546
+ * ```
3547
+ */
3268
3548
  function Chi(a, b, c) {
3269
3549
  return a & b ^ ~a & c;
3270
3550
  }
3271
- /** Majority function, true if any two inputs is true. */
3551
+ /**
3552
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
3553
+ * Returns bits shared by at least two inputs.
3554
+ * @param a - first input word
3555
+ * @param b - second input word
3556
+ * @param c - third input word
3557
+ * @returns Mixed 32-bit word.
3558
+ * @example
3559
+ * Combine three words with the shared 32-bit majority primitive.
3560
+ * ```ts
3561
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
3562
+ * ```
3563
+ */
3272
3564
  function Maj(a, b, c) {
3273
3565
  return a & b ^ a & c ^ b & c;
3274
3566
  }
3275
3567
  /**
3276
3568
  * Merkle-Damgard hash construction base class.
3277
3569
  * Could be used to create MD5, RIPEMD, SHA1, SHA2.
3570
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
3571
+ * strings with partial-byte tails.
3572
+ * @param blockLen - internal block size in bytes
3573
+ * @param outputLen - digest size in bytes
3574
+ * @param padOffset - trailing length field size in bytes
3575
+ * @param isLE - whether length and state words are encoded in little-endian
3576
+ * @example
3577
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
3578
+ * ```ts
3579
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
3580
+ * const hash = new _SHA1();
3581
+ * hash.update(new Uint8Array([97, 98, 99]));
3582
+ * hash.digest();
3583
+ * ```
3278
3584
  */
3279
- var HashMD$1 = class extends Hash {
3585
+ var HashMD = class {
3586
+ blockLen;
3587
+ outputLen;
3588
+ canXOF = false;
3589
+ padOffset;
3590
+ isLE;
3591
+ buffer;
3592
+ view;
3593
+ finished = false;
3594
+ length = 0;
3595
+ pos = 0;
3596
+ destroyed = false;
3280
3597
  constructor(blockLen, outputLen, padOffset, isLE) {
3281
- super();
3282
- this.finished = false;
3283
- this.length = 0;
3284
- this.pos = 0;
3285
- this.destroyed = false;
3286
3598
  this.blockLen = blockLen;
3287
3599
  this.outputLen = outputLen;
3288
3600
  this.padOffset = padOffset;
3289
3601
  this.isLE = isLE;
3290
3602
  this.buffer = new Uint8Array(blockLen);
3291
- this.view = createView$1(this.buffer);
3603
+ this.view = createView(this.buffer);
3292
3604
  }
3293
3605
  update(data) {
3294
- aexists$1(this);
3295
- data = toBytes(data);
3606
+ aexists(this);
3296
3607
  abytes$1(data);
3297
3608
  const { view, buffer, blockLen } = this;
3298
3609
  const len = data.length;
3299
3610
  for (let pos = 0; pos < len;) {
3300
3611
  const take = Math.min(blockLen - this.pos, len - pos);
3301
3612
  if (take === blockLen) {
3302
- const dataView = createView$1(data);
3613
+ const dataView = createView(data);
3303
3614
  for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
3304
3615
  continue;
3305
3616
  }
@@ -3316,23 +3627,23 @@ var HashMD$1 = class extends Hash {
3316
3627
  return this;
3317
3628
  }
3318
3629
  digestInto(out) {
3319
- aexists$1(this);
3320
- aoutput$1(out, this);
3630
+ aexists(this);
3631
+ aoutput(out, this);
3321
3632
  this.finished = true;
3322
3633
  const { buffer, view, blockLen, isLE } = this;
3323
3634
  let { pos } = this;
3324
3635
  buffer[pos++] = 128;
3325
- clean$1(this.buffer.subarray(pos));
3636
+ clean(this.buffer.subarray(pos));
3326
3637
  if (this.padOffset > blockLen - pos) {
3327
3638
  this.process(view, 0);
3328
3639
  pos = 0;
3329
3640
  }
3330
3641
  for (let i = pos; i < blockLen; i++) buffer[i] = 0;
3331
- setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
3642
+ view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
3332
3643
  this.process(view, 0);
3333
- const oview = createView$1(out);
3644
+ const oview = createView(out);
3334
3645
  const len = this.outputLen;
3335
- if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
3646
+ if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
3336
3647
  const outLen = len / 4;
3337
3648
  const state = this.get();
3338
3649
  if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
@@ -3346,7 +3657,7 @@ var HashMD$1 = class extends Hash {
3346
3657
  return res;
3347
3658
  }
3348
3659
  _cloneInto(to) {
3349
- to || (to = new this.constructor());
3660
+ to ||= new this.constructor();
3350
3661
  to.set(...this.get());
3351
3662
  const { blockLen, buffer, length, finished, destroyed, pos } = this;
3352
3663
  to.destroyed = destroyed;
@@ -3364,7 +3675,9 @@ var HashMD$1 = class extends Hash {
3364
3675
  * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
3365
3676
  * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
3366
3677
  */
3367
- /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
3678
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
3679
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
3680
+ * it as read-only because constructors copy words from it by index. */
3368
3681
  const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
3369
3682
  1779033703,
3370
3683
  3144134277,
@@ -3375,49 +3688,85 @@ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
3375
3688
  528734635,
3376
3689
  1541459225
3377
3690
  ]);
3691
+ /** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen
3692
+ * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first
3693
+ * eight prime numbers. Exported as a shared table; callers must treat it as read-only because
3694
+ * constructors copy halves from it by index. */
3695
+ const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
3696
+ 1779033703,
3697
+ 4089235720,
3698
+ 3144134277,
3699
+ 2227873595,
3700
+ 1013904242,
3701
+ 4271175723,
3702
+ 2773480762,
3703
+ 1595750129,
3704
+ 1359893119,
3705
+ 2917565137,
3706
+ 2600822924,
3707
+ 725511199,
3708
+ 528734635,
3709
+ 4215389547,
3710
+ 1541459225,
3711
+ 327033209
3712
+ ]);
3378
3713
 
3379
3714
  //#endregion
3380
- //#region node_modules/@noble/hashes/esm/_u64.js
3381
- /**
3382
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
3383
- * @todo re-check https://issues.chromium.org/issues/42212588
3384
- * @module
3385
- */
3386
- const U32_MASK64$1 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
3387
- const _32n$1 = /* @__PURE__ */ BigInt(32);
3388
- function fromBig$1(n, le = false) {
3715
+ //#region node_modules/@noble/hashes/_u64.js
3716
+ const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
3717
+ const _32n = /* @__PURE__ */ BigInt(32);
3718
+ function fromBig(n, le = false) {
3389
3719
  if (le) return {
3390
- h: Number(n & U32_MASK64$1),
3391
- l: Number(n >> _32n$1 & U32_MASK64$1)
3720
+ h: Number(n & U32_MASK64),
3721
+ l: Number(n >> _32n & U32_MASK64)
3392
3722
  };
3393
3723
  return {
3394
- h: Number(n >> _32n$1 & U32_MASK64$1) | 0,
3395
- l: Number(n & U32_MASK64$1) | 0
3724
+ h: Number(n >> _32n & U32_MASK64) | 0,
3725
+ l: Number(n & U32_MASK64) | 0
3396
3726
  };
3397
3727
  }
3398
- function split$1(lst, le = false) {
3728
+ function split(lst, le = false) {
3399
3729
  const len = lst.length;
3400
3730
  let Ah = new Uint32Array(len);
3401
3731
  let Al = new Uint32Array(len);
3402
3732
  for (let i = 0; i < len; i++) {
3403
- const { h, l } = fromBig$1(lst[i], le);
3733
+ const { h, l } = fromBig(lst[i], le);
3404
3734
  [Ah[i], Al[i]] = [h, l];
3405
3735
  }
3406
3736
  return [Ah, Al];
3407
3737
  }
3738
+ const shrSH = (h, _l, s) => h >>> s;
3739
+ const shrSL = (h, l, s) => h << 32 - s | l >>> s;
3740
+ const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
3741
+ const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
3742
+ const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
3743
+ const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
3744
+ function add(Ah, Al, Bh, Bl) {
3745
+ const l = (Al >>> 0) + (Bl >>> 0);
3746
+ return {
3747
+ h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
3748
+ l: l | 0
3749
+ };
3750
+ }
3751
+ const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
3752
+ const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
3753
+ const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
3754
+ const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
3755
+ const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
3756
+ const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
3408
3757
 
3409
3758
  //#endregion
3410
- //#region node_modules/@noble/hashes/esm/sha2.js
3759
+ //#region node_modules/@noble/hashes/sha2.js
3411
3760
  /**
3412
3761
  * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
3413
3762
  * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
3414
- * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
3415
- * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
3763
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
3764
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
3416
3765
  * @module
3417
3766
  */
3418
3767
  /**
3419
- * Round constants:
3420
- * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
3768
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
3769
+ * of the cube roots of the first 64 primes (2..311).
3421
3770
  */
3422
3771
  const SHA256_K = /* @__PURE__ */ Uint32Array.from([
3423
3772
  1116352408,
@@ -3485,19 +3834,12 @@ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
3485
3834
  3204031479,
3486
3835
  3329325298
3487
3836
  ]);
3488
- /** Reusable temporary buffer. "W" comes straight from spec. */
3837
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
3489
3838
  const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3490
- var SHA256 = class extends HashMD$1 {
3491
- constructor(outputLen = 32) {
3839
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
3840
+ var SHA2_32B = class extends HashMD {
3841
+ constructor(outputLen) {
3492
3842
  super(64, outputLen, 8, false);
3493
- this.A = SHA256_IV[0] | 0;
3494
- this.B = SHA256_IV[1] | 0;
3495
- this.C = SHA256_IV[2] | 0;
3496
- this.D = SHA256_IV[3] | 0;
3497
- this.E = SHA256_IV[4] | 0;
3498
- this.F = SHA256_IV[5] | 0;
3499
- this.G = SHA256_IV[6] | 0;
3500
- this.H = SHA256_IV[7] | 0;
3501
3843
  }
3502
3844
  get() {
3503
3845
  const { A, B, C, D, E, F, G, H } = this;
@@ -3555,15 +3897,30 @@ var SHA256 = class extends HashMD$1 {
3555
3897
  this.set(A, B, C, D, E, F, G, H);
3556
3898
  }
3557
3899
  roundClean() {
3558
- clean$1(SHA256_W);
3900
+ clean(SHA256_W);
3559
3901
  }
3560
3902
  destroy() {
3903
+ this.destroyed = true;
3561
3904
  this.set(0, 0, 0, 0, 0, 0, 0, 0);
3562
- clean$1(this.buffer);
3905
+ clean(this.buffer);
3563
3906
  }
3564
3907
  };
3565
- const K512$1 = split$1([
3566
- "0x428a2f98d728ae22",
3908
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
3909
+ var _SHA256 = class extends SHA2_32B {
3910
+ A = SHA256_IV[0] | 0;
3911
+ B = SHA256_IV[1] | 0;
3912
+ C = SHA256_IV[2] | 0;
3913
+ D = SHA256_IV[3] | 0;
3914
+ E = SHA256_IV[4] | 0;
3915
+ F = SHA256_IV[5] | 0;
3916
+ G = SHA256_IV[6] | 0;
3917
+ H = SHA256_IV[7] | 0;
3918
+ constructor() {
3919
+ super(32);
3920
+ }
3921
+ };
3922
+ const K512 = split([
3923
+ "0x428a2f98d728ae22",
3567
3924
  "0x7137449123ef65cd",
3568
3925
  "0xb5c0fbcfec4d3b2f",
3569
3926
  "0xe9b5dba58189dbbc",
@@ -3644,31 +4001,170 @@ const K512$1 = split$1([
3644
4001
  "0x5fcb6fab3ad6faec",
3645
4002
  "0x6c44198c4a475817"
3646
4003
  ].map((n) => BigInt(n)));
3647
- const SHA512_Kh$1 = K512$1[0];
3648
- const SHA512_Kl$1 = K512$1[1];
4004
+ const SHA512_Kh = K512[0];
4005
+ const SHA512_Kl = K512[1];
4006
+ const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
4007
+ const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
4008
+ /** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */
4009
+ var SHA2_64B = class extends HashMD {
4010
+ constructor(outputLen) {
4011
+ super(128, outputLen, 16, false);
4012
+ }
4013
+ get() {
4014
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
4015
+ return [
4016
+ Ah,
4017
+ Al,
4018
+ Bh,
4019
+ Bl,
4020
+ Ch,
4021
+ Cl,
4022
+ Dh,
4023
+ Dl,
4024
+ Eh,
4025
+ El,
4026
+ Fh,
4027
+ Fl,
4028
+ Gh,
4029
+ Gl,
4030
+ Hh,
4031
+ Hl
4032
+ ];
4033
+ }
4034
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
4035
+ this.Ah = Ah | 0;
4036
+ this.Al = Al | 0;
4037
+ this.Bh = Bh | 0;
4038
+ this.Bl = Bl | 0;
4039
+ this.Ch = Ch | 0;
4040
+ this.Cl = Cl | 0;
4041
+ this.Dh = Dh | 0;
4042
+ this.Dl = Dl | 0;
4043
+ this.Eh = Eh | 0;
4044
+ this.El = El | 0;
4045
+ this.Fh = Fh | 0;
4046
+ this.Fl = Fl | 0;
4047
+ this.Gh = Gh | 0;
4048
+ this.Gl = Gl | 0;
4049
+ this.Hh = Hh | 0;
4050
+ this.Hl = Hl | 0;
4051
+ }
4052
+ process(view, offset) {
4053
+ for (let i = 0; i < 16; i++, offset += 4) {
4054
+ SHA512_W_H[i] = view.getUint32(offset);
4055
+ SHA512_W_L[i] = view.getUint32(offset += 4);
4056
+ }
4057
+ for (let i = 16; i < 80; i++) {
4058
+ const W15h = SHA512_W_H[i - 15] | 0;
4059
+ const W15l = SHA512_W_L[i - 15] | 0;
4060
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
4061
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
4062
+ const W2h = SHA512_W_H[i - 2] | 0;
4063
+ const W2l = SHA512_W_L[i - 2] | 0;
4064
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
4065
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
4066
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
4067
+ SHA512_W_H[i] = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]) | 0;
4068
+ SHA512_W_L[i] = SUMl | 0;
4069
+ }
4070
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
4071
+ for (let i = 0; i < 80; i++) {
4072
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
4073
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
4074
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
4075
+ const CHIl = El & Fl ^ ~El & Gl;
4076
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
4077
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
4078
+ const T1l = T1ll | 0;
4079
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
4080
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
4081
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
4082
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
4083
+ Hh = Gh | 0;
4084
+ Hl = Gl | 0;
4085
+ Gh = Fh | 0;
4086
+ Gl = Fl | 0;
4087
+ Fh = Eh | 0;
4088
+ Fl = El | 0;
4089
+ ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
4090
+ Dh = Ch | 0;
4091
+ Dl = Cl | 0;
4092
+ Ch = Bh | 0;
4093
+ Cl = Bl | 0;
4094
+ Bh = Ah | 0;
4095
+ Bl = Al | 0;
4096
+ const All = add3L(T1l, sigma0l, MAJl);
4097
+ Ah = add3H(All, T1h, sigma0h, MAJh);
4098
+ Al = All | 0;
4099
+ }
4100
+ ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
4101
+ ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
4102
+ ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
4103
+ ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
4104
+ ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
4105
+ ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
4106
+ ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
4107
+ ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
4108
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
4109
+ }
4110
+ roundClean() {
4111
+ clean(SHA512_W_H, SHA512_W_L);
4112
+ }
4113
+ destroy() {
4114
+ this.destroyed = true;
4115
+ clean(this.buffer);
4116
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
4117
+ }
4118
+ };
4119
+ /** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */
4120
+ var _SHA512 = class extends SHA2_64B {
4121
+ Ah = SHA512_IV[0] | 0;
4122
+ Al = SHA512_IV[1] | 0;
4123
+ Bh = SHA512_IV[2] | 0;
4124
+ Bl = SHA512_IV[3] | 0;
4125
+ Ch = SHA512_IV[4] | 0;
4126
+ Cl = SHA512_IV[5] | 0;
4127
+ Dh = SHA512_IV[6] | 0;
4128
+ Dl = SHA512_IV[7] | 0;
4129
+ Eh = SHA512_IV[8] | 0;
4130
+ El = SHA512_IV[9] | 0;
4131
+ Fh = SHA512_IV[10] | 0;
4132
+ Fl = SHA512_IV[11] | 0;
4133
+ Gh = SHA512_IV[12] | 0;
4134
+ Gl = SHA512_IV[13] | 0;
4135
+ Hh = SHA512_IV[14] | 0;
4136
+ Hl = SHA512_IV[15] | 0;
4137
+ constructor() {
4138
+ super(64);
4139
+ }
4140
+ };
3649
4141
  /**
3650
- * SHA2-256 hash function from RFC 4634.
4142
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
3651
4143
  *
3652
- * It is the fastest JS hash, even faster than Blake3.
3653
- * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
3654
- * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
4144
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
4145
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
4146
+ * - Each sha256 hash is executing 2^18 bit operations.
4147
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
4148
+ * @param msg - message bytes to hash
4149
+ * @returns Digest bytes.
4150
+ * @example
4151
+ * Hash a message with SHA2-256.
4152
+ * ```ts
4153
+ * sha256(new Uint8Array([97, 98, 99]));
4154
+ * ```
3655
4155
  */
3656
- const sha256$1 = /* @__PURE__ */ createHasher$2(() => new SHA256());
3657
-
3658
- //#endregion
3659
- //#region node_modules/@noble/hashes/esm/sha256.js
4156
+ const sha256 = /* @__PURE__ */ createHasher$1(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
3660
4157
  /**
3661
- * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
3662
- *
3663
- * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
3664
- * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3665
- *
3666
- * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
3667
- * @module
3668
- * @deprecated
4158
+ * SHA2-512 hash function from RFC 4634.
4159
+ * @param msg - message bytes to hash
4160
+ * @returns Digest bytes.
4161
+ * @example
4162
+ * Hash a message with SHA2-512.
4163
+ * ```ts
4164
+ * sha512(new Uint8Array([97, 98, 99]));
4165
+ * ```
3669
4166
  */
3670
- /** @deprecated Use import from `noble/hashes/sha2` module */
3671
- const sha256 = sha256$1;
4167
+ const sha512 = /* @__PURE__ */ createHasher$1(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
3672
4168
 
3673
4169
  //#endregion
3674
4170
  //#region packages/provider/src/webrtc/SignalingSocket.ts
@@ -4548,598 +5044,261 @@ function constantTimeEqual(a, b) {
4548
5044
  }
4549
5045
 
4550
5046
  //#endregion
4551
- //#region node_modules/@noble/curves/node_modules/@noble/hashes/utils.js
5047
+ //#region node_modules/@noble/curves/utils.js
4552
5048
  /**
4553
- * Utilities for hex, bytes, CSPRNG.
5049
+ * Hex, bytes and number utilities.
4554
5050
  * @module
4555
5051
  */
4556
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
4557
- /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
4558
- function isBytes(a) {
4559
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
4560
- }
4561
- /** Asserts something is positive integer. */
4562
- function anumber(n, title = "") {
4563
- if (!Number.isSafeInteger(n) || n < 0) {
4564
- const prefix = title && `"${title}" `;
4565
- throw new Error(`${prefix}expected integer >= 0, got ${n}`);
4566
- }
4567
- }
4568
- /** Asserts something is Uint8Array. */
4569
- function abytes(value, length, title = "") {
4570
- const bytes = isBytes(value);
4571
- const len = value?.length;
4572
- const needsLen = length !== void 0;
4573
- if (!bytes || needsLen && len !== length) {
5052
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5053
+ /**
5054
+ * Validates that a value is a byte array.
5055
+ * @param value - Value to validate.
5056
+ * @param length - Optional exact byte length.
5057
+ * @param title - Optional field name.
5058
+ * @returns Original byte array.
5059
+ * @example
5060
+ * Reject non-byte input before passing data into curve code.
5061
+ *
5062
+ * ```ts
5063
+ * abytes(new Uint8Array(1));
5064
+ * ```
5065
+ */
5066
+ const abytes = (value, length, title) => abytes$1(value, length, title);
5067
+ /**
5068
+ * Validates that a value is a non-negative safe integer.
5069
+ * @param n - Value to validate.
5070
+ * @param title - Optional field name.
5071
+ * @example
5072
+ * Validate a numeric length before allocating buffers.
5073
+ *
5074
+ * ```ts
5075
+ * anumber(1);
5076
+ * ```
5077
+ */
5078
+ const anumber = anumber$1;
5079
+ /**
5080
+ * Encodes bytes as lowercase hex.
5081
+ * @param bytes - Bytes to encode.
5082
+ * @returns Lowercase hex string.
5083
+ * @example
5084
+ * Serialize bytes as hex for logging or fixtures.
5085
+ *
5086
+ * ```ts
5087
+ * bytesToHex(Uint8Array.of(1, 2, 3));
5088
+ * ```
5089
+ */
5090
+ const bytesToHex = bytesToHex$2;
5091
+ /**
5092
+ * Concatenates byte arrays.
5093
+ * @param arrays - Byte arrays to join.
5094
+ * @returns Concatenated bytes.
5095
+ * @example
5096
+ * Join domain-separated chunks into one buffer.
5097
+ *
5098
+ * ```ts
5099
+ * concatBytes(Uint8Array.of(1), Uint8Array.of(2));
5100
+ * ```
5101
+ */
5102
+ const concatBytes = (...arrays) => concatBytes$1(...arrays);
5103
+ /**
5104
+ * Decodes lowercase or uppercase hex into bytes.
5105
+ * @param hex - Hex string to decode.
5106
+ * @returns Decoded bytes.
5107
+ * @example
5108
+ * Parse fixture hex into bytes before hashing.
5109
+ *
5110
+ * ```ts
5111
+ * hexToBytes('0102');
5112
+ * ```
5113
+ */
5114
+ const hexToBytes = (hex) => hexToBytes$2(hex);
5115
+ /**
5116
+ * Checks whether a value is a Uint8Array.
5117
+ * @param a - Value to inspect.
5118
+ * @returns `true` when `a` is a Uint8Array.
5119
+ * @example
5120
+ * Branch on byte input before decoding it.
5121
+ *
5122
+ * ```ts
5123
+ * isBytes(new Uint8Array(1));
5124
+ * ```
5125
+ */
5126
+ const isBytes = isBytes$1;
5127
+ /**
5128
+ * Reads random bytes from the platform CSPRNG.
5129
+ * @param bytesLength - Number of random bytes to read.
5130
+ * @returns Fresh random bytes.
5131
+ * @example
5132
+ * Generate a random seed for a keypair.
5133
+ *
5134
+ * ```ts
5135
+ * randomBytes(2);
5136
+ * ```
5137
+ */
5138
+ const randomBytes = (bytesLength) => randomBytes$1(bytesLength);
5139
+ const _0n$5 = /* @__PURE__ */ BigInt(0);
5140
+ const _1n$5 = /* @__PURE__ */ BigInt(1);
5141
+ /**
5142
+ * Validates that a flag is boolean.
5143
+ * @param value - Value to validate.
5144
+ * @param title - Optional field name.
5145
+ * @returns Original value.
5146
+ * @throws On wrong argument types. {@link TypeError}
5147
+ * @example
5148
+ * Reject non-boolean option flags early.
5149
+ *
5150
+ * ```ts
5151
+ * abool(true);
5152
+ * ```
5153
+ */
5154
+ function abool(value, title = "") {
5155
+ if (typeof value !== "boolean") {
4574
5156
  const prefix = title && `"${title}" `;
4575
- const ofLen = needsLen ? ` of length ${length}` : "";
4576
- const got = bytes ? `length=${len}` : `type=${typeof value}`;
4577
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
5157
+ throw new TypeError(prefix + "expected boolean, got type=" + typeof value);
4578
5158
  }
4579
5159
  return value;
4580
5160
  }
4581
- /** Asserts a hash instance has not been destroyed / finished */
4582
- function aexists(instance, checkFinished = true) {
4583
- if (instance.destroyed) throw new Error("Hash instance has been destroyed");
4584
- if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
4585
- }
4586
- /** Asserts output is properly-sized byte array */
4587
- function aoutput(out, instance) {
4588
- abytes(out, void 0, "digestInto() output");
4589
- const min = instance.outputLen;
4590
- if (out.length < min) throw new Error("\"digestInto() output\" expected to be of length >=" + min);
4591
- }
4592
- /** Zeroize a byte array. Warning: JS provides no guarantees. */
4593
- function clean(...arrays) {
4594
- for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
4595
- }
4596
- /** Create DataView of an array for easy byte-level manipulation. */
4597
- function createView(arr) {
4598
- return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
4599
- }
4600
- /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
4601
- const isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
4602
- const hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function";
4603
- const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
4604
5161
  /**
4605
- * Convert byte array to hex string. Uses built-in function, when available.
4606
- * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
5162
+ * Validates that a value is a non-negative bigint or safe integer.
5163
+ * @param n - Value to validate.
5164
+ * @returns The same validated value.
5165
+ * @throws On wrong argument ranges or values. {@link RangeError}
5166
+ * @example
5167
+ * Validate one integer-like value before serializing it.
5168
+ *
5169
+ * ```ts
5170
+ * abignumber(1n);
5171
+ * ```
4607
5172
  */
4608
- function bytesToHex(bytes) {
4609
- abytes(bytes);
4610
- if (hasHexBuiltin) return bytes.toHex();
4611
- let hex = "";
4612
- for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
4613
- return hex;
5173
+ function abignumber(n) {
5174
+ if (typeof n === "bigint") {
5175
+ if (!isPosBig(n)) throw new RangeError("positive bigint expected, got " + n);
5176
+ } else anumber(n);
5177
+ return n;
4614
5178
  }
4615
- const asciis = {
4616
- _0: 48,
4617
- _9: 57,
4618
- A: 65,
4619
- F: 70,
4620
- a: 97,
4621
- f: 102
4622
- };
4623
- function asciiToBase16(ch) {
4624
- if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
4625
- if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
4626
- if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
4627
- }
4628
- /**
4629
- * Convert hex string to byte array. Uses built-in function, when available.
4630
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
4631
- */
4632
- function hexToBytes(hex) {
4633
- if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
4634
- if (hasHexBuiltin) return Uint8Array.fromHex(hex);
4635
- const hl = hex.length;
4636
- const al = hl / 2;
4637
- if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
4638
- const array = new Uint8Array(al);
4639
- for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
4640
- const n1 = asciiToBase16(hex.charCodeAt(hi));
4641
- const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
4642
- if (n1 === void 0 || n2 === void 0) {
4643
- const char = hex[hi] + hex[hi + 1];
4644
- throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
4645
- }
4646
- array[ai] = n1 * 16 + n2;
4647
- }
4648
- return array;
4649
- }
4650
- /** Copies several Uint8Arrays into one. */
4651
- function concatBytes(...arrays) {
4652
- let sum = 0;
4653
- for (let i = 0; i < arrays.length; i++) {
4654
- const a = arrays[i];
4655
- abytes(a);
4656
- sum += a.length;
4657
- }
4658
- const res = new Uint8Array(sum);
4659
- for (let i = 0, pad = 0; i < arrays.length; i++) {
4660
- const a = arrays[i];
4661
- res.set(a, pad);
4662
- pad += a.length;
4663
- }
4664
- return res;
4665
- }
4666
- /** Creates function with outputLen, blockLen, create properties from a class constructor. */
4667
- function createHasher$1(hashCons, info = {}) {
4668
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
4669
- const tmp = hashCons(void 0);
4670
- hashC.outputLen = tmp.outputLen;
4671
- hashC.blockLen = tmp.blockLen;
4672
- hashC.create = (opts) => hashCons(opts);
4673
- Object.assign(hashC, info);
4674
- return Object.freeze(hashC);
4675
- }
4676
- /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
4677
- function randomBytes(bytesLength = 32) {
4678
- const cr = typeof globalThis === "object" ? globalThis.crypto : null;
4679
- if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
4680
- return cr.getRandomValues(new Uint8Array(bytesLength));
4681
- }
4682
- /** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */
4683
- const oidNist = (suffix) => ({ oid: Uint8Array.from([
4684
- 6,
4685
- 9,
4686
- 96,
4687
- 134,
4688
- 72,
4689
- 1,
4690
- 101,
4691
- 3,
4692
- 4,
4693
- 2,
4694
- suffix
4695
- ]) });
4696
-
4697
- //#endregion
4698
- //#region node_modules/@noble/curves/node_modules/@noble/hashes/_md.js
4699
- /**
4700
- * Internal Merkle-Damgard hash utils.
4701
- * @module
4702
- */
4703
- /**
4704
- * Merkle-Damgard hash construction base class.
4705
- * Could be used to create MD5, RIPEMD, SHA1, SHA2.
4706
- */
4707
- var HashMD = class {
4708
- blockLen;
4709
- outputLen;
4710
- padOffset;
4711
- isLE;
4712
- buffer;
4713
- view;
4714
- finished = false;
4715
- length = 0;
4716
- pos = 0;
4717
- destroyed = false;
4718
- constructor(blockLen, outputLen, padOffset, isLE) {
4719
- this.blockLen = blockLen;
4720
- this.outputLen = outputLen;
4721
- this.padOffset = padOffset;
4722
- this.isLE = isLE;
4723
- this.buffer = new Uint8Array(blockLen);
4724
- this.view = createView(this.buffer);
4725
- }
4726
- update(data) {
4727
- aexists(this);
4728
- abytes(data);
4729
- const { view, buffer, blockLen } = this;
4730
- const len = data.length;
4731
- for (let pos = 0; pos < len;) {
4732
- const take = Math.min(blockLen - this.pos, len - pos);
4733
- if (take === blockLen) {
4734
- const dataView = createView(data);
4735
- for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
4736
- continue;
4737
- }
4738
- buffer.set(data.subarray(pos, pos + take), this.pos);
4739
- this.pos += take;
4740
- pos += take;
4741
- if (this.pos === blockLen) {
4742
- this.process(view, 0);
4743
- this.pos = 0;
4744
- }
4745
- }
4746
- this.length += data.length;
4747
- this.roundClean();
4748
- return this;
4749
- }
4750
- digestInto(out) {
4751
- aexists(this);
4752
- aoutput(out, this);
4753
- this.finished = true;
4754
- const { buffer, view, blockLen, isLE } = this;
4755
- let { pos } = this;
4756
- buffer[pos++] = 128;
4757
- clean(this.buffer.subarray(pos));
4758
- if (this.padOffset > blockLen - pos) {
4759
- this.process(view, 0);
4760
- pos = 0;
4761
- }
4762
- for (let i = pos; i < blockLen; i++) buffer[i] = 0;
4763
- view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);
4764
- this.process(view, 0);
4765
- const oview = createView(out);
4766
- const len = this.outputLen;
4767
- if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
4768
- const outLen = len / 4;
4769
- const state = this.get();
4770
- if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
4771
- for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
4772
- }
4773
- digest() {
4774
- const { buffer, outputLen } = this;
4775
- this.digestInto(buffer);
4776
- const res = buffer.slice(0, outputLen);
4777
- this.destroy();
4778
- return res;
4779
- }
4780
- _cloneInto(to) {
4781
- to ||= new this.constructor();
4782
- to.set(...this.get());
4783
- const { blockLen, buffer, length, finished, destroyed, pos } = this;
4784
- to.destroyed = destroyed;
4785
- to.finished = finished;
4786
- to.length = length;
4787
- to.pos = pos;
4788
- if (length % blockLen) to.buffer.set(buffer);
4789
- return to;
4790
- }
4791
- clone() {
4792
- return this._cloneInto();
4793
- }
4794
- };
4795
- /** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
4796
- const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
4797
- 1779033703,
4798
- 4089235720,
4799
- 3144134277,
4800
- 2227873595,
4801
- 1013904242,
4802
- 4271175723,
4803
- 2773480762,
4804
- 1595750129,
4805
- 1359893119,
4806
- 2917565137,
4807
- 2600822924,
4808
- 725511199,
4809
- 528734635,
4810
- 4215389547,
4811
- 1541459225,
4812
- 327033209
4813
- ]);
4814
-
4815
- //#endregion
4816
- //#region node_modules/@noble/curves/node_modules/@noble/hashes/_u64.js
4817
5179
  /**
4818
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
4819
- * @todo re-check https://issues.chromium.org/issues/42212588
4820
- * @module
4821
- */
4822
- const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
4823
- const _32n = /* @__PURE__ */ BigInt(32);
4824
- function fromBig(n, le = false) {
4825
- if (le) return {
4826
- h: Number(n & U32_MASK64),
4827
- l: Number(n >> _32n & U32_MASK64)
4828
- };
4829
- return {
4830
- h: Number(n >> _32n & U32_MASK64) | 0,
4831
- l: Number(n & U32_MASK64) | 0
4832
- };
4833
- }
4834
- function split(lst, le = false) {
4835
- const len = lst.length;
4836
- let Ah = new Uint32Array(len);
4837
- let Al = new Uint32Array(len);
4838
- for (let i = 0; i < len; i++) {
4839
- const { h, l } = fromBig(lst[i], le);
4840
- [Ah[i], Al[i]] = [h, l];
4841
- }
4842
- return [Ah, Al];
4843
- }
4844
- const shrSH = (h, _l, s) => h >>> s;
4845
- const shrSL = (h, l, s) => h << 32 - s | l >>> s;
4846
- const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
4847
- const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
4848
- const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
4849
- const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
4850
- function add(Ah, Al, Bh, Bl) {
4851
- const l = (Al >>> 0) + (Bl >>> 0);
4852
- return {
4853
- h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
4854
- l: l | 0
4855
- };
4856
- }
4857
- const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
4858
- const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
4859
- const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
4860
- const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
4861
- const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
4862
- const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
4863
-
4864
- //#endregion
4865
- //#region node_modules/@noble/curves/node_modules/@noble/hashes/sha2.js
4866
- /**
4867
- * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
4868
- * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
4869
- * Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and
4870
- * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
4871
- * @module
4872
- */
4873
- const K512 = split([
4874
- "0x428a2f98d728ae22",
4875
- "0x7137449123ef65cd",
4876
- "0xb5c0fbcfec4d3b2f",
4877
- "0xe9b5dba58189dbbc",
4878
- "0x3956c25bf348b538",
4879
- "0x59f111f1b605d019",
4880
- "0x923f82a4af194f9b",
4881
- "0xab1c5ed5da6d8118",
4882
- "0xd807aa98a3030242",
4883
- "0x12835b0145706fbe",
4884
- "0x243185be4ee4b28c",
4885
- "0x550c7dc3d5ffb4e2",
4886
- "0x72be5d74f27b896f",
4887
- "0x80deb1fe3b1696b1",
4888
- "0x9bdc06a725c71235",
4889
- "0xc19bf174cf692694",
4890
- "0xe49b69c19ef14ad2",
4891
- "0xefbe4786384f25e3",
4892
- "0x0fc19dc68b8cd5b5",
4893
- "0x240ca1cc77ac9c65",
4894
- "0x2de92c6f592b0275",
4895
- "0x4a7484aa6ea6e483",
4896
- "0x5cb0a9dcbd41fbd4",
4897
- "0x76f988da831153b5",
4898
- "0x983e5152ee66dfab",
4899
- "0xa831c66d2db43210",
4900
- "0xb00327c898fb213f",
4901
- "0xbf597fc7beef0ee4",
4902
- "0xc6e00bf33da88fc2",
4903
- "0xd5a79147930aa725",
4904
- "0x06ca6351e003826f",
4905
- "0x142929670a0e6e70",
4906
- "0x27b70a8546d22ffc",
4907
- "0x2e1b21385c26c926",
4908
- "0x4d2c6dfc5ac42aed",
4909
- "0x53380d139d95b3df",
4910
- "0x650a73548baf63de",
4911
- "0x766a0abb3c77b2a8",
4912
- "0x81c2c92e47edaee6",
4913
- "0x92722c851482353b",
4914
- "0xa2bfe8a14cf10364",
4915
- "0xa81a664bbc423001",
4916
- "0xc24b8b70d0f89791",
4917
- "0xc76c51a30654be30",
4918
- "0xd192e819d6ef5218",
4919
- "0xd69906245565a910",
4920
- "0xf40e35855771202a",
4921
- "0x106aa07032bbd1b8",
4922
- "0x19a4c116b8d2d0c8",
4923
- "0x1e376c085141ab53",
4924
- "0x2748774cdf8eeb99",
4925
- "0x34b0bcb5e19b48a8",
4926
- "0x391c0cb3c5c95a63",
4927
- "0x4ed8aa4ae3418acb",
4928
- "0x5b9cca4f7763e373",
4929
- "0x682e6ff3d6b2b8a3",
4930
- "0x748f82ee5defb2fc",
4931
- "0x78a5636f43172f60",
4932
- "0x84c87814a1f0ab72",
4933
- "0x8cc702081a6439ec",
4934
- "0x90befffa23631e28",
4935
- "0xa4506cebde82bde9",
4936
- "0xbef9a3f7b2c67915",
4937
- "0xc67178f2e372532b",
4938
- "0xca273eceea26619c",
4939
- "0xd186b8c721c0c207",
4940
- "0xeada7dd6cde0eb1e",
4941
- "0xf57d4f7fee6ed178",
4942
- "0x06f067aa72176fba",
4943
- "0x0a637dc5a2c898a6",
4944
- "0x113f9804bef90dae",
4945
- "0x1b710b35131c471b",
4946
- "0x28db77f523047d84",
4947
- "0x32caab7b40c72493",
4948
- "0x3c9ebe0a15c9bebc",
4949
- "0x431d67c49c100d4c",
4950
- "0x4cc5d4becb3e42b6",
4951
- "0x597f299cfc657e2a",
4952
- "0x5fcb6fab3ad6faec",
4953
- "0x6c44198c4a475817"
4954
- ].map((n) => BigInt(n)));
4955
- const SHA512_Kh = K512[0];
4956
- const SHA512_Kl = K512[1];
4957
- const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
4958
- const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
4959
- /** Internal 64-byte base SHA2 hash class. */
4960
- var SHA2_64B = class extends HashMD {
4961
- constructor(outputLen) {
4962
- super(128, outputLen, 16, false);
4963
- }
4964
- get() {
4965
- const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
4966
- return [
4967
- Ah,
4968
- Al,
4969
- Bh,
4970
- Bl,
4971
- Ch,
4972
- Cl,
4973
- Dh,
4974
- Dl,
4975
- Eh,
4976
- El,
4977
- Fh,
4978
- Fl,
4979
- Gh,
4980
- Gl,
4981
- Hh,
4982
- Hl
4983
- ];
4984
- }
4985
- set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
4986
- this.Ah = Ah | 0;
4987
- this.Al = Al | 0;
4988
- this.Bh = Bh | 0;
4989
- this.Bl = Bl | 0;
4990
- this.Ch = Ch | 0;
4991
- this.Cl = Cl | 0;
4992
- this.Dh = Dh | 0;
4993
- this.Dl = Dl | 0;
4994
- this.Eh = Eh | 0;
4995
- this.El = El | 0;
4996
- this.Fh = Fh | 0;
4997
- this.Fl = Fl | 0;
4998
- this.Gh = Gh | 0;
4999
- this.Gl = Gl | 0;
5000
- this.Hh = Hh | 0;
5001
- this.Hl = Hl | 0;
5002
- }
5003
- process(view, offset) {
5004
- for (let i = 0; i < 16; i++, offset += 4) {
5005
- SHA512_W_H[i] = view.getUint32(offset);
5006
- SHA512_W_L[i] = view.getUint32(offset += 4);
5007
- }
5008
- for (let i = 16; i < 80; i++) {
5009
- const W15h = SHA512_W_H[i - 15] | 0;
5010
- const W15l = SHA512_W_L[i - 15] | 0;
5011
- const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
5012
- const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
5013
- const W2h = SHA512_W_H[i - 2] | 0;
5014
- const W2l = SHA512_W_L[i - 2] | 0;
5015
- const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
5016
- const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
5017
- const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
5018
- SHA512_W_H[i] = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]) | 0;
5019
- SHA512_W_L[i] = SUMl | 0;
5020
- }
5021
- let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
5022
- for (let i = 0; i < 80; i++) {
5023
- const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
5024
- const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
5025
- const CHIh = Eh & Fh ^ ~Eh & Gh;
5026
- const CHIl = El & Fl ^ ~El & Gl;
5027
- const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
5028
- const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
5029
- const T1l = T1ll | 0;
5030
- const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
5031
- const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
5032
- const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
5033
- const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
5034
- Hh = Gh | 0;
5035
- Hl = Gl | 0;
5036
- Gh = Fh | 0;
5037
- Gl = Fl | 0;
5038
- Fh = Eh | 0;
5039
- Fl = El | 0;
5040
- ({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
5041
- Dh = Ch | 0;
5042
- Dl = Cl | 0;
5043
- Ch = Bh | 0;
5044
- Cl = Bl | 0;
5045
- Bh = Ah | 0;
5046
- Bl = Al | 0;
5047
- const All = add3L(T1l, sigma0l, MAJl);
5048
- Ah = add3H(All, T1h, sigma0h, MAJh);
5049
- Al = All | 0;
5050
- }
5051
- ({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
5052
- ({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
5053
- ({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
5054
- ({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
5055
- ({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
5056
- ({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
5057
- ({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
5058
- ({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
5059
- this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
5060
- }
5061
- roundClean() {
5062
- clean(SHA512_W_H, SHA512_W_L);
5063
- }
5064
- destroy() {
5065
- clean(this.buffer);
5066
- this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
5067
- }
5068
- };
5069
- /** Internal SHA2-512 hash class. */
5070
- var _SHA512 = class extends SHA2_64B {
5071
- Ah = SHA512_IV[0] | 0;
5072
- Al = SHA512_IV[1] | 0;
5073
- Bh = SHA512_IV[2] | 0;
5074
- Bl = SHA512_IV[3] | 0;
5075
- Ch = SHA512_IV[4] | 0;
5076
- Cl = SHA512_IV[5] | 0;
5077
- Dh = SHA512_IV[6] | 0;
5078
- Dl = SHA512_IV[7] | 0;
5079
- Eh = SHA512_IV[8] | 0;
5080
- El = SHA512_IV[9] | 0;
5081
- Fh = SHA512_IV[10] | 0;
5082
- Fl = SHA512_IV[11] | 0;
5083
- Gh = SHA512_IV[12] | 0;
5084
- Gl = SHA512_IV[13] | 0;
5085
- Hh = SHA512_IV[14] | 0;
5086
- Hl = SHA512_IV[15] | 0;
5087
- constructor() {
5088
- super(64);
5089
- }
5090
- };
5091
- /** SHA2-512 hash function from RFC 4634. */
5092
- const sha512 = /* @__PURE__ */ createHasher$1(() => new _SHA512(), /* @__PURE__ */ oidNist(3));
5093
-
5094
- //#endregion
5095
- //#region node_modules/@noble/curves/utils.js
5096
- /**
5097
- * Hex, bytes and number utilities.
5098
- * @module
5180
+ * Validates that a value is a safe integer.
5181
+ * @param value - Integer to validate.
5182
+ * @param title - Optional field name.
5183
+ * @throws On wrong argument types. {@link TypeError}
5184
+ * @throws On wrong argument ranges or values. {@link RangeError}
5185
+ * @example
5186
+ * Validate a window size before scalar arithmetic uses it.
5187
+ *
5188
+ * ```ts
5189
+ * asafenumber(1);
5190
+ * ```
5099
5191
  */
5100
- /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5101
- const _0n$5 = /* @__PURE__ */ BigInt(0);
5102
- const _1n$5 = /* @__PURE__ */ BigInt(1);
5103
- function abool(value, title = "") {
5104
- if (typeof value !== "boolean") {
5192
+ function asafenumber(value, title = "") {
5193
+ if (typeof value !== "number") {
5105
5194
  const prefix = title && `"${title}" `;
5106
- throw new Error(prefix + "expected boolean, got type=" + typeof value);
5195
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
5107
5196
  }
5108
- return value;
5109
- }
5110
- function abignumber(n) {
5111
- if (typeof n === "bigint") {
5112
- if (!isPosBig(n)) throw new Error("positive bigint expected, got " + n);
5113
- } else anumber(n);
5114
- return n;
5115
- }
5116
- function asafenumber(value, title = "") {
5117
5197
  if (!Number.isSafeInteger(value)) {
5118
5198
  const prefix = title && `"${title}" `;
5119
- throw new Error(prefix + "expected safe integer, got type=" + typeof value);
5199
+ throw new RangeError(prefix + "expected safe integer, got " + value);
5120
5200
  }
5121
5201
  }
5202
+ /**
5203
+ * Parses a big-endian hex string into bigint.
5204
+ * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the
5205
+ * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.
5206
+ * @param hex - Hex string without `0x`.
5207
+ * @returns Parsed bigint value.
5208
+ * @throws On wrong argument types. {@link TypeError}
5209
+ * @example
5210
+ * Parse a scalar from fixture hex.
5211
+ *
5212
+ * ```ts
5213
+ * hexToNumber('ff');
5214
+ * ```
5215
+ */
5122
5216
  function hexToNumber(hex) {
5123
- if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
5217
+ if (typeof hex !== "string") throw new TypeError("hex string expected, got " + typeof hex);
5124
5218
  return hex === "" ? _0n$5 : BigInt("0x" + hex);
5125
5219
  }
5220
+ /**
5221
+ * Parses big-endian bytes into bigint.
5222
+ * @param bytes - Bytes in big-endian order.
5223
+ * @returns Parsed bigint value.
5224
+ * @throws On wrong argument types. {@link TypeError}
5225
+ * @example
5226
+ * Read a scalar encoded in network byte order.
5227
+ *
5228
+ * ```ts
5229
+ * bytesToNumberBE(Uint8Array.of(1, 0));
5230
+ * ```
5231
+ */
5126
5232
  function bytesToNumberBE(bytes) {
5127
- return hexToNumber(bytesToHex(bytes));
5233
+ return hexToNumber(bytesToHex$2(bytes));
5128
5234
  }
5235
+ /**
5236
+ * Parses little-endian bytes into bigint.
5237
+ * @param bytes - Bytes in little-endian order.
5238
+ * @returns Parsed bigint value.
5239
+ * @throws On wrong argument types. {@link TypeError}
5240
+ * @example
5241
+ * Read a scalar encoded in little-endian form.
5242
+ *
5243
+ * ```ts
5244
+ * bytesToNumberLE(Uint8Array.of(1, 0));
5245
+ * ```
5246
+ */
5129
5247
  function bytesToNumberLE(bytes) {
5130
- return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
5248
+ return hexToNumber(bytesToHex$2(copyBytes(abytes$1(bytes)).reverse()));
5131
5249
  }
5250
+ /**
5251
+ * Encodes a bigint into fixed-length big-endian bytes.
5252
+ * @param n - Number to encode.
5253
+ * @param len - Output length in bytes. Must be greater than zero.
5254
+ * @returns Big-endian byte array.
5255
+ * @throws On wrong argument ranges or values. {@link RangeError}
5256
+ * @example
5257
+ * Serialize a scalar into a 32-byte field element.
5258
+ *
5259
+ * ```ts
5260
+ * numberToBytesBE(255n, 2);
5261
+ * ```
5262
+ */
5132
5263
  function numberToBytesBE(n, len) {
5133
- anumber(len);
5264
+ anumber$1(len);
5265
+ if (len === 0) throw new RangeError("zero length");
5134
5266
  n = abignumber(n);
5135
- const res = hexToBytes(n.toString(16).padStart(len * 2, "0"));
5136
- if (res.length !== len) throw new Error("number too large");
5137
- return res;
5267
+ const hex = n.toString(16);
5268
+ if (hex.length > len * 2) throw new RangeError("number too large");
5269
+ return hexToBytes$2(hex.padStart(len * 2, "0"));
5138
5270
  }
5271
+ /**
5272
+ * Encodes a bigint into fixed-length little-endian bytes.
5273
+ * @param n - Number to encode.
5274
+ * @param len - Output length in bytes.
5275
+ * @returns Little-endian byte array.
5276
+ * @throws On wrong argument ranges or values. {@link RangeError}
5277
+ * @example
5278
+ * Serialize a scalar for little-endian protocols.
5279
+ *
5280
+ * ```ts
5281
+ * numberToBytesLE(255n, 2);
5282
+ * ```
5283
+ */
5139
5284
  function numberToBytesLE(n, len) {
5140
5285
  return numberToBytesBE(n, len).reverse();
5141
5286
  }
5287
+ /**
5288
+ * Compares two byte arrays in constant-ish time.
5289
+ * @param a - Left byte array.
5290
+ * @param b - Right byte array.
5291
+ * @returns `true` when bytes match.
5292
+ * @example
5293
+ * Compare two encoded points without early exit.
5294
+ *
5295
+ * ```ts
5296
+ * equalBytes(Uint8Array.of(1), Uint8Array.of(1));
5297
+ * ```
5298
+ */
5142
5299
  function equalBytes(a, b) {
5300
+ a = abytes(a);
5301
+ b = abytes(b);
5143
5302
  if (a.length !== b.length) return false;
5144
5303
  let diff = 0;
5145
5304
  for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
@@ -5148,40 +5307,92 @@ function equalBytes(a, b) {
5148
5307
  /**
5149
5308
  * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,
5150
5309
  * and Buffer#slice creates mutable copy. Never use Buffers!
5310
+ * @param bytes - Bytes to copy.
5311
+ * @returns Detached copy.
5312
+ * @example
5313
+ * Make an isolated copy before mutating serialized bytes.
5314
+ *
5315
+ * ```ts
5316
+ * copyBytes(Uint8Array.of(1, 2, 3));
5317
+ * ```
5151
5318
  */
5152
5319
  function copyBytes(bytes) {
5153
- return Uint8Array.from(bytes);
5320
+ return Uint8Array.from(abytes(bytes));
5154
5321
  }
5155
5322
  /**
5156
5323
  * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols
5157
5324
  * Should be safe to use for things expected to be ASCII.
5158
5325
  * Returns exact same result as `TextEncoder` for ASCII or throws.
5326
+ * @param ascii - ASCII input text.
5327
+ * @returns Encoded bytes.
5328
+ * @throws On wrong argument types. {@link TypeError}
5329
+ * @example
5330
+ * Encode an ASCII domain-separation tag.
5331
+ *
5332
+ * ```ts
5333
+ * asciiToBytes('ABC');
5334
+ * ```
5159
5335
  */
5160
5336
  function asciiToBytes(ascii) {
5337
+ if (typeof ascii !== "string") throw new TypeError("ascii string expected, got " + typeof ascii);
5161
5338
  return Uint8Array.from(ascii, (c, i) => {
5162
5339
  const charCode = c.charCodeAt(0);
5163
- if (c.length !== 1 || charCode > 127) throw new Error(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
5340
+ if (c.length !== 1 || charCode > 127) throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`);
5164
5341
  return charCode;
5165
5342
  });
5166
5343
  }
5167
5344
  const isPosBig = (n) => typeof n === "bigint" && _0n$5 <= n;
5345
+ /**
5346
+ * Checks whether a bigint lies inside a half-open range.
5347
+ * @param n - Candidate value.
5348
+ * @param min - Inclusive lower bound.
5349
+ * @param max - Exclusive upper bound.
5350
+ * @returns `true` when the value is inside the range.
5351
+ * @example
5352
+ * Check whether a candidate scalar fits the field order.
5353
+ *
5354
+ * ```ts
5355
+ * inRange(2n, 1n, 3n);
5356
+ * ```
5357
+ */
5168
5358
  function inRange(n, min, max) {
5169
5359
  return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
5170
5360
  }
5171
5361
  /**
5172
- * Asserts min <= n < max. NOTE: It's < max and not <= max.
5362
+ * Asserts `min <= n < max`. NOTE: upper bound is exclusive.
5363
+ * @param title - Value label for error messages.
5364
+ * @param n - Candidate value.
5365
+ * @param min - Inclusive lower bound.
5366
+ * @param max - Exclusive upper bound.
5367
+ * Wrong-type inputs are not separated from out-of-range values here: they still flow through the
5368
+ * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.
5369
+ * @throws On wrong argument ranges or values. {@link RangeError}
5173
5370
  * @example
5174
- * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
5371
+ * Assert that a bigint stays within one half-open range.
5372
+ *
5373
+ * ```ts
5374
+ * aInRange('x', 2n, 1n, 256n);
5375
+ * ```
5175
5376
  */
5176
5377
  function aInRange(title, n, min, max) {
5177
- if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
5378
+ if (!inRange(n, min, max)) throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
5178
5379
  }
5179
5380
  /**
5180
5381
  * Calculates amount of bits in a bigint.
5181
5382
  * Same as `n.toString(2).length`
5182
5383
  * TODO: merge with nLength in modular
5384
+ * @param n - Value to inspect.
5385
+ * @returns Bit length.
5386
+ * @throws If the value is negative. {@link Error}
5387
+ * @example
5388
+ * Measure the bit length of a scalar before serialization.
5389
+ *
5390
+ * ```ts
5391
+ * bitLen(8n);
5392
+ * ```
5183
5393
  */
5184
5394
  function bitLen(n) {
5395
+ if (n < _0n$5) throw new Error("expected non-negative bigint, got " + n);
5185
5396
  let len;
5186
5397
  for (len = 0; n > _0n$5; n >>= _1n$5, len += 1);
5187
5398
  return len;
@@ -5189,40 +5400,61 @@ function bitLen(n) {
5189
5400
  /**
5190
5401
  * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
5191
5402
  * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
5403
+ * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift
5404
+ * semantics and therefore produce `-1n`.
5405
+ * @returns Bitmask value.
5406
+ * @example
5407
+ * Calculate mask for N bits.
5408
+ *
5409
+ * ```ts
5410
+ * bitMask(4);
5411
+ * ```
5192
5412
  */
5193
5413
  const bitMask = (n) => (_1n$5 << BigInt(n)) - _1n$5;
5414
+ /**
5415
+ * Validates declared required and optional field types on a plain object.
5416
+ * Extra keys are intentionally ignored because many callers validate only the subset they use from
5417
+ * richer option bags or runtime objects.
5418
+ * @param object - Object to validate.
5419
+ * @param fields - Required field types.
5420
+ * @param optFields - Optional field types.
5421
+ * @throws On wrong argument types. {@link TypeError}
5422
+ * @example
5423
+ * Check user options before building a curve helper.
5424
+ *
5425
+ * ```ts
5426
+ * validateObject({ flag: true }, { flag: 'boolean' });
5427
+ * ```
5428
+ */
5194
5429
  function validateObject(object, fields = {}, optFields = {}) {
5195
- if (!object || typeof object !== "object") throw new Error("expected valid options object");
5430
+ if (Object.prototype.toString.call(object) !== "[object Object]") throw new TypeError("expected valid options object");
5196
5431
  function checkField(fieldName, expectedType, isOpt) {
5432
+ if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName)) throw new TypeError(`param "${fieldName}" is invalid: expected own property`);
5197
5433
  const val = object[fieldName];
5198
5434
  if (isOpt && val === void 0) return;
5199
5435
  const current = typeof val;
5200
- if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
5436
+ if (current !== expectedType || val === null) throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
5201
5437
  }
5202
5438
  const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
5203
5439
  iter(fields, false);
5204
5440
  iter(optFields, true);
5205
5441
  }
5206
5442
  /**
5207
- * throws not implemented error
5443
+ * Throws not implemented error.
5444
+ * @returns Never returns.
5445
+ * @throws If the unfinished code path is reached. {@link Error}
5446
+ * @example
5447
+ * Surface the placeholder error from an unfinished code path.
5448
+ *
5449
+ * ```ts
5450
+ * try {
5451
+ * notImplemented();
5452
+ * } catch {}
5453
+ * ```
5208
5454
  */
5209
5455
  const notImplemented = () => {
5210
5456
  throw new Error("not implemented");
5211
5457
  };
5212
- /**
5213
- * Memoizes (caches) computation result.
5214
- * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
5215
- */
5216
- function memoized(fn) {
5217
- const map = /* @__PURE__ */ new WeakMap();
5218
- return (arg, ...args) => {
5219
- const val = map.get(arg);
5220
- if (val !== void 0) return val;
5221
- const computed = fn(arg, ...args);
5222
- map.set(arg, computed);
5223
- return computed;
5224
- };
5225
- }
5226
5458
 
5227
5459
  //#endregion
5228
5460
  //#region node_modules/@noble/curves/abstract/modular.js
@@ -5237,12 +5469,41 @@ const _0n$4 = /* @__PURE__ */ BigInt(0), _1n$4 = /* @__PURE__ */ BigInt(1), _2n$
5237
5469
  const _3n$1 = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n$1 = /* @__PURE__ */ BigInt(5);
5238
5470
  const _7n = /* @__PURE__ */ BigInt(7), _8n$2 = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);
5239
5471
  const _16n = /* @__PURE__ */ BigInt(16);
5472
+ /**
5473
+ * @param a - Dividend value.
5474
+ * @param b - Positive modulus.
5475
+ * @returns Reduced value in `[0, b)` only when `b` is positive.
5476
+ * @throws If the modulus is not positive. {@link Error}
5477
+ * @example
5478
+ * Normalize a bigint into one field residue.
5479
+ *
5480
+ * ```ts
5481
+ * mod(-1n, 5n);
5482
+ * ```
5483
+ */
5240
5484
  function mod(a, b) {
5485
+ if (b <= _0n$4) throw new Error("mod: expected positive modulus, got " + b);
5241
5486
  const result = a % b;
5242
5487
  return result >= _0n$4 ? result : b + result;
5243
5488
  }
5244
- /** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */
5489
+ /**
5490
+ * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.
5491
+ * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen
5492
+ * modulus; the `power===0` fast path intentionally returns the input unchanged.
5493
+ * @param x - Base value.
5494
+ * @param power - Number of squarings.
5495
+ * @param modulo - Reduction modulus.
5496
+ * @returns Repeated-squaring result.
5497
+ * @throws If the exponent is negative. {@link Error}
5498
+ * @example
5499
+ * Apply repeated squaring inside one field.
5500
+ *
5501
+ * ```ts
5502
+ * pow2(3n, 2n, 11n);
5503
+ * ```
5504
+ */
5245
5505
  function pow2(x, power, modulo) {
5506
+ if (power < _0n$4) throw new Error("pow2: expected non-negative exponent, got " + power);
5246
5507
  let res = x;
5247
5508
  while (power-- > _0n$4) {
5248
5509
  res *= res;
@@ -5252,7 +5513,17 @@ function pow2(x, power, modulo) {
5252
5513
  }
5253
5514
  /**
5254
5515
  * Inverses number over modulo.
5255
- * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
5516
+ * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.
5517
+ * @param number - Value to invert.
5518
+ * @param modulo - Positive modulus.
5519
+ * @returns Multiplicative inverse.
5520
+ * @throws If the modulus is invalid or the inverse does not exist. {@link Error}
5521
+ * @example
5522
+ * Compute one modular inverse with the extended Euclidean algorithm.
5523
+ *
5524
+ * ```ts
5525
+ * invert(3n, 11n);
5526
+ * ```
5256
5527
  */
5257
5528
  function invert(number, modulo) {
5258
5529
  if (number === _0n$4) throw new Error("invert: expected non-zero number");
@@ -5262,7 +5533,7 @@ function invert(number, modulo) {
5262
5533
  let x = _0n$4, y = _1n$4, u = _1n$4, v = _0n$4;
5263
5534
  while (a !== _0n$4) {
5264
5535
  const q = b / a;
5265
- const r = b % a;
5536
+ const r = b - a * q;
5266
5537
  const m = x - u * q;
5267
5538
  const n = y - v * q;
5268
5539
  b = a, a = r, x = u, y = v, u = m, v = n;
@@ -5271,22 +5542,25 @@ function invert(number, modulo) {
5271
5542
  return mod(x, modulo);
5272
5543
  }
5273
5544
  function assertIsSquare(Fp, root, n) {
5274
- if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
5545
+ const F = Fp;
5546
+ if (!F.eql(F.sqr(root), n)) throw new Error("Cannot find square root");
5275
5547
  }
5276
5548
  function sqrt3mod4(Fp, n) {
5277
- const p1div4 = (Fp.ORDER + _1n$4) / _4n;
5278
- const root = Fp.pow(n, p1div4);
5279
- assertIsSquare(Fp, root, n);
5549
+ const F = Fp;
5550
+ const p1div4 = (F.ORDER + _1n$4) / _4n;
5551
+ const root = F.pow(n, p1div4);
5552
+ assertIsSquare(F, root, n);
5280
5553
  return root;
5281
5554
  }
5282
5555
  function sqrt5mod8(Fp, n) {
5283
- const p5div8 = (Fp.ORDER - _5n$1) / _8n$2;
5284
- const n2 = Fp.mul(n, _2n$3);
5285
- const v = Fp.pow(n2, p5div8);
5286
- const nv = Fp.mul(n, v);
5287
- const i = Fp.mul(Fp.mul(nv, _2n$3), v);
5288
- const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
5289
- assertIsSquare(Fp, root, n);
5556
+ const F = Fp;
5557
+ const p5div8 = (F.ORDER - _5n$1) / _8n$2;
5558
+ const n2 = F.mul(n, _2n$3);
5559
+ const v = F.pow(n2, p5div8);
5560
+ const nv = F.mul(n, v);
5561
+ const i = F.mul(F.mul(nv, _2n$3), v);
5562
+ const root = F.mul(nv, F.sub(i, F.ONE));
5563
+ assertIsSquare(F, root, n);
5290
5564
  return root;
5291
5565
  }
5292
5566
  function sqrt9mod16(P) {
@@ -5296,27 +5570,39 @@ function sqrt9mod16(P) {
5296
5570
  const c2 = tn(Fp_, c1);
5297
5571
  const c3 = tn(Fp_, Fp_.neg(c1));
5298
5572
  const c4 = (P + _7n) / _16n;
5299
- return (Fp, n) => {
5300
- let tv1 = Fp.pow(n, c4);
5301
- let tv2 = Fp.mul(tv1, c1);
5302
- const tv3 = Fp.mul(tv1, c2);
5303
- const tv4 = Fp.mul(tv1, c3);
5304
- const e1 = Fp.eql(Fp.sqr(tv2), n);
5305
- const e2 = Fp.eql(Fp.sqr(tv3), n);
5306
- tv1 = Fp.cmov(tv1, tv2, e1);
5307
- tv2 = Fp.cmov(tv4, tv3, e2);
5308
- const e3 = Fp.eql(Fp.sqr(tv2), n);
5309
- const root = Fp.cmov(tv1, tv2, e3);
5310
- assertIsSquare(Fp, root, n);
5573
+ return ((Fp, n) => {
5574
+ const F = Fp;
5575
+ let tv1 = F.pow(n, c4);
5576
+ let tv2 = F.mul(tv1, c1);
5577
+ const tv3 = F.mul(tv1, c2);
5578
+ const tv4 = F.mul(tv1, c3);
5579
+ const e1 = F.eql(F.sqr(tv2), n);
5580
+ const e2 = F.eql(F.sqr(tv3), n);
5581
+ tv1 = F.cmov(tv1, tv2, e1);
5582
+ tv2 = F.cmov(tv4, tv3, e2);
5583
+ const e3 = F.eql(F.sqr(tv2), n);
5584
+ const root = F.cmov(tv1, tv2, e3);
5585
+ assertIsSquare(F, root, n);
5311
5586
  return root;
5312
- };
5587
+ });
5313
5588
  }
5314
5589
  /**
5315
5590
  * Tonelli-Shanks square root search algorithm.
5316
- * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
5591
+ * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`
5592
+ * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.
5593
+ * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12
5317
5594
  * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
5318
- * @param P field order
5595
+ * @param P - field order
5319
5596
  * @returns function that takes field Fp (created from P) and number n
5597
+ * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}
5598
+ * @example
5599
+ * Construct a square-root helper for primes that need Tonelli-Shanks.
5600
+ *
5601
+ * ```ts
5602
+ * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';
5603
+ * const Fp = Field(17n);
5604
+ * const sqrt = tonelliShanks(17n)(Fp, 4n);
5605
+ * ```
5320
5606
  */
5321
5607
  function tonelliShanks(P) {
5322
5608
  if (P < _3n$1) throw new Error("sqrt is not defined for small field");
@@ -5333,27 +5619,28 @@ function tonelliShanks(P) {
5333
5619
  let cc = _Fp.pow(Z, Q);
5334
5620
  const Q1div2 = (Q + _1n$4) / _2n$3;
5335
5621
  return function tonelliSlow(Fp, n) {
5336
- if (Fp.is0(n)) return n;
5337
- if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
5622
+ const F = Fp;
5623
+ if (F.is0(n)) return n;
5624
+ if (FpLegendre(F, n) !== 1) throw new Error("Cannot find square root");
5338
5625
  let M = S;
5339
- let c = Fp.mul(Fp.ONE, cc);
5340
- let t = Fp.pow(n, Q);
5341
- let R = Fp.pow(n, Q1div2);
5342
- while (!Fp.eql(t, Fp.ONE)) {
5343
- if (Fp.is0(t)) return Fp.ZERO;
5626
+ let c = F.mul(F.ONE, cc);
5627
+ let t = F.pow(n, Q);
5628
+ let R = F.pow(n, Q1div2);
5629
+ while (!F.eql(t, F.ONE)) {
5630
+ if (F.is0(t)) return F.ZERO;
5344
5631
  let i = 1;
5345
- let t_tmp = Fp.sqr(t);
5346
- while (!Fp.eql(t_tmp, Fp.ONE)) {
5632
+ let t_tmp = F.sqr(t);
5633
+ while (!F.eql(t_tmp, F.ONE)) {
5347
5634
  i++;
5348
- t_tmp = Fp.sqr(t_tmp);
5635
+ t_tmp = F.sqr(t_tmp);
5349
5636
  if (i === M) throw new Error("Cannot find square root");
5350
5637
  }
5351
5638
  const exponent = _1n$4 << BigInt(M - i - 1);
5352
- const b = Fp.pow(c, exponent);
5639
+ const b = F.pow(c, exponent);
5353
5640
  M = i;
5354
- c = Fp.sqr(b);
5355
- t = Fp.mul(t, c);
5356
- R = Fp.mul(R, b);
5641
+ c = F.sqr(b);
5642
+ t = F.mul(t, c);
5643
+ R = F.mul(R, b);
5357
5644
  }
5358
5645
  return R;
5359
5646
  };
@@ -5367,7 +5654,20 @@ function tonelliShanks(P) {
5367
5654
  * 4. Tonelli-Shanks algorithm
5368
5655
  *
5369
5656
  * Different algorithms can give different roots, it is up to user to decide which one they want.
5370
- * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
5657
+ * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness
5658
+ * (used for hash-to-curve).
5659
+ * @param P - Field order.
5660
+ * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time
5661
+ * behavior and this selector assumes prime-field-style integer moduli.
5662
+ * @throws If the field is unsupported or the square root does not exist. {@link Error}
5663
+ * @example
5664
+ * Choose the square-root helper appropriate for one field modulus.
5665
+ *
5666
+ * ```ts
5667
+ * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';
5668
+ * const Fp = Field(17n);
5669
+ * const sqrt = FpSqrt(17n)(Fp, 4n);
5670
+ * ```
5371
5671
  */
5372
5672
  function FpSqrt(P) {
5373
5673
  if (P % _4n === _3n$1) return sqrt3mod4;
@@ -5375,6 +5675,18 @@ function FpSqrt(P) {
5375
5675
  if (P % _16n === _9n) return sqrt9mod16(P);
5376
5676
  return tonelliShanks(P);
5377
5677
  }
5678
+ /**
5679
+ * @param num - Value to inspect.
5680
+ * @param modulo - Field modulus.
5681
+ * @returns `true` when the least-significant little-endian bit is set.
5682
+ * @throws If the modulus is invalid for `mod(...)`. {@link Error}
5683
+ * @example
5684
+ * Inspect the low bit used by little-endian sign conventions.
5685
+ *
5686
+ * ```ts
5687
+ * isNegativeLE(3n, 11n);
5688
+ * ```
5689
+ */
5378
5690
  const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n$4) === _1n$4;
5379
5691
  const FIELD_FIELDS = [
5380
5692
  "create",
@@ -5395,6 +5707,20 @@ const FIELD_FIELDS = [
5395
5707
  "mulN",
5396
5708
  "sqrN"
5397
5709
  ];
5710
+ /**
5711
+ * @param field - Field implementation.
5712
+ * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it
5713
+ * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or
5714
+ * field-specific extras beyond positive `BYTES` / `BITS`.
5715
+ * @throws If the field shape or numeric metadata are invalid. {@link Error}
5716
+ * @example
5717
+ * Check that a field implementation exposes the operations curve code expects.
5718
+ *
5719
+ * ```ts
5720
+ * import { Field, validateField } from '@noble/curves/abstract/modular.js';
5721
+ * const Fp = validateField(Field(17n));
5722
+ * ```
5723
+ */
5398
5724
  function validateField(field) {
5399
5725
  validateObject(field, FIELD_FIELDS.reduce((map, val) => {
5400
5726
  map[val] = "function";
@@ -5404,42 +5730,72 @@ function validateField(field) {
5404
5730
  BYTES: "number",
5405
5731
  BITS: "number"
5406
5732
  }));
5733
+ asafenumber(field.BYTES, "BYTES");
5734
+ asafenumber(field.BITS, "BITS");
5735
+ if (field.BYTES < 1 || field.BITS < 1) throw new Error("invalid field: expected BYTES/BITS > 0");
5736
+ if (field.ORDER <= _1n$4) throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
5407
5737
  return field;
5408
5738
  }
5409
5739
  /**
5410
5740
  * Same as `pow` but for Fp: non-constant-time.
5411
5741
  * Unsafe in some contexts: uses ladder, so can expose bigint bits.
5742
+ * @param Fp - Field implementation.
5743
+ * @param num - Base value.
5744
+ * @param power - Exponent value.
5745
+ * @returns Powered field element.
5746
+ * @throws If the exponent is negative. {@link Error}
5747
+ * @example
5748
+ * Raise one field element to a public exponent.
5749
+ *
5750
+ * ```ts
5751
+ * import { Field, FpPow } from '@noble/curves/abstract/modular.js';
5752
+ * const Fp = Field(17n);
5753
+ * const x = FpPow(Fp, 3n, 5n);
5754
+ * ```
5412
5755
  */
5413
5756
  function FpPow(Fp, num, power) {
5757
+ const F = Fp;
5414
5758
  if (power < _0n$4) throw new Error("invalid exponent, negatives unsupported");
5415
- if (power === _0n$4) return Fp.ONE;
5759
+ if (power === _0n$4) return F.ONE;
5416
5760
  if (power === _1n$4) return num;
5417
- let p = Fp.ONE;
5761
+ let p = F.ONE;
5418
5762
  let d = num;
5419
5763
  while (power > _0n$4) {
5420
- if (power & _1n$4) p = Fp.mul(p, d);
5421
- d = Fp.sqr(d);
5764
+ if (power & _1n$4) p = F.mul(p, d);
5765
+ d = F.sqr(d);
5422
5766
  power >>= _1n$4;
5423
5767
  }
5424
5768
  return p;
5425
5769
  }
5426
5770
  /**
5427
5771
  * Efficiently invert an array of Field elements.
5428
- * Exception-free. Will return `undefined` for 0 elements.
5429
- * @param passZero map 0 to 0 (instead of undefined)
5772
+ * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.
5773
+ * @param Fp - Field implementation.
5774
+ * @param nums - Values to invert.
5775
+ * @param passZero - map 0 to 0 (instead of undefined)
5776
+ * @returns Inverted values.
5777
+ * @example
5778
+ * Invert several field elements with one shared inversion.
5779
+ *
5780
+ * ```ts
5781
+ * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';
5782
+ * const Fp = Field(17n);
5783
+ * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);
5784
+ * ```
5430
5785
  */
5431
5786
  function FpInvertBatch(Fp, nums, passZero = false) {
5432
- const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
5787
+ const F = Fp;
5788
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
5433
5789
  const multipliedAcc = nums.reduce((acc, num, i) => {
5434
- if (Fp.is0(num)) return acc;
5790
+ if (F.is0(num)) return acc;
5435
5791
  inverted[i] = acc;
5436
- return Fp.mul(acc, num);
5437
- }, Fp.ONE);
5438
- const invertedAcc = Fp.inv(multipliedAcc);
5792
+ return F.mul(acc, num);
5793
+ }, F.ONE);
5794
+ const invertedAcc = F.inv(multipliedAcc);
5439
5795
  nums.reduceRight((acc, num, i) => {
5440
- if (Fp.is0(num)) return acc;
5441
- inverted[i] = Fp.mul(acc, inverted[i]);
5442
- return Fp.mul(acc, num);
5796
+ if (F.is0(num)) return acc;
5797
+ inverted[i] = F.mul(acc, inverted[i]);
5798
+ return F.mul(acc, num);
5443
5799
  }, invertedAcc);
5444
5800
  return inverted;
5445
5801
  }
@@ -5451,24 +5807,55 @@ function FpInvertBatch(Fp, nums, passZero = false) {
5451
5807
  * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
5452
5808
  * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
5453
5809
  * * (a | p) ≡ 0 if a ≡ 0 (mod p)
5810
+ * @param Fp - Field implementation.
5811
+ * @param n - Value to inspect.
5812
+ * @returns Legendre symbol.
5813
+ * @throws If the field returns an invalid Legendre symbol value. {@link Error}
5814
+ * @example
5815
+ * Compute the Legendre symbol of one field element.
5816
+ *
5817
+ * ```ts
5818
+ * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';
5819
+ * const Fp = Field(17n);
5820
+ * const symbol = FpLegendre(Fp, 4n);
5821
+ * ```
5454
5822
  */
5455
5823
  function FpLegendre(Fp, n) {
5456
- const p1mod2 = (Fp.ORDER - _1n$4) / _2n$3;
5457
- const powered = Fp.pow(n, p1mod2);
5458
- const yes = Fp.eql(powered, Fp.ONE);
5459
- const zero = Fp.eql(powered, Fp.ZERO);
5460
- const no = Fp.eql(powered, Fp.neg(Fp.ONE));
5824
+ const F = Fp;
5825
+ const p1mod2 = (F.ORDER - _1n$4) / _2n$3;
5826
+ const powered = F.pow(n, p1mod2);
5827
+ const yes = F.eql(powered, F.ONE);
5828
+ const zero = F.eql(powered, F.ZERO);
5829
+ const no = F.eql(powered, F.neg(F.ONE));
5461
5830
  if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
5462
5831
  return yes ? 1 : zero ? 0 : -1;
5463
5832
  }
5833
+ /**
5834
+ * @param n - Curve order. Callers are expected to pass a positive order.
5835
+ * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached
5836
+ * value when overriding the derived bit length.
5837
+ * @returns Byte and bit lengths.
5838
+ * @throws If the order or cached bit length is invalid. {@link Error}
5839
+ * @example
5840
+ * Measure the encoding sizes needed for one modulus.
5841
+ *
5842
+ * ```ts
5843
+ * nLength(255n);
5844
+ * ```
5845
+ */
5464
5846
  function nLength(n, nBitLength) {
5465
5847
  if (nBitLength !== void 0) anumber(nBitLength);
5466
- const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
5848
+ if (n <= _0n$4) throw new Error("invalid n length: expected positive n, got " + n);
5849
+ if (nBitLength !== void 0 && nBitLength < 1) throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
5850
+ const bits = bitLen(n);
5851
+ if (nBitLength !== void 0 && nBitLength < bits) throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);
5852
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
5467
5853
  return {
5468
5854
  nBitLength: _nBitLength,
5469
5855
  nByteLength: Math.ceil(_nBitLength / 8)
5470
5856
  };
5471
5857
  }
5858
+ const FIELD_SQRT = /* @__PURE__ */ new WeakMap();
5472
5859
  var _Field = class {
5473
5860
  ORDER;
5474
5861
  BITS;
@@ -5477,17 +5864,19 @@ var _Field = class {
5477
5864
  ZERO = _0n$4;
5478
5865
  ONE = _1n$4;
5479
5866
  _lengths;
5480
- _sqrt;
5481
5867
  _mod;
5482
5868
  constructor(ORDER, opts = {}) {
5483
- if (ORDER <= _0n$4) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
5869
+ if (ORDER <= _1n$4) throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
5484
5870
  let _nbitLength = void 0;
5485
5871
  this.isLE = false;
5486
5872
  if (opts != null && typeof opts === "object") {
5487
5873
  if (typeof opts.BITS === "number") _nbitLength = opts.BITS;
5488
- if (typeof opts.sqrt === "function") this.sqrt = opts.sqrt;
5874
+ if (typeof opts.sqrt === "function") Object.defineProperty(this, "sqrt", {
5875
+ value: opts.sqrt,
5876
+ enumerable: true
5877
+ });
5489
5878
  if (typeof opts.isLE === "boolean") this.isLE = opts.isLE;
5490
- if (opts.allowedLengths) this._lengths = opts.allowedLengths?.slice();
5879
+ if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());
5491
5880
  if (typeof opts.modFromBytes === "boolean") this._mod = opts.modFromBytes;
5492
5881
  }
5493
5882
  const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
@@ -5495,14 +5884,13 @@ var _Field = class {
5495
5884
  this.ORDER = ORDER;
5496
5885
  this.BITS = nBitLength;
5497
5886
  this.BYTES = nByteLength;
5498
- this._sqrt = void 0;
5499
- Object.preventExtensions(this);
5887
+ Object.freeze(this);
5500
5888
  }
5501
5889
  create(num) {
5502
5890
  return mod(num, this.ORDER);
5503
5891
  }
5504
5892
  isValid(num) {
5505
- if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
5893
+ if (typeof num !== "bigint") throw new TypeError("invalid field element: expected bigint, got " + typeof num);
5506
5894
  return _0n$4 <= num && num < this.ORDER;
5507
5895
  }
5508
5896
  is0(num) {
@@ -5554,8 +5942,9 @@ var _Field = class {
5554
5942
  return invert(num, this.ORDER);
5555
5943
  }
5556
5944
  sqrt(num) {
5557
- if (!this._sqrt) this._sqrt = FpSqrt(this.ORDER);
5558
- return this._sqrt(this, num);
5945
+ let sqrt = FIELD_SQRT.get(this);
5946
+ if (!sqrt) FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
5947
+ return sqrt(this, num);
5559
5948
  }
5560
5949
  toBytes(num) {
5561
5950
  return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
@@ -5564,7 +5953,7 @@ var _Field = class {
5564
5953
  abytes(bytes);
5565
5954
  const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;
5566
5955
  if (allowedLengths) {
5567
- if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
5956
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
5568
5957
  const padded = new Uint8Array(BYTES);
5569
5958
  padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
5570
5959
  bytes = padded;
@@ -5581,53 +5970,95 @@ var _Field = class {
5581
5970
  return FpInvertBatch(this, lst);
5582
5971
  }
5583
5972
  cmov(a, b, condition) {
5973
+ abool(condition, "condition");
5584
5974
  return condition ? b : a;
5585
5975
  }
5586
5976
  };
5977
+ Object.freeze(_Field.prototype);
5587
5978
  /**
5588
5979
  * Creates a finite field. Major performance optimizations:
5589
5980
  * * 1. Denormalized operations like mulN instead of mul.
5590
5981
  * * 2. Identical object shape: never add or remove keys.
5591
- * * 3. `Object.freeze`.
5982
+ * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.
5592
5983
  * Fragile: always run a benchmark on a change.
5593
- * Security note: operations don't check 'isValid' for all elements for performance reasons,
5594
- * it is caller responsibility to check this.
5984
+ * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for
5985
+ * all elements for performance and protocol-flexibility reasons; callers are responsible for
5986
+ * supplying valid elements when they need canonical field behavior.
5595
5987
  * This is low-level code, please make sure you know what you're doing.
5596
5988
  *
5597
5989
  * Note about field properties:
5598
5990
  * * CHARACTERISTIC p = prime number, number of elements in main subgroup.
5599
5991
  * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
5600
5992
  *
5601
- * @param ORDER field order, probably prime, or could be composite
5602
- * @param bitLen how many bits the field consumes
5603
- * @param isLE (default: false) if encoding / decoding should be in little-endian
5604
- * @param redef optional faster redefinitions of sqrt and other methods
5993
+ * @param ORDER - field order, probably prime, or could be composite
5994
+ * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.
5995
+ * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight
5996
+ * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.
5997
+ * @example
5998
+ * Construct one prime field with optional overrides.
5999
+ *
6000
+ * ```ts
6001
+ * Field(11n);
6002
+ * ```
5605
6003
  */
5606
6004
  function Field(ORDER, opts = {}) {
5607
6005
  return new _Field(ORDER, opts);
5608
6006
  }
6007
+ /**
6008
+ * @param Fp - Field implementation.
6009
+ * @param elm - Value to square-root.
6010
+ * @returns Even square root.
6011
+ * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}
6012
+ * @example
6013
+ * Select the even square root when two roots exist.
6014
+ *
6015
+ * ```ts
6016
+ * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';
6017
+ * const Fp = Field(17n);
6018
+ * const root = FpSqrtEven(Fp, 4n);
6019
+ * ```
6020
+ */
5609
6021
  function FpSqrtEven(Fp, elm) {
5610
- if (!Fp.isOdd) throw new Error("Field doesn't have isOdd");
5611
- const root = Fp.sqrt(elm);
5612
- return Fp.isOdd(root) ? Fp.neg(root) : root;
6022
+ const F = Fp;
6023
+ if (!F.isOdd) throw new Error("Field doesn't have isOdd");
6024
+ const root = F.sqrt(elm);
6025
+ return F.isOdd(root) ? F.neg(root) : root;
5613
6026
  }
5614
6027
  /**
5615
6028
  * Returns total number of bytes consumed by the field element.
5616
6029
  * For example, 32 bytes for usual 256-bit weierstrass curve.
5617
- * @param fieldOrder number of field elements, usually CURVE.n
6030
+ * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an
6031
+ * order greater than 1.
5618
6032
  * @returns byte length of field
6033
+ * @throws If the field order is not a bigint. {@link Error}
6034
+ * @example
6035
+ * Read the fixed-width byte length of one field.
6036
+ *
6037
+ * ```ts
6038
+ * getFieldBytesLength(255n);
6039
+ * ```
5619
6040
  */
5620
6041
  function getFieldBytesLength(fieldOrder) {
5621
6042
  if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
5622
- const bitLength = fieldOrder.toString(2).length;
6043
+ if (fieldOrder <= _1n$4) throw new Error("field order must be greater than 1");
6044
+ const bitLength = bitLen(fieldOrder - _1n$4);
5623
6045
  return Math.ceil(bitLength / 8);
5624
6046
  }
5625
6047
  /**
5626
6048
  * Returns minimal amount of bytes that can be safely reduced
5627
6049
  * by field order.
5628
6050
  * Should be 2^-128 for 128-bit curve such as P256.
5629
- * @param fieldOrder number of field elements, usually CURVE.n
6051
+ * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger
6052
+ * absolute floor for policy reasons.
6053
+ * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.
5630
6054
  * @returns byte length of target hash
6055
+ * @throws If the field order is invalid. {@link Error}
6056
+ * @example
6057
+ * Compute the minimum hash length needed for field reduction.
6058
+ *
6059
+ * ```ts
6060
+ * getMinHashLength(255n);
6061
+ * ```
5631
6062
  */
5632
6063
  function getMinHashLength(fieldOrder) {
5633
6064
  const length = getFieldBytesLength(fieldOrder);
@@ -5637,21 +6068,31 @@ function getMinHashLength(fieldOrder) {
5637
6068
  * "Constant-time" private key generation utility.
5638
6069
  * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
5639
6070
  * and convert them into private scalar, with the modulo bias being negligible.
5640
- * Needs at least 48 bytes of input for 32-byte private key.
5641
- * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
5642
- * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
5643
- * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
5644
- * @param hash hash output from SHA3 or a similar function
5645
- * @param groupOrder size of subgroup - (e.g. secp256k1.Point.Fn.ORDER)
5646
- * @param isLE interpret hash bytes as LE num
6071
+ * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard
6072
+ * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look
6073
+ * accidentally acceptable for real scalar derivation.
6074
+ * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},
6075
+ * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and
6076
+ * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380
6077
+ * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.
6078
+ * @param key - Uniform input bytes.
6079
+ * @param fieldOrder - Size of subgroup.
6080
+ * @param isLE - interpret hash bytes as LE num
5647
6081
  * @returns valid private scalar
6082
+ * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}
6083
+ * @example
6084
+ * Map hash output into a private scalar range.
6085
+ *
6086
+ * ```ts
6087
+ * mapHashToField(new Uint8Array(48).fill(1), 255n);
6088
+ * ```
5648
6089
  */
5649
6090
  function mapHashToField(key, fieldOrder, isLE = false) {
5650
6091
  abytes(key);
5651
6092
  const len = key.length;
5652
6093
  const fieldLen = getFieldBytesLength(fieldOrder);
5653
- const minLen = getMinHashLength(fieldOrder);
5654
- if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
6094
+ const minLen = Math.max(getMinHashLength(fieldOrder), 16);
6095
+ if (len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
5655
6096
  const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$4) + _1n$4;
5656
6097
  return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
5657
6098
  }
@@ -5666,6 +6107,55 @@ function mapHashToField(key, fieldOrder, isLE = false) {
5666
6107
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5667
6108
  const _0n$3 = /* @__PURE__ */ BigInt(0);
5668
6109
  const _1n$3 = /* @__PURE__ */ BigInt(1);
6110
+ /**
6111
+ * Validates the static surface of a point constructor.
6112
+ * This is only a cheap sanity check for the constructor hooks and fields consumed by generic
6113
+ * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.
6114
+ * @param Point - Runtime point constructor.
6115
+ * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}
6116
+ * @example
6117
+ * Check that one point constructor exposes the static hooks generic helpers need.
6118
+ *
6119
+ * ```ts
6120
+ * import { ed25519 } from '@noble/curves/ed25519.js';
6121
+ * import { validatePointCons } from '@noble/curves/abstract/curve.js';
6122
+ * validatePointCons(ed25519.Point);
6123
+ * ```
6124
+ */
6125
+ function validatePointCons(Point) {
6126
+ const pc = Point;
6127
+ if (typeof pc !== "function") throw new TypeError("Point must be a constructor");
6128
+ validateObject({
6129
+ Fp: pc.Fp,
6130
+ Fn: pc.Fn,
6131
+ fromAffine: pc.fromAffine,
6132
+ fromBytes: pc.fromBytes,
6133
+ fromHex: pc.fromHex
6134
+ }, {
6135
+ Fp: "object",
6136
+ Fn: "object",
6137
+ fromAffine: "function",
6138
+ fromBytes: "function",
6139
+ fromHex: "function"
6140
+ });
6141
+ validateField(pc.Fp);
6142
+ validateField(pc.Fn);
6143
+ }
6144
+ /**
6145
+ * Computes both candidates first, but the final selection still branches on `condition`, so this
6146
+ * is not a strict constant-time CMOV primitive.
6147
+ * @param condition - Whether to negate the point.
6148
+ * @param item - Point-like value.
6149
+ * @returns Original or negated value.
6150
+ * @example
6151
+ * Keep the point or return its negation based on one boolean branch.
6152
+ *
6153
+ * ```ts
6154
+ * import { negateCt } from '@noble/curves/abstract/curve.js';
6155
+ * import { p256 } from '@noble/curves/nist.js';
6156
+ * const maybeNegated = negateCt(true, p256.Point.BASE);
6157
+ * ```
6158
+ */
5669
6159
  function negateCt(condition, item) {
5670
6160
  const neg = item.negate();
5671
6161
  return condition ? neg : item;
@@ -5675,6 +6165,18 @@ function negateCt(condition, item) {
5675
6165
  * inversion on all of them. Inversion is very slow operation,
5676
6166
  * so this improves performance massively.
5677
6167
  * Optimization: converts a list of projective points to a list of identical points with Z=1.
6168
+ * Input points are left unchanged; the normalized points are returned as fresh instances.
6169
+ * @param c - Point constructor.
6170
+ * @param points - Projective points.
6171
+ * @returns Fresh projective points reconstructed from normalized affine coordinates.
6172
+ * @example
6173
+ * Batch-normalize projective points with a single shared inversion.
6174
+ *
6175
+ * ```ts
6176
+ * import { normalizeZ } from '@noble/curves/abstract/curve.js';
6177
+ * import { p256 } from '@noble/curves/nist.js';
6178
+ * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
6179
+ * ```
5678
6180
  */
5679
6181
  function normalizeZ(c, points) {
5680
6182
  const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
@@ -5753,8 +6255,18 @@ function assert0(n) {
5753
6255
  * - +1 window is neccessary for wNAF
5754
6256
  * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
5755
6257
  *
5756
- * @todo Research returning 2d JS array of windows, instead of a single window.
5757
- * This would allow windows to be in different memory locations
6258
+ * TODO: research returning a 2d JS array of windows instead of a single window.
6259
+ * This would allow windows to be in different memory locations.
6260
+ * @param Point - Point constructor.
6261
+ * @param bits - Scalar bit length.
6262
+ * @example
6263
+ * Elliptic curve multiplication of Point by scalar.
6264
+ *
6265
+ * ```ts
6266
+ * import { wNAF } from '@noble/curves/abstract/curve.js';
6267
+ * import { p256 } from '@noble/curves/nist.js';
6268
+ * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
6269
+ * ```
5758
6270
  */
5759
6271
  var wNAF = class {
5760
6272
  BASE;
@@ -5784,8 +6296,8 @@ var wNAF = class {
5784
6296
  * - 𝑊 is the window size
5785
6297
  * - 𝑛 is the bitlength of the curve order.
5786
6298
  * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
5787
- * @param point Point instance
5788
- * @param W window size
6299
+ * @param point - Point instance
6300
+ * @param W - window size
5789
6301
  * @returns precomputed point tables flattened to a single array
5790
6302
  */
5791
6303
  precomputeWindow(point, W) {
@@ -5828,8 +6340,9 @@ var wNAF = class {
5828
6340
  };
5829
6341
  }
5830
6342
  /**
5831
- * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
5832
- * @param acc accumulator point to add result of multiplication
6343
+ * Implements unsafe EC multiplication using precomputed tables
6344
+ * and w-ary non-adjacent form.
6345
+ * @param acc - accumulator point to add result of multiplication
5833
6346
  * @returns point
5834
6347
  */
5835
6348
  wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
@@ -5881,10 +6394,19 @@ var wNAF = class {
5881
6394
  * 30x faster vs naive addition on L=4096, 10x faster than precomputes.
5882
6395
  * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
5883
6396
  * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
5884
- * @param c Curve Point constructor
5885
- * @param fieldN field over CURVE.N - important that it's not over CURVE.P
5886
- * @param points array of L curve points
5887
- * @param scalars array of L scalars (aka secret keys / bigints)
6397
+ * @param c - Curve Point constructor
6398
+ * @param points - array of L curve points
6399
+ * @param scalars - array of L scalars (aka secret keys / bigints)
6400
+ * @returns MSM result point. Empty input is accepted and returns the identity.
6401
+ * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}
6402
+ * @example
6403
+ * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
6404
+ *
6405
+ * ```ts
6406
+ * import { pippenger } from '@noble/curves/abstract/curve.js';
6407
+ * import { p256 } from '@noble/curves/nist.js';
6408
+ * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);
6409
+ * ```
5888
6410
  */
5889
6411
  function pippenger(c, points, scalars) {
5890
6412
  const fieldN = c.Fn;
@@ -5927,7 +6449,33 @@ function createField(order, field, isLE) {
5927
6449
  return field;
5928
6450
  } else return Field(order, { isLE });
5929
6451
  }
5930
- /** Validates CURVE opts and creates fields */
6452
+ /**
6453
+ * Validates basic CURVE shape and field membership, then creates fields.
6454
+ * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
6455
+ * that the curve equation itself is otherwise sane.
6456
+ * @param type - Curve family.
6457
+ * @param CURVE - Curve parameters.
6458
+ * @param curveOpts - Optional field overrides:
6459
+ * - `Fp` (optional): Optional base-field override.
6460
+ * - `Fn` (optional): Optional scalar-field override.
6461
+ * @param FpFnLE - Whether field encoding is little-endian.
6462
+ * @returns Frozen curve parameters and fields.
6463
+ * @throws If the curve parameters or field overrides are invalid. {@link Error}
6464
+ * @example
6465
+ * Build curve fields from raw constants before constructing a curve instance.
6466
+ *
6467
+ * ```ts
6468
+ * const curve = createCurveFields('weierstrass', {
6469
+ * p: 17n,
6470
+ * n: 19n,
6471
+ * h: 1n,
6472
+ * a: 2n,
6473
+ * b: 2n,
6474
+ * Gx: 5n,
6475
+ * Gy: 1n,
6476
+ * });
6477
+ * ```
6478
+ */
5931
6479
  function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
5932
6480
  if (FpFnLE === void 0) FpFnLE = type === "edwards";
5933
6481
  if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
@@ -5955,6 +6503,20 @@ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
5955
6503
  Fn
5956
6504
  };
5957
6505
  }
6506
+ /**
6507
+ * @param randomSecretKey - Secret-key generator.
6508
+ * @param getPublicKey - Public-key derivation helper.
6509
+ * @returns Keypair generator.
6510
+ * @example
6511
+ * Build a `keygen()` helper from existing secret-key and public-key primitives.
6512
+ *
6513
+ * ```ts
6514
+ * import { createKeygen } from '@noble/curves/abstract/curve.js';
6515
+ * import { p256 } from '@noble/curves/nist.js';
6516
+ * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
6517
+ * const pair = keygen();
6518
+ * ```
6519
+ */
5958
6520
  function createKeygen(randomSecretKey, getPublicKey) {
5959
6521
  return function keygen(seed) {
5960
6522
  const secretKey = randomSecretKey(seed);
@@ -5974,7 +6536,7 @@ function createKeygen(randomSecretKey, getPublicKey) {
5974
6536
  * @module
5975
6537
  */
5976
6538
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5977
- const _0n$2 = BigInt(0), _1n$2 = BigInt(1), _2n$2 = BigInt(2), _8n$1 = BigInt(8);
6539
+ const _0n$2 = /* @__PURE__ */ BigInt(0), _1n$2 = /* @__PURE__ */ BigInt(1), _2n$2 = /* @__PURE__ */ BigInt(2), _8n$1 = /* @__PURE__ */ BigInt(8);
5978
6540
  function isEdValidXY(Fp, CURVE, x, y) {
5979
6541
  const x2 = Fp.sqr(x);
5980
6542
  const y2 = Fp.sqr(y);
@@ -5982,15 +6544,37 @@ function isEdValidXY(Fp, CURVE, x, y) {
5982
6544
  const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
5983
6545
  return Fp.eql(left, right);
5984
6546
  }
6547
+ /**
6548
+ * @param params - Curve parameters. See {@link EdwardsOpts}.
6549
+ * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.
6550
+ * @returns Edwards point constructor. Generator validation here only checks
6551
+ * that `(Gx, Gy)` satisfies the affine Edwards equation.
6552
+ * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`
6553
+ * are left to the caller's chosen parameters, since eager subgroup
6554
+ * validation here adds about 10-15ms to heavyweight imports like ed448.
6555
+ * The returned constructor also eagerly marks `Point.BASE` for W=8
6556
+ * precompute caching. Some code paths still assume
6557
+ * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.
6558
+ * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}
6559
+ * @example
6560
+ * ```ts
6561
+ * import { edwards } from '@noble/curves/abstract/edwards.js';
6562
+ * import { jubjub } from '@noble/curves/misc.js';
6563
+ * // Build a point constructor from explicit curve parameters, then use its base point.
6564
+ * const Point = edwards(jubjub.Point.CURVE());
6565
+ * Point.BASE.toHex();
6566
+ * ```
6567
+ */
5985
6568
  function edwards(params, extraOpts = {}) {
5986
- const validated = createCurveFields("edwards", params, extraOpts, extraOpts.FpFnLE);
6569
+ const opts = extraOpts;
6570
+ const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
5987
6571
  const { Fp, Fn } = validated;
5988
6572
  let CURVE = validated.CURVE;
5989
6573
  const { h: cofactor } = CURVE;
5990
- validateObject(extraOpts, {}, { uvRatio: "function" });
6574
+ validateObject(opts, {}, { uvRatio: "function" });
5991
6575
  const MASK = _2n$2 << BigInt(Fn.BYTES * 8) - _1n$2;
5992
6576
  const modP = (n) => Fp.create(n);
5993
- const uvRatio = extraOpts.uvRatio || ((u, v) => {
6577
+ const uvRatio = opts.uvRatio === void 0 ? (u, v) => {
5994
6578
  try {
5995
6579
  return {
5996
6580
  isValid: true,
@@ -6002,7 +6586,7 @@ function edwards(params, extraOpts = {}) {
6002
6586
  value: _0n$2
6003
6587
  };
6004
6588
  }
6005
- });
6589
+ } : opts.uvRatio;
6006
6590
  if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
6007
6591
  /**
6008
6592
  * Asserts coordinate is valid: 0 <= n < MASK.
@@ -6016,35 +6600,6 @@ function edwards(params, extraOpts = {}) {
6016
6600
  function aedpoint(other) {
6017
6601
  if (!(other instanceof Point)) throw new Error("EdwardsPoint expected");
6018
6602
  }
6019
- const toAffineMemo = memoized((p, iz) => {
6020
- const { X, Y, Z } = p;
6021
- const is0 = p.is0();
6022
- if (iz == null) iz = is0 ? _8n$1 : Fp.inv(Z);
6023
- const x = modP(X * iz);
6024
- const y = modP(Y * iz);
6025
- const zz = Fp.mul(Z, iz);
6026
- if (is0) return {
6027
- x: _0n$2,
6028
- y: _1n$2
6029
- };
6030
- if (zz !== _1n$2) throw new Error("invZ was invalid");
6031
- return {
6032
- x,
6033
- y
6034
- };
6035
- });
6036
- const assertValidMemo = memoized((p) => {
6037
- const { a, d } = CURVE;
6038
- if (p.is0()) throw new Error("bad point: ZERO");
6039
- const { X, Y, Z, T } = p;
6040
- const X2 = modP(X * X);
6041
- const Y2 = modP(Y * Y);
6042
- const Z2 = modP(Z * Z);
6043
- const Z4 = modP(Z2 * Z2);
6044
- if (modP(Z2 * modP(modP(X2 * a) + Y2)) !== modP(Z4 + modP(d * modP(X2 * Y2)))) throw new Error("bad point: equation left != right (1)");
6045
- if (modP(X * Y) !== modP(Z * T)) throw new Error("bad point: equation left != right (2)");
6046
- return true;
6047
- });
6048
6603
  class Point {
6049
6604
  static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n$2, modP(CURVE.Gx * CURVE.Gy));
6050
6605
  static ZERO = new Point(_0n$2, _1n$2, _1n$2, _0n$2);
@@ -6064,6 +6619,11 @@ function edwards(params, extraOpts = {}) {
6064
6619
  static CURVE() {
6065
6620
  return CURVE;
6066
6621
  }
6622
+ /**
6623
+ * Create one extended Edwards point from affine coordinates.
6624
+ * Does NOT validate that the point is on-curve or torsion-free.
6625
+ * Use `.assertValidity()` on adversarial inputs.
6626
+ */
6067
6627
  static fromAffine(p) {
6068
6628
  if (p instanceof Point) throw new Error("extended point not allowed");
6069
6629
  const { x, y } = p || {};
@@ -6108,7 +6668,16 @@ function edwards(params, extraOpts = {}) {
6108
6668
  return this;
6109
6669
  }
6110
6670
  assertValidity() {
6111
- assertValidMemo(this);
6671
+ const p = this;
6672
+ const { a, d } = CURVE;
6673
+ if (p.is0()) throw new Error("bad point: ZERO");
6674
+ const { X, Y, Z, T } = p;
6675
+ const X2 = modP(X * X);
6676
+ const Y2 = modP(Y * Y);
6677
+ const Z2 = modP(Z * Z);
6678
+ const Z4 = modP(Z2 * Z2);
6679
+ if (modP(Z2 * modP(modP(X2 * a) + Y2)) !== modP(Z4 + modP(d * modP(X2 * Y2)))) throw new Error("bad point: equation left != right (1)");
6680
+ if (modP(X * Y) !== modP(Z * T)) throw new Error("bad point: equation left != right (2)");
6112
6681
  }
6113
6682
  equals(other) {
6114
6683
  aedpoint(other);
@@ -6162,27 +6731,44 @@ function edwards(params, extraOpts = {}) {
6162
6731
  return new Point(X3, Y3, modP(F * G), T3);
6163
6732
  }
6164
6733
  subtract(other) {
6734
+ aedpoint(other);
6165
6735
  return this.add(other.negate());
6166
6736
  }
6167
6737
  multiply(scalar) {
6168
- if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: expected 1 <= sc < curve.n");
6738
+ if (!Fn.isValidNot0(scalar)) throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
6169
6739
  const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));
6170
6740
  return normalizeZ(Point, [p, f])[0];
6171
6741
  }
6172
- multiplyUnsafe(scalar, acc = Point.ZERO) {
6173
- if (!Fn.isValid(scalar)) throw new Error("invalid scalar: expected 0 <= sc < curve.n");
6742
+ multiplyUnsafe(scalar) {
6743
+ if (!Fn.isValid(scalar)) throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
6174
6744
  if (scalar === _0n$2) return Point.ZERO;
6175
6745
  if (this.is0() || scalar === _1n$2) return this;
6176
- return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p), acc);
6746
+ return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));
6177
6747
  }
6178
6748
  isSmallOrder() {
6179
- return this.multiplyUnsafe(cofactor).is0();
6749
+ return this.clearCofactor().is0();
6180
6750
  }
6181
6751
  isTorsionFree() {
6182
6752
  return wnaf.unsafe(this, CURVE.n).is0();
6183
6753
  }
6184
6754
  toAffine(invertedZ) {
6185
- return toAffineMemo(this, invertedZ);
6755
+ const p = this;
6756
+ let iz = invertedZ;
6757
+ const { X, Y, Z } = p;
6758
+ const is0 = p.is0();
6759
+ if (iz == null) iz = is0 ? _8n$1 : Fp.inv(Z);
6760
+ const x = modP(X * iz);
6761
+ const y = modP(Y * iz);
6762
+ const zz = Fp.mul(Z, iz);
6763
+ if (is0) return {
6764
+ x: _0n$2,
6765
+ y: _1n$2
6766
+ };
6767
+ if (zz !== _1n$2) throw new Error("invZ was invalid");
6768
+ return {
6769
+ x,
6770
+ y
6771
+ };
6186
6772
  }
6187
6773
  clearCofactor() {
6188
6774
  if (cofactor === _1n$2) return this;
@@ -6202,13 +6788,25 @@ function edwards(params, extraOpts = {}) {
6202
6788
  }
6203
6789
  }
6204
6790
  const wnaf = new wNAF(Point, Fn.BITS);
6205
- Point.BASE.precompute(8);
6791
+ if (Fn.BITS >= 8) Point.BASE.precompute(8);
6792
+ Object.freeze(Point.prototype);
6793
+ Object.freeze(Point);
6206
6794
  return Point;
6207
6795
  }
6208
6796
  /**
6209
6797
  * Base class for prime-order points like Ristretto255 and Decaf448.
6210
6798
  * These points eliminate cofactor issues by representing equivalence classes
6211
- * of Edwards curve points.
6799
+ * of Edwards curve points. Multiple Edwards representatives can describe the
6800
+ * same abstract wrapper element, so wrapper validity is not the same thing as
6801
+ * the hidden representative being torsion-free.
6802
+ * @param ep - Backing Edwards point.
6803
+ * @example
6804
+ * Base class for prime-order points like Ristretto255 and Decaf448.
6805
+ *
6806
+ * ```ts
6807
+ * import { ristretto255 } from '@noble/curves/ed25519.js';
6808
+ * const point = ristretto255.Point.BASE.multiply(2n);
6809
+ * ```
6212
6810
  */
6213
6811
  var PrimeEdwardsPoint = class {
6214
6812
  static BASE;
@@ -6216,6 +6814,11 @@ var PrimeEdwardsPoint = class {
6216
6814
  static Fp;
6217
6815
  static Fn;
6218
6816
  ep;
6817
+ /**
6818
+ * Wrap one internal Edwards representative directly.
6819
+ * This is not a canonical encoding boundary: alternate Edwards
6820
+ * representatives may still describe the same abstract wrapper element.
6821
+ */
6219
6822
  constructor(ep) {
6220
6823
  this.ep = ep;
6221
6824
  }
@@ -6237,6 +6840,12 @@ var PrimeEdwardsPoint = class {
6237
6840
  assertValidity() {
6238
6841
  this.ep.assertValidity();
6239
6842
  }
6843
+ /**
6844
+ * Return affine coordinates of the current internal Edwards representative.
6845
+ * This is a convenience helper, not a canonical Ristretto/Decaf encoding.
6846
+ * Equal abstract elements may expose different `x` / `y`; use
6847
+ * `toBytes()` / `fromBytes()` for canonical roundtrips.
6848
+ */
6240
6849
  toAffine(invertedZ) {
6241
6850
  return this.ep.toAffine(invertedZ);
6242
6851
  }
@@ -6273,37 +6882,65 @@ var PrimeEdwardsPoint = class {
6273
6882
  return this.init(this.ep.negate());
6274
6883
  }
6275
6884
  precompute(windowSize, isLazy) {
6276
- return this.init(this.ep.precompute(windowSize, isLazy));
6885
+ this.ep.precompute(windowSize, isLazy);
6886
+ return this;
6277
6887
  }
6278
6888
  };
6279
6889
  /**
6280
6890
  * Initializes EdDSA signatures over given Edwards curve.
6891
+ * @param Point - Edwards point constructor.
6892
+ * @param cHash - Hash function.
6893
+ * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.
6894
+ * @returns EdDSA helper namespace.
6895
+ * @throws If the hash function, options, or derived point operations are invalid. {@link Error}
6896
+ * @example
6897
+ * Initializes EdDSA signatures over given Edwards curve.
6898
+ *
6899
+ * ```ts
6900
+ * import { eddsa } from '@noble/curves/abstract/edwards.js';
6901
+ * import { jubjub } from '@noble/curves/misc.js';
6902
+ * import { sha512 } from '@noble/hashes/sha2.js';
6903
+ * const sigs = eddsa(jubjub.Point, sha512);
6904
+ * const { secretKey, publicKey } = sigs.keygen();
6905
+ * const msg = new TextEncoder().encode('hello noble');
6906
+ * const sig = sigs.sign(msg, secretKey);
6907
+ * const isValid = sigs.verify(sig, msg, publicKey);
6908
+ * ```
6281
6909
  */
6282
6910
  function eddsa(Point, cHash, eddsaOpts = {}) {
6283
6911
  if (typeof cHash !== "function") throw new Error("\"hash\" function param is required");
6284
- validateObject(eddsaOpts, {}, {
6912
+ const hash = cHash;
6913
+ const opts = eddsaOpts;
6914
+ validateObject(opts, {}, {
6285
6915
  adjustScalarBytes: "function",
6286
6916
  randomBytes: "function",
6287
6917
  domain: "function",
6288
6918
  prehash: "function",
6919
+ zip215: "boolean",
6289
6920
  mapToCurve: "function"
6290
6921
  });
6291
- const { prehash } = eddsaOpts;
6922
+ const { prehash } = opts;
6292
6923
  const { BASE, Fp, Fn } = Point;
6293
- const randomBytes$1 = eddsaOpts.randomBytes || randomBytes;
6294
- const adjustScalarBytes = eddsaOpts.adjustScalarBytes || ((bytes) => bytes);
6295
- const domain = eddsaOpts.domain || ((data, ctx, phflag) => {
6924
+ const outputLen = hash.outputLen;
6925
+ const expectedLen = 2 * Fp.BYTES;
6926
+ if (outputLen !== void 0) {
6927
+ asafenumber(outputLen, "hash.outputLen");
6928
+ if (outputLen !== expectedLen) throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
6929
+ }
6930
+ const randomBytes$2 = opts.randomBytes === void 0 ? randomBytes : opts.randomBytes;
6931
+ const adjustScalarBytes = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
6932
+ const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
6296
6933
  abool(phflag, "phflag");
6297
6934
  if (ctx.length || phflag) throw new Error("Contexts/pre-hash are not supported");
6298
6935
  return data;
6299
- });
6936
+ } : opts.domain;
6300
6937
  function modN_LE(hash) {
6301
6938
  return Fn.create(bytesToNumberLE(hash));
6302
6939
  }
6303
6940
  function getPrivateScalar(key) {
6304
6941
  const len = lengths.secretKey;
6305
6942
  abytes(key, lengths.secretKey, "secretKey");
6306
- const hashed = abytes(cHash(key), 2 * len, "hashedSecretKey");
6943
+ const hashed = abytes(hash(key), 2 * len, "hashedSecretKey");
6307
6944
  const head = adjustScalarBytes(hashed.slice(0, len));
6308
6945
  return {
6309
6946
  head,
@@ -6311,7 +6948,9 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6311
6948
  scalar: modN_LE(head)
6312
6949
  };
6313
6950
  }
6314
- /** Convenience method that creates public key from scalar. RFC8032 5.1.5 */
6951
+ /** Convenience method that creates public key from scalar. RFC8032 5.1.5
6952
+ * Also exposes the derived scalar/prefix tuple and point form reused by sign().
6953
+ */
6315
6954
  function getExtendedPublicKey(secretKey) {
6316
6955
  const { head, prefix, scalar } = getPrivateScalar(secretKey);
6317
6956
  const point = BASE.multiply(scalar);
@@ -6328,7 +6967,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6328
6967
  return getExtendedPublicKey(secretKey).pointBytes;
6329
6968
  }
6330
6969
  function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
6331
- return modN_LE(cHash(domain(concatBytes(...msgs), abytes(context, void 0, "context"), !!prehash)));
6970
+ return modN_LE(hash(domain(concatBytes(...msgs), abytes(context, void 0, "context"), !!prehash)));
6332
6971
  }
6333
6972
  /** Signs message with secret key. RFC8032 5.1.6 */
6334
6973
  function sign(msg, secretKey, options = {}) {
@@ -6342,13 +6981,14 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6342
6981
  if (!Fn.isValid(s)) throw new Error("sign failed: invalid s");
6343
6982
  return abytes(concatBytes(R, Fn.toBytes(s)), lengths.signature, "result");
6344
6983
  }
6345
- const verifyOpts = { zip215: true };
6984
+ const verifyOpts = { zip215: opts.zip215 };
6346
6985
  /**
6347
- * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
6348
- * An extended group equation is checked.
6986
+ * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.
6987
+ * A cofactored verification equation is checked.
6349
6988
  */
6350
6989
  function verify(sig, msg, publicKey, options = verifyOpts) {
6351
- const { context, zip215 } = options;
6990
+ const { context } = options;
6991
+ const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
6352
6992
  const len = lengths.signature;
6353
6993
  sig = abytes(sig, len, "signature");
6354
6994
  msg = abytes(msg, void 0, "message");
@@ -6367,7 +7007,7 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6367
7007
  return false;
6368
7008
  }
6369
7009
  if (!zip215 && A.isSmallOrder()) return false;
6370
- const k = hashDomainToScalar(context, R.toBytes(), A.toBytes(), msg);
7010
+ const k = hashDomainToScalar(context, r, publicKey, msg);
6371
7011
  return R.add(A.multiplyUnsafe(k)).subtract(SB).clearCofactor().is0();
6372
7012
  }
6373
7013
  const _size = Fp.BYTES;
@@ -6377,15 +7017,16 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6377
7017
  signature: 2 * _size,
6378
7018
  seed: _size
6379
7019
  };
6380
- function randomSecretKey(seed = randomBytes$1(lengths.seed)) {
7020
+ function randomSecretKey(seed) {
7021
+ seed = seed === void 0 ? randomBytes$2(lengths.seed) : seed;
6381
7022
  return abytes(seed, lengths.seed, "seed");
6382
7023
  }
6383
7024
  function isValidSecretKey(key) {
6384
- return isBytes(key) && key.length === Fn.BYTES;
7025
+ return isBytes(key) && key.length === lengths.secretKey;
6385
7026
  }
6386
7027
  function isValidPublicKey(key, zip215) {
6387
7028
  try {
6388
- return !!Point.fromBytes(key, zip215);
7029
+ return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts.zip215 : zip215);
6389
7030
  } catch (error) {
6390
7031
  return false;
6391
7032
  }
@@ -6403,21 +7044,224 @@ function eddsa(Point, cHash, eddsaOpts = {}) {
6403
7044
  const u = is25519 ? Fp.div(_1n$2 + y, _1n$2 - y) : Fp.div(y - _1n$2, y + _1n$2);
6404
7045
  return Fp.toBytes(u);
6405
7046
  },
6406
- toMontgomerySecret(secretKey) {
6407
- const size = lengths.secretKey;
6408
- abytes(secretKey, size);
6409
- return adjustScalarBytes(cHash(secretKey.subarray(0, size))).subarray(0, size);
7047
+ toMontgomerySecret(secretKey) {
7048
+ const size = lengths.secretKey;
7049
+ abytes(secretKey, size);
7050
+ return adjustScalarBytes(hash(secretKey.subarray(0, size))).subarray(0, size);
7051
+ }
7052
+ };
7053
+ Object.freeze(lengths);
7054
+ Object.freeze(utils);
7055
+ return Object.freeze({
7056
+ keygen: createKeygen(randomSecretKey, getPublicKey),
7057
+ getPublicKey,
7058
+ sign,
7059
+ verify,
7060
+ utils,
7061
+ Point,
7062
+ lengths
7063
+ });
7064
+ }
7065
+
7066
+ //#endregion
7067
+ //#region node_modules/@noble/curves/abstract/fft.js
7068
+ function checkU32(n) {
7069
+ if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295) throw new Error("wrong u32 integer:" + n);
7070
+ return n;
7071
+ }
7072
+ /**
7073
+ * @param n - Input value.
7074
+ * @returns Next power of two within the u32/array-length domain.
7075
+ * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
7076
+ * @example
7077
+ * Round an integer up to the FFT size it needs.
7078
+ *
7079
+ * ```ts
7080
+ * nextPowerOfTwo(9);
7081
+ * ```
7082
+ */
7083
+ function nextPowerOfTwo(n) {
7084
+ checkU32(n);
7085
+ if (n <= 1) return 1;
7086
+ if (n > 2147483648) throw new Error("nextPowerOfTwo overflow: result does not fit u32");
7087
+ return 1 << log2(n - 1) + 1 >>> 0;
7088
+ }
7089
+ /**
7090
+ * Similar to `bitLen(x)-1` but much faster for small integers, like indices.
7091
+ * @param n - Input value.
7092
+ * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.
7093
+ * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}
7094
+ * @example
7095
+ * Compute the radix-2 stage count for one transform size.
7096
+ *
7097
+ * ```ts
7098
+ * log2(8);
7099
+ * ```
7100
+ */
7101
+ function log2(n) {
7102
+ checkU32(n);
7103
+ return 31 - Math.clz32(n);
7104
+ }
7105
+ function poly(field, roots, create, fft, length) {
7106
+ const F = field;
7107
+ const _create = create || ((len, elm) => new Array(len).fill(elm ?? F.ZERO));
7108
+ const isPoly = (x) => {
7109
+ if (Array.isArray(x)) return true;
7110
+ if (!ArrayBuffer.isView(x)) return false;
7111
+ const v = x;
7112
+ return typeof v.length === "number" && typeof v.slice === "function" && typeof v[Symbol.iterator] === "function";
7113
+ };
7114
+ const checkLength = (...lst) => {
7115
+ if (!lst.length) return 0;
7116
+ for (const i of lst) if (!isPoly(i)) throw new Error("poly: not polynomial: " + i);
7117
+ const L = lst[0].length;
7118
+ for (let i = 1; i < lst.length; i++) if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);
7119
+ if (length !== void 0 && L !== length) throw new Error(`poly: expected fixed length ${length}, got ${L}`);
7120
+ return L;
7121
+ };
7122
+ function findOmegaIndex(x, n, brp = false) {
7123
+ const bits = log2(n);
7124
+ const omega = brp ? roots.brp(bits) : roots.roots(bits);
7125
+ for (let i = 0; i < n; i++) if (F.eql(x, omega[i])) return i;
7126
+ return -1;
7127
+ }
7128
+ return {
7129
+ roots,
7130
+ create: _create,
7131
+ length,
7132
+ extend: (a, len) => {
7133
+ checkLength(a);
7134
+ const out = _create(len, F.ZERO);
7135
+ for (let i = 0; i < Math.min(a.length, len); i++) out[i] = a[i];
7136
+ return out;
7137
+ },
7138
+ degree: (a) => {
7139
+ checkLength(a);
7140
+ for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;
7141
+ return -1;
7142
+ },
7143
+ add: (a, b) => {
7144
+ const len = checkLength(a, b);
7145
+ const out = _create(len);
7146
+ for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);
7147
+ return out;
7148
+ },
7149
+ sub: (a, b) => {
7150
+ const len = checkLength(a, b);
7151
+ const out = _create(len);
7152
+ for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);
7153
+ return out;
7154
+ },
7155
+ dot: (a, b) => {
7156
+ const len = checkLength(a, b);
7157
+ const out = _create(len);
7158
+ for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);
7159
+ return out;
7160
+ },
7161
+ mul: (a, b) => {
7162
+ if (isPoly(b)) {
7163
+ const len = checkLength(a, b);
7164
+ if (fft) {
7165
+ const A = fft.direct(a, false, true);
7166
+ const B = fft.direct(b, false, true);
7167
+ for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]);
7168
+ return fft.inverse(A, true, false);
7169
+ } else {
7170
+ const res = _create(len);
7171
+ for (let i = 0; i < len; i++) for (let j = 0; j < len; j++) {
7172
+ const k = (i + j) % len;
7173
+ res[k] = F.add(res[k], F.mul(a[i], b[j]));
7174
+ }
7175
+ return res;
7176
+ }
7177
+ } else {
7178
+ const out = _create(checkLength(a));
7179
+ for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);
7180
+ return out;
7181
+ }
7182
+ },
7183
+ convolve(a, b) {
7184
+ const len = nextPowerOfTwo(a.length + b.length - 1);
7185
+ return this.mul(this.extend(a, len), this.extend(b, len));
7186
+ },
7187
+ shift(p, factor) {
7188
+ const out = _create(checkLength(p));
7189
+ out[0] = p[0];
7190
+ for (let i = 1, power = F.ONE; i < p.length; i++) {
7191
+ power = F.mul(power, factor);
7192
+ out[i] = F.mul(p[i], power);
7193
+ }
7194
+ return out;
7195
+ },
7196
+ clone: (a) => {
7197
+ checkLength(a);
7198
+ const out = _create(a.length);
7199
+ for (let i = 0; i < a.length; i++) out[i] = a[i];
7200
+ return out;
7201
+ },
7202
+ eval: (a, basis) => {
7203
+ checkLength(a, basis);
7204
+ let acc = F.ZERO;
7205
+ for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));
7206
+ return acc;
7207
+ },
7208
+ monomial: {
7209
+ basis: (x, n) => {
7210
+ const out = _create(n);
7211
+ let pow = F.ONE;
7212
+ for (let i = 0; i < n; i++) {
7213
+ out[i] = pow;
7214
+ pow = F.mul(pow, x);
7215
+ }
7216
+ return out;
7217
+ },
7218
+ eval: (a, x) => {
7219
+ checkLength(a);
7220
+ let acc = F.ZERO;
7221
+ for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]);
7222
+ return acc;
7223
+ }
7224
+ },
7225
+ lagrange: {
7226
+ basis: (x, n, brp = false, weights) => {
7227
+ const bits = log2(n);
7228
+ const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits));
7229
+ const out = _create(n);
7230
+ const idx = findOmegaIndex(x, n, brp);
7231
+ if (idx !== -1) {
7232
+ out[idx] = F.ONE;
7233
+ return out;
7234
+ }
7235
+ const tm = F.pow(x, BigInt(n));
7236
+ const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n)));
7237
+ const denom = _create(n);
7238
+ for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i]);
7239
+ const inv = F.invertBatch(denom);
7240
+ for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i], inv[i]));
7241
+ return out;
7242
+ },
7243
+ eval(a, x, brp = false) {
7244
+ checkLength(a);
7245
+ const idx = findOmegaIndex(x, a.length, brp);
7246
+ if (idx !== -1) return a[idx];
7247
+ const L = this.basis(x, a.length, brp);
7248
+ let acc = F.ZERO;
7249
+ for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));
7250
+ return acc;
7251
+ }
7252
+ },
7253
+ vanishing(roots) {
7254
+ checkLength(roots);
7255
+ const out = _create(roots.length + 1, F.ZERO);
7256
+ out[0] = F.ONE;
7257
+ for (const r of roots) {
7258
+ const neg = F.neg(r);
7259
+ for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]);
7260
+ out[0] = F.mul(out[0], neg);
7261
+ }
7262
+ return out;
6410
7263
  }
6411
7264
  };
6412
- return Object.freeze({
6413
- keygen: createKeygen(randomSecretKey, getPublicKey),
6414
- getPublicKey,
6415
- sign,
6416
- verify,
6417
- utils,
6418
- Point,
6419
- lengths
6420
- });
6421
7265
  }
6422
7266
 
6423
7267
  //#endregion
@@ -6426,7 +7270,8 @@ const os2ip = bytesToNumberBE;
6426
7270
  function i2osp(value, length) {
6427
7271
  asafenumber(value);
6428
7272
  asafenumber(length);
6429
- if (value < 0 || value >= 1 << 8 * length) throw new Error("invalid I2OSP input: " + value);
7273
+ if (length < 0 || length > 4) throw new Error("invalid I2OSP length: " + length);
7274
+ if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error("invalid I2OSP input: " + value);
6430
7275
  const res = Array.from({ length }).fill(0);
6431
7276
  for (let i = length - 1; i >= 0; i--) {
6432
7277
  res[i] = value & 255;
@@ -6441,11 +7286,29 @@ function strxor(a, b) {
6441
7286
  }
6442
7287
  function normDST(DST) {
6443
7288
  if (!isBytes(DST) && typeof DST !== "string") throw new Error("DST must be Uint8Array or ascii string");
6444
- return typeof DST === "string" ? asciiToBytes(DST) : DST;
7289
+ const dst = typeof DST === "string" ? asciiToBytes(DST) : DST;
7290
+ if (dst.length === 0) throw new Error("DST must be non-empty");
7291
+ return dst;
6445
7292
  }
6446
7293
  /**
6447
- * Produces a uniformly random byte string using a cryptographic hash function H that outputs b bits.
6448
- * [RFC 9380 5.3.1](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1).
7294
+ * Produces a uniformly random byte string using a cryptographic hash
7295
+ * function H that outputs b bits.
7296
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
7297
+ * @param msg - Input message.
7298
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
7299
+ * oversize-hashes DST when needed.
7300
+ * @param lenInBytes - Output length.
7301
+ * @param H - Hash function.
7302
+ * @returns Uniform byte string.
7303
+ * @throws If the message, DST, hash, or output length is invalid. {@link Error}
7304
+ * @example
7305
+ * Expand one message into uniform bytes with the XMD construction.
7306
+ *
7307
+ * ```ts
7308
+ * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';
7309
+ * import { sha256 } from '@noble/hashes/sha2.js';
7310
+ * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
7311
+ * ```
6449
7312
  */
6450
7313
  function expand_message_xmd(msg, DST, lenInBytes, H) {
6451
7314
  abytes(msg);
@@ -6456,12 +7319,12 @@ function expand_message_xmd(msg, DST, lenInBytes, H) {
6456
7319
  const ell = Math.ceil(lenInBytes / b_in_bytes);
6457
7320
  if (lenInBytes > 65535 || ell > 255) throw new Error("expand_message_xmd: invalid lenInBytes");
6458
7321
  const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
6459
- const Z_pad = i2osp(0, r_in_bytes);
7322
+ const Z_pad = new Uint8Array(r_in_bytes);
6460
7323
  const l_i_b_str = i2osp(lenInBytes, 2);
6461
7324
  const b = new Array(ell);
6462
7325
  const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
6463
7326
  b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
6464
- for (let i = 1; i <= ell; i++) b[i] = H(concatBytes(...[
7327
+ for (let i = 1; i < ell; i++) b[i] = H(concatBytes(...[
6465
7328
  strxor(b_0, b[i - 1]),
6466
7329
  i2osp(i + 1, 1),
6467
7330
  DST_prime
@@ -6473,7 +7336,29 @@ function expand_message_xmd(msg, DST, lenInBytes, H) {
6473
7336
  * 1. The collision resistance of H MUST be at least k bits.
6474
7337
  * 2. H MUST be an XOF that has been proved indifferentiable from
6475
7338
  * a random oracle under a reasonable cryptographic assumption.
6476
- * [RFC 9380 5.3.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2).
7339
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
7340
+ * @param msg - Input message.
7341
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
7342
+ * oversize-hashes DST when needed.
7343
+ * @param lenInBytes - Output length.
7344
+ * @param k - Target security level.
7345
+ * @param H - XOF hash function.
7346
+ * @returns Uniform byte string.
7347
+ * @throws If the message, DST, XOF, or output length is invalid. {@link Error}
7348
+ * @example
7349
+ * Expand one message into uniform bytes with the XOF construction.
7350
+ *
7351
+ * ```ts
7352
+ * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';
7353
+ * import { shake256 } from '@noble/hashes/sha3.js';
7354
+ * const uniform = expand_message_xof(
7355
+ * new TextEncoder().encode('hello noble'),
7356
+ * 'DST',
7357
+ * 32,
7358
+ * 128,
7359
+ * shake256
7360
+ * );
7361
+ * ```
6477
7362
  */
6478
7363
  function expand_message_xof(msg, DST, lenInBytes, k, H) {
6479
7364
  abytes(msg);
@@ -6488,11 +7373,27 @@ function expand_message_xof(msg, DST, lenInBytes, k, H) {
6488
7373
  }
6489
7374
  /**
6490
7375
  * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
6491
- * [RFC 9380 5.2](https://www.rfc-editor.org/rfc/rfc9380#section-5.2).
6492
- * @param msg a byte string containing the message to hash
6493
- * @param count the number of elements of F to output
6494
- * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
6495
- * @returns [u_0, ..., u_(count - 1)], a list of field elements.
7376
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
7377
+ * @param msg - Input message bytes.
7378
+ * @param count - Number of field elements to derive. Must be `>= 1`.
7379
+ * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
7380
+ * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
7381
+ * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
7382
+ * @example
7383
+ * Hash one message into field elements before mapping it onto a curve.
7384
+ *
7385
+ * ```ts
7386
+ * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';
7387
+ * import { sha256 } from '@noble/hashes/sha2.js';
7388
+ * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
7389
+ * DST: 'DST',
7390
+ * p: 17n,
7391
+ * m: 1,
7392
+ * k: 128,
7393
+ * expand: 'xmd',
7394
+ * hash: sha256,
7395
+ * });
7396
+ * ```
6496
7397
  */
6497
7398
  function hash_to_field(msg, count, options) {
6498
7399
  validateObject(options, {
@@ -6505,6 +7406,8 @@ function hash_to_field(msg, count, options) {
6505
7406
  asafenumber(hash.outputLen, "valid hash");
6506
7407
  abytes(msg);
6507
7408
  asafenumber(count);
7409
+ if (count < 1) throw new Error("hash_to_field: expected count >= 1");
7410
+ if (m < 1) throw new Error("hash_to_field: expected m >= 1");
6508
7411
  const log2p = p.toString(2).length;
6509
7412
  const L = Math.ceil((log2p + k) / 8);
6510
7413
  const len_in_bytes = count * m * L;
@@ -6524,10 +7427,42 @@ function hash_to_field(msg, count, options) {
6524
7427
  }
6525
7428
  return u;
6526
7429
  }
6527
- const _DST_scalar = asciiToBytes("HashToScalar-");
6528
- /** Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. */
7430
+ const _DST_scalar = "HashToScalar-";
7431
+ /**
7432
+ * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
7433
+ * @param Point - Point constructor.
7434
+ * @param mapToCurve - Map-to-curve function.
7435
+ * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
7436
+ * the shared defaults bundle for the returned helpers.
7437
+ * @returns Hash-to-curve helper namespace.
7438
+ * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
7439
+ * @example
7440
+ * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
7441
+ *
7442
+ * ```ts
7443
+ * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';
7444
+ * import { p256 } from '@noble/curves/nist.js';
7445
+ * import { sha256 } from '@noble/hashes/sha2.js';
7446
+ * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
7447
+ * DST: 'P256_XMD:SHA-256_SSWU_RO_',
7448
+ * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
7449
+ * p: p256.Point.Fp.ORDER,
7450
+ * m: 1,
7451
+ * k: 128,
7452
+ * expand: 'xmd',
7453
+ * hash: sha256,
7454
+ * });
7455
+ * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
7456
+ * ```
7457
+ */
6529
7458
  function createHasher(Point, mapToCurve, defaults) {
6530
7459
  if (typeof mapToCurve !== "function") throw new Error("mapToCurve() must be defined");
7460
+ const snapshot = (src) => Object.freeze({
7461
+ ...src,
7462
+ DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,
7463
+ ...src.encodeDST === void 0 ? {} : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }
7464
+ });
7465
+ const safeDefaults = snapshot(defaults);
6531
7466
  function map(num) {
6532
7467
  return Point.fromAffine(mapToCurve(num));
6533
7468
  }
@@ -6537,21 +7472,23 @@ function createHasher(Point, mapToCurve, defaults) {
6537
7472
  P.assertValidity();
6538
7473
  return P;
6539
7474
  }
6540
- return {
6541
- defaults: Object.freeze(defaults),
7475
+ return Object.freeze({
7476
+ get defaults() {
7477
+ return snapshot(safeDefaults);
7478
+ },
6542
7479
  Point,
6543
7480
  hashToCurve(msg, options) {
6544
- const u = hash_to_field(msg, 2, Object.assign({}, defaults, options));
7481
+ const u = hash_to_field(msg, 2, Object.assign({}, safeDefaults, options));
6545
7482
  const u0 = map(u[0]);
6546
7483
  const u1 = map(u[1]);
6547
7484
  return clear(u0.add(u1));
6548
7485
  },
6549
7486
  encodeToCurve(msg, options) {
6550
- const optsDst = defaults.encodeDST ? { DST: defaults.encodeDST } : {};
6551
- return clear(map(hash_to_field(msg, 1, Object.assign({}, defaults, optsDst, options))[0]));
7487
+ const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
7488
+ return clear(map(hash_to_field(msg, 1, Object.assign({}, safeDefaults, optsDst, options))[0]));
6552
7489
  },
6553
7490
  mapToCurve(scalars) {
6554
- if (defaults.m === 1) {
7491
+ if (safeDefaults.m === 1) {
6555
7492
  if (typeof scalars !== "bigint") throw new Error("expected bigint (m=1)");
6556
7493
  return clear(map([scalars]));
6557
7494
  }
@@ -6561,13 +7498,551 @@ function createHasher(Point, mapToCurve, defaults) {
6561
7498
  },
6562
7499
  hashToScalar(msg, options) {
6563
7500
  const N = Point.Fn.ORDER;
6564
- return hash_to_field(msg, 1, Object.assign({}, defaults, {
7501
+ return hash_to_field(msg, 1, Object.assign({}, safeDefaults, {
6565
7502
  p: N,
6566
7503
  m: 1,
6567
7504
  DST: _DST_scalar
6568
7505
  }, options))[0][0];
6569
7506
  }
7507
+ });
7508
+ }
7509
+
7510
+ //#endregion
7511
+ //#region node_modules/@noble/curves/abstract/frost.js
7512
+ /**
7513
+ * FROST: Flexible Round-Optimized Schnorr Threshold Protocol for Two-Round Schnorr Signatures.
7514
+ *
7515
+ * See [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/) and [frost.zfnd.org](https://frost.zfnd.org).
7516
+ * @module
7517
+ */
7518
+ const validateSigners = (signers) => {
7519
+ if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max)) throw new Error("Wrong signers info: min=" + signers.min + " max=" + signers.max);
7520
+ if (signers.min < 2 || signers.max < 2 || signers.min > signers.max) throw new Error("Wrong signers info: min=" + signers.min + " max=" + signers.max);
7521
+ };
7522
+ const validateCommitmentsNum = (signers, len) => {
7523
+ if (len < signers.min || len > signers.max) throw new Error("Wrong number of commitments=" + len);
7524
+ };
7525
+ var AggErr = class extends Error {
7526
+ cheaters;
7527
+ constructor(msg, cheaters) {
7528
+ super(msg);
7529
+ this.cheaters = cheaters;
7530
+ }
7531
+ };
7532
+ function createFROST(opts) {
7533
+ validateObject(opts, {
7534
+ name: "string",
7535
+ hash: "function"
7536
+ }, {
7537
+ hashToScalar: "function",
7538
+ validatePoint: "function",
7539
+ parsePublicKey: "function",
7540
+ adjustScalar: "function",
7541
+ adjustPoint: "function",
7542
+ challenge: "function",
7543
+ adjustNonces: "function",
7544
+ adjustSecret: "function",
7545
+ adjustPublic: "function",
7546
+ adjustGroupCommitmentShare: "function",
7547
+ adjustDKG: "function"
7548
+ });
7549
+ validatePointCons(opts.Point);
7550
+ const { Point } = opts;
7551
+ const Fn = opts.Fn === void 0 ? Point.Fn : opts.Fn;
7552
+ const hashBytes = opts.hash;
7553
+ const hashToScalar = opts.hashToScalar === void 0 ? (msg, opts = { DST: new Uint8Array() }) => {
7554
+ const t = hashBytes(concatBytes(opts.DST, msg));
7555
+ return Fn.create(Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t));
7556
+ } : opts.hashToScalar;
7557
+ const H1Prefix = utf8ToBytes(opts.H1 !== void 0 ? opts.H1 : opts.name + "rho");
7558
+ const H2Prefix = utf8ToBytes(opts.H2 !== void 0 ? opts.H2 : opts.name + "chal");
7559
+ const H3Prefix = utf8ToBytes(opts.H3 !== void 0 ? opts.H3 : opts.name + "nonce");
7560
+ const H4Prefix = utf8ToBytes(opts.H4 !== void 0 ? opts.H4 : opts.name + "msg");
7561
+ const H5Prefix = utf8ToBytes(opts.H5 !== void 0 ? opts.H5 : opts.name + "com");
7562
+ const HDKGPrefix = utf8ToBytes(opts.HDKG !== void 0 ? opts.HDKG : opts.name + "dkg");
7563
+ const HIDPrefix = utf8ToBytes(opts.HID !== void 0 ? opts.HID : opts.name + "id");
7564
+ const H1 = (msg) => hashToScalar(msg, { DST: H1Prefix });
7565
+ const H2 = (msg) => hashToScalar(msg, { DST: H2Prefix });
7566
+ const H3 = (msg) => hashToScalar(msg, { DST: H3Prefix });
7567
+ const H4 = (msg) => hashBytes(concatBytes(H4Prefix, msg));
7568
+ const H5 = (msg) => hashBytes(concatBytes(H5Prefix, msg));
7569
+ const HDKG = (msg) => hashToScalar(msg, { DST: HDKGPrefix });
7570
+ const HID = (msg) => hashToScalar(msg, { DST: HIDPrefix });
7571
+ const randomScalar = (rng = randomBytes) => {
7572
+ const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);
7573
+ return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
7574
+ };
7575
+ const serializePoint = (p) => p.toBytes();
7576
+ const parsePoint = (bytes) => {
7577
+ const p = Point.fromBytes(bytes);
7578
+ if (opts.validatePoint) opts.validatePoint(p);
7579
+ return p;
7580
+ };
7581
+ const nonceCommitments = (identifier, nonces) => ({
7582
+ identifier,
7583
+ hiding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.hiding))),
7584
+ binding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.binding)))
7585
+ });
7586
+ const adjustPoint = opts.adjustPoint === void 0 ? (n) => n : opts.adjustPoint;
7587
+ const validateIdentifier = (n) => {
7588
+ if (!Fn.isValid(n) || Fn.is0(n)) throw new Error("Invalid identifier " + n);
7589
+ return n;
7590
+ };
7591
+ const serializeIdentifier = (id) => bytesToHex(Fn.toBytes(validateIdentifier(id)));
7592
+ const parseIdentifier = (id) => {
7593
+ const n = validateIdentifier(Fn.fromBytes(hexToBytes(id)));
7594
+ if (serializeIdentifier(n) !== id) throw new Error("expected canonical identifier hex");
7595
+ return n;
7596
+ };
7597
+ const Signature = {
7598
+ encode: (R, z) => {
7599
+ let res = concatBytes(serializePoint(R), Fn.toBytes(z));
7600
+ if (opts.adjustTx) res = opts.adjustTx.encode(res);
7601
+ return res;
7602
+ },
7603
+ decode: (sig) => {
7604
+ if (opts.adjustTx) sig = opts.adjustTx.decode(sig);
7605
+ return {
7606
+ R: parsePoint(sig.subarray(0, -Fn.BYTES)),
7607
+ z: Fn.fromBytes(sig.subarray(-Fn.BYTES))
7608
+ };
7609
+ }
7610
+ };
7611
+ const genPointScalarPair = (rng = randomBytes) => {
7612
+ let n = randomScalar(rng);
7613
+ if (opts.adjustScalar) n = opts.adjustScalar(n);
7614
+ let p = Point.BASE.multiply(n);
7615
+ return {
7616
+ scalar: n,
7617
+ point: p
7618
+ };
7619
+ };
7620
+ const nrErr = "roots are unavailable in FROST polynomial mode";
7621
+ const Poly = poly(Fn, {
7622
+ info: {
7623
+ G: Fn.ZERO,
7624
+ oddFactor: Fn.ZERO,
7625
+ powerOfTwo: 0
7626
+ },
7627
+ roots() {
7628
+ throw new Error(nrErr);
7629
+ },
7630
+ brp() {
7631
+ throw new Error(nrErr);
7632
+ },
7633
+ inverse() {
7634
+ throw new Error(nrErr);
7635
+ },
7636
+ omega() {
7637
+ throw new Error(nrErr);
7638
+ },
7639
+ clear() {}
7640
+ });
7641
+ const msm = (points, scalars) => pippenger(Point, points, scalars);
7642
+ const polynomialEvaluate = (x, coeffs) => {
7643
+ if (!coeffs.length) throw new Error("empty coefficients");
7644
+ return Poly.monomial.eval(coeffs, x);
7645
+ };
7646
+ const deriveInterpolatingValue = (L, xi) => {
7647
+ const err = "invalid parameters";
7648
+ if (!L.some((x) => Fn.eql(x, xi))) throw new Error(err);
7649
+ const Lset = new Set(L);
7650
+ if (Lset.size !== L.length) throw new Error(err);
7651
+ if (!Lset.has(xi)) throw new Error(err);
7652
+ let num = Fn.ONE;
7653
+ let den = Fn.ONE;
7654
+ for (const x of L) {
7655
+ if (Fn.eql(x, xi)) continue;
7656
+ num = Fn.mul(num, x);
7657
+ den = Fn.mul(den, Fn.sub(x, xi));
7658
+ }
7659
+ return Fn.div(num, den);
7660
+ };
7661
+ const evalutateVSS = (identifier, commitment) => {
7662
+ return msm(commitment, Poly.monomial.basis(identifier, commitment.length));
7663
+ };
7664
+ const generateSecretPolynomial = (signers, secret, coeffs, rng = randomBytes) => {
7665
+ validateSigners(signers);
7666
+ const secretScalar = secret === void 0 ? randomScalar(rng) : Fn.fromBytes(secret);
7667
+ if (!coeffs) {
7668
+ coeffs = [];
7669
+ for (let i = 0; i < signers.min - 1; i++) coeffs.push(randomScalar(rng));
7670
+ }
7671
+ if (coeffs.length !== signers.min - 1) throw new Error("wrong coefficients length");
7672
+ const coefficients = [secretScalar, ...coeffs];
7673
+ return {
7674
+ coefficients,
7675
+ commitment: coefficients.map((i) => Point.BASE.multiply(i)),
7676
+ secret: secretScalar
7677
+ };
7678
+ };
7679
+ const ProofOfKnowledge = {
7680
+ challenge: (id, verKey, R) => HDKG(concatBytes(Fn.toBytes(id), serializePoint(verKey), serializePoint(R))),
7681
+ compute(id, coefficents, commitments, rng = randomBytes) {
7682
+ if (coefficents.length < 1) throw new Error("coefficients should have at least one element");
7683
+ const { point: R, scalar: k } = genPointScalarPair(rng);
7684
+ const verKey = commitments[0];
7685
+ const c = this.challenge(id, verKey, R);
7686
+ const mu = Fn.add(k, Fn.mul(coefficents[0], c));
7687
+ return Signature.encode(R, mu);
7688
+ },
7689
+ validate(id, commitment, proof) {
7690
+ if (commitment.length < 1) throw new Error("commitment should have at least one element");
7691
+ const { R, z } = Signature.decode(proof);
7692
+ const phi = parsePoint(commitment[0]);
7693
+ const c = this.challenge(id, phi, R);
7694
+ if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c)))) throw new Error("invalid proof of knowledge");
7695
+ }
7696
+ };
7697
+ const Basic = {
7698
+ challenge: (R, PK, msg) => {
7699
+ if (opts.challenge) return opts.challenge(R, PK, msg);
7700
+ return H2(concatBytes(serializePoint(R), serializePoint(PK), msg));
7701
+ },
7702
+ sign(msg, sk, rng = randomBytes) {
7703
+ const { point: R, scalar: r } = genPointScalarPair(rng);
7704
+ const PK = Point.BASE.multiply(sk);
7705
+ const c = this.challenge(R, PK, msg);
7706
+ return [R, Fn.add(r, Fn.mul(c, sk))];
7707
+ },
7708
+ verify(msg, R, z, PK) {
7709
+ if (opts.adjustPoint) PK = opts.adjustPoint(PK);
7710
+ if (opts.adjustPoint) R = opts.adjustPoint(R);
7711
+ const c = this.challenge(R, PK, msg);
7712
+ const zB = Point.BASE.multiply(z);
7713
+ const cA = PK.multiply(c);
7714
+ let check = zB.subtract(cA).subtract(R);
7715
+ if (check.clearCofactor) check = check.clearCofactor();
7716
+ return Point.ZERO.equals(check);
7717
+ }
7718
+ };
7719
+ const validateSecretShare = (identifier, commitment, signingShare) => {
7720
+ if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment))) throw new Error("invalid secret share");
7721
+ };
7722
+ const Identifier = {
7723
+ fromNumber(n) {
7724
+ if (!Number.isSafeInteger(n)) throw new Error("expected safe interger");
7725
+ return serializeIdentifier(BigInt(n));
7726
+ },
7727
+ derive(s) {
7728
+ if (typeof s !== "string") throw new Error("wrong identifier string: " + s);
7729
+ return serializeIdentifier(HID(utf8ToBytes(s)));
7730
+ }
7731
+ };
7732
+ const generateNonce = (secret, rng = randomBytes) => H3(concatBytes(rng(32), Fn.toBytes(secret)));
7733
+ const getGroupCommitment = (GPK, commitmentList, msg) => {
7734
+ const CL = commitmentList.map((i) => [
7735
+ i.identifier,
7736
+ parseIdentifier(i.identifier),
7737
+ parsePoint(i.hiding),
7738
+ parsePoint(i.binding)
7739
+ ]);
7740
+ CL.sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0);
7741
+ const Cbytes = [];
7742
+ for (const [_, id, hC, bC] of CL) Cbytes.push(Fn.toBytes(id), serializePoint(hC), serializePoint(bC));
7743
+ const encodedCommitmentHash = H5(concatBytes(...Cbytes));
7744
+ const rhoPrefix = concatBytes(serializePoint(GPK), H4(msg), encodedCommitmentHash);
7745
+ const bindingFactors = {};
7746
+ for (const [i, id] of CL) bindingFactors[i] = H1(concatBytes(rhoPrefix, Fn.toBytes(id)));
7747
+ const points = [];
7748
+ const scalars = [];
7749
+ for (const [i, _, hC, bC] of CL) {
7750
+ if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC)) throw new Error("infinity commitment");
7751
+ points.push(hC, bC);
7752
+ scalars.push(Fn.ONE, bindingFactors[i]);
7753
+ }
7754
+ const groupCommitment = msm(points, scalars);
7755
+ return {
7756
+ identifiers: CL.map((i) => i[1]),
7757
+ groupCommitment,
7758
+ bindingFactors
7759
+ };
7760
+ };
7761
+ const prepareShare = (PK, commitmentList, msg, identifier) => {
7762
+ const GPK = adjustPoint(parsePoint(PK));
7763
+ const id = parseIdentifier(identifier);
7764
+ const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment(GPK, commitmentList, msg);
7765
+ const bindingFactor = bindingFactors[identifier];
7766
+ return {
7767
+ lambda: deriveInterpolatingValue(identifiers, id),
7768
+ challenge: Basic.challenge(groupCommitment, GPK, msg),
7769
+ bindingFactor,
7770
+ groupCommitment
7771
+ };
7772
+ };
7773
+ Object.freeze(Identifier);
7774
+ const frost = {
7775
+ Identifier,
7776
+ DKG: Object.freeze({
7777
+ round1: (id, signers, secret, rng = randomBytes) => {
7778
+ validateSigners(signers);
7779
+ const idNum = parseIdentifier(id);
7780
+ const { coefficients, commitment } = generateSecretPolynomial(signers, secret, void 0, rng);
7781
+ const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng);
7782
+ const commitmentBytes = commitment.map(serializePoint);
7783
+ return {
7784
+ public: {
7785
+ identifier: serializeIdentifier(idNum),
7786
+ commitment: commitmentBytes,
7787
+ proofOfKnowledge
7788
+ },
7789
+ secret: {
7790
+ identifier: idNum,
7791
+ coefficients,
7792
+ commitment: commitment.map(serializePoint),
7793
+ signers: {
7794
+ min: signers.min,
7795
+ max: signers.max
7796
+ },
7797
+ step: 1
7798
+ }
7799
+ };
7800
+ },
7801
+ round2: (secret, others) => {
7802
+ if (others.length !== secret.signers.max - 1) throw new Error("wrong number of round1 packages");
7803
+ if (!secret.coefficients || secret.step === 3) throw new Error("round3 package used in round2");
7804
+ const res = {};
7805
+ for (const p of others) {
7806
+ if (p.commitment.length !== secret.signers.min) throw new Error("wrong number of commitments");
7807
+ const id = parseIdentifier(p.identifier);
7808
+ if (id === secret.identifier) throw new Error("duplicate id=" + serializeIdentifier(id));
7809
+ ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge);
7810
+ for (const c of p.commitment) parsePoint(c);
7811
+ if (res[p.identifier]) throw new Error("Duplicate id=" + id);
7812
+ const signingShare = Fn.toBytes(polynomialEvaluate(id, secret.coefficients));
7813
+ res[p.identifier] = {
7814
+ identifier: serializeIdentifier(secret.identifier),
7815
+ signingShare
7816
+ };
7817
+ }
7818
+ secret.step = 2;
7819
+ return res;
7820
+ },
7821
+ round3: (secret, round1, round2) => {
7822
+ if (round1.length !== secret.signers.max - 1) throw new Error("wrong length of round1 packages");
7823
+ if (!secret.coefficients || secret.step !== 2) throw new Error("round2 package used in round3");
7824
+ if (round2.length !== round1.length) throw new Error("wrong length of round2 packages");
7825
+ const merged = {};
7826
+ for (const r1 of round1) {
7827
+ if (!r1.identifier || !r1.commitment) throw new Error("wrong round1 share");
7828
+ merged[r1.identifier] = { ...r1 };
7829
+ }
7830
+ for (const r2 of round2) {
7831
+ if (!r2.identifier || !r2.signingShare) throw new Error("wrong round2 share");
7832
+ if (!merged[r2.identifier]) throw new Error("round1 share for " + r2.identifier + " is missing");
7833
+ merged[r2.identifier].signingShare = r2.signingShare;
7834
+ }
7835
+ if (Object.keys(merged).length !== round1.length) throw new Error("mismatch identifiers between rounds");
7836
+ let signingShare = Fn.ZERO;
7837
+ if (secret.commitment.length !== secret.signers.min) throw new Error("wrong commitments length");
7838
+ const localCommitment = secret.commitment.map(parsePoint);
7839
+ const localShare = polynomialEvaluate(secret.identifier, secret.coefficients);
7840
+ validateSecretShare(secret.identifier, localCommitment, localShare);
7841
+ const localCommitmentBytes = localCommitment.map(serializePoint);
7842
+ const commitments = { [serializeIdentifier(secret.identifier)]: localCommitmentBytes };
7843
+ for (const k in merged) {
7844
+ const v = merged[k];
7845
+ if (!v.signingShare || !v.commitment) throw new Error("mismatch identifiers");
7846
+ const id = parseIdentifier(k);
7847
+ const signingSharePart = Fn.fromBytes(v.signingShare);
7848
+ const commitment = v.commitment.map(parsePoint);
7849
+ validateSecretShare(secret.identifier, commitment, signingSharePart);
7850
+ signingShare = Fn.add(signingShare, signingSharePart);
7851
+ const idSer = serializeIdentifier(id);
7852
+ if (commitments[idSer]) throw new Error("duplicated id=" + idSer);
7853
+ commitments[idSer] = v.commitment;
7854
+ }
7855
+ signingShare = Fn.add(signingShare, localShare);
7856
+ const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO);
7857
+ for (const k in commitments) {
7858
+ const v = commitments[k];
7859
+ if (v.length !== secret.signers.min) throw new Error("wrong commitments length");
7860
+ for (let i = 0; i < v.length; i++) mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i]));
7861
+ }
7862
+ const mergedCommitmentBytes = mergedCommitment.map(serializePoint);
7863
+ const verifyingShares = {};
7864
+ for (const k in commitments) verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment));
7865
+ let res = {
7866
+ public: {
7867
+ signers: {
7868
+ min: secret.signers.min,
7869
+ max: secret.signers.max
7870
+ },
7871
+ commitments: mergedCommitmentBytes,
7872
+ verifyingShares: Object.fromEntries(Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()]))
7873
+ },
7874
+ secret: {
7875
+ identifier: serializeIdentifier(secret.identifier),
7876
+ signingShare: Fn.toBytes(signingShare)
7877
+ }
7878
+ };
7879
+ if (opts.adjustDKG) res = opts.adjustDKG(res);
7880
+ for (let i = 0; i < secret.coefficients.length; i++) secret.coefficients[i] -= secret.coefficients[i];
7881
+ delete secret.coefficients;
7882
+ secret.step = 3;
7883
+ return res;
7884
+ },
7885
+ clean(secret) {
7886
+ secret.identifier -= secret.identifier;
7887
+ if (secret.coefficients) for (let i = 0; i < secret.coefficients.length; i++) secret.coefficients[i] -= secret.coefficients[i];
7888
+ secret.step = 3;
7889
+ }
7890
+ }),
7891
+ trustedDealer(signers, identifiers, secret, rng = randomBytes) {
7892
+ validateSigners(signers);
7893
+ if (identifiers === void 0) {
7894
+ identifiers = [];
7895
+ for (let i = 1; i <= signers.max; i++) identifiers.push(Identifier.fromNumber(i));
7896
+ } else if (!Array.isArray(identifiers) || identifiers.length !== signers.max) throw new Error("identifiers should be array of " + signers.max);
7897
+ const identifierNums = {};
7898
+ for (const id of identifiers) {
7899
+ const idNum = parseIdentifier(id);
7900
+ if (id in identifierNums) throw new Error("duplicated id=" + id);
7901
+ identifierNums[id] = idNum;
7902
+ }
7903
+ const sp = generateSecretPolynomial(signers, secret, void 0, rng);
7904
+ const commitmentBytes = sp.commitment.map(serializePoint);
7905
+ const secretShares = {};
7906
+ const verifyingShares = {};
7907
+ for (const id of identifiers) {
7908
+ const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients);
7909
+ verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare));
7910
+ secretShares[id] = {
7911
+ identifier: id,
7912
+ signingShare: Fn.toBytes(signingShare)
7913
+ };
7914
+ }
7915
+ return {
7916
+ public: {
7917
+ signers: {
7918
+ min: signers.min,
7919
+ max: signers.max
7920
+ },
7921
+ commitments: commitmentBytes,
7922
+ verifyingShares
7923
+ },
7924
+ secretShares
7925
+ };
7926
+ },
7927
+ validateSecret(secret, pub) {
7928
+ validateSecretShare(parseIdentifier(secret.identifier), pub.commitments.map(parsePoint), Fn.fromBytes(secret.signingShare));
7929
+ },
7930
+ commit(secret, rng = randomBytes) {
7931
+ const secretScalar = Fn.fromBytes(secret.signingShare);
7932
+ const hiding = generateNonce(secretScalar, rng);
7933
+ const binding = generateNonce(secretScalar, rng);
7934
+ const nonces = {
7935
+ hiding: Fn.toBytes(hiding),
7936
+ binding: Fn.toBytes(binding)
7937
+ };
7938
+ return {
7939
+ nonces,
7940
+ commitments: nonceCommitments(secret.identifier, nonces)
7941
+ };
7942
+ },
7943
+ signShare(secret, pub, nonces, commitmentList, msg) {
7944
+ validateCommitmentsNum(pub.signers, commitmentList.length);
7945
+ const hidingNonce0 = Fn.fromBytes(nonces.hiding);
7946
+ const bindingNonce0 = Fn.fromBytes(nonces.binding);
7947
+ if (Fn.is0(hidingNonce0) || Fn.is0(bindingNonce0)) throw new Error("signing nonces already used");
7948
+ const expectedCommitment = {
7949
+ identifier: secret.identifier,
7950
+ hiding: serializePoint(Point.BASE.multiply(hidingNonce0)),
7951
+ binding: serializePoint(Point.BASE.multiply(bindingNonce0))
7952
+ };
7953
+ const commitment = commitmentList.find((i) => i.identifier === secret.identifier);
7954
+ if (!commitment) throw new Error("missing signer commitment");
7955
+ if (bytesToHex(commitment.hiding) !== bytesToHex(expectedCommitment.hiding) || bytesToHex(commitment.binding) !== bytesToHex(expectedCommitment.binding)) throw new Error("incorrect signer commitment");
7956
+ if (opts.adjustSecret) secret = opts.adjustSecret(secret, pub);
7957
+ if (opts.adjustPublic) pub = opts.adjustPublic(pub);
7958
+ const SK = Fn.fromBytes(secret.signingShare);
7959
+ const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, secret.identifier);
7960
+ const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces;
7961
+ const hidingNonce = opts.adjustNonces ? Fn.fromBytes(N.hiding) : hidingNonce0;
7962
+ const bindingNonce = opts.adjustNonces ? Fn.fromBytes(N.binding) : bindingNonce0;
7963
+ const t = Fn.mul(Fn.mul(lambda, SK), challenge);
7964
+ const t2 = Fn.mul(bindingNonce, bindingFactor);
7965
+ const r = Fn.toBytes(Fn.add(Fn.add(hidingNonce, t2), t));
7966
+ nonces.hiding.fill(0);
7967
+ nonces.binding.fill(0);
7968
+ return r;
7969
+ },
7970
+ verifyShare(pub, commitmentList, msg, identifier, sigShare) {
7971
+ if (opts.adjustPublic) pub = opts.adjustPublic(pub);
7972
+ const comm = commitmentList.find((i) => i.identifier === identifier);
7973
+ if (!comm) throw new Error("cannot find identifier commitment");
7974
+ const PK = parsePoint(pub.verifyingShares[identifier]);
7975
+ const hidingNonceCommitment = parsePoint(comm.hiding);
7976
+ const bindingNonceCommitment = parsePoint(comm.binding);
7977
+ const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, identifier);
7978
+ let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor));
7979
+ if (opts.adjustGroupCommitmentShare) commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare);
7980
+ const l = Point.BASE.multiply(Fn.fromBytes(sigShare));
7981
+ const r = commShare.add(PK.multiply(Fn.mul(challenge, lambda)));
7982
+ return l.equals(r);
7983
+ },
7984
+ aggregate(pub, commitmentList, msg, sigShares) {
7985
+ if (opts.adjustPublic) pub = opts.adjustPublic(pub);
7986
+ try {
7987
+ validateCommitmentsNum(pub.signers, commitmentList.length);
7988
+ } catch {
7989
+ throw new AggErr("aggregation failed", []);
7990
+ }
7991
+ const ids = commitmentList.map((i) => i.identifier);
7992
+ if (ids.length !== Object.keys(sigShares).length) throw new AggErr("aggregation failed", []);
7993
+ for (const id of ids) if (!(id in sigShares) || !(id in pub.verifyingShares)) throw new AggErr("aggregation failed", []);
7994
+ const GPK = parsePoint(pub.commitments[0]);
7995
+ const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg);
7996
+ let z = Fn.ZERO;
7997
+ for (const id of ids) z = Fn.add(z, Fn.fromBytes(sigShares[id]));
7998
+ if (!Basic.verify(msg, groupCommitment, z, GPK)) {
7999
+ const cheaters = [];
8000
+ for (const id of ids) if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id])) cheaters.push(id);
8001
+ throw new AggErr("aggregation failed", cheaters);
8002
+ }
8003
+ return Signature.encode(groupCommitment, z);
8004
+ },
8005
+ sign(msg, secretKey) {
8006
+ let sk = Fn.fromBytes(secretKey);
8007
+ if (opts.adjustScalar) sk = opts.adjustScalar(sk);
8008
+ const [R, z] = Basic.sign(msg, sk);
8009
+ return Signature.encode(R, z);
8010
+ },
8011
+ verify(sig, msg, publicKey) {
8012
+ const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey);
8013
+ const { R, z } = Signature.decode(sig);
8014
+ return Basic.verify(msg, R, z, PK);
8015
+ },
8016
+ combineSecret(shares, signers) {
8017
+ validateSigners(signers);
8018
+ if (!Array.isArray(shares) || shares.length < signers.min) throw new Error("wrong secret shares array");
8019
+ const points = [];
8020
+ const seen = {};
8021
+ for (const s of shares) {
8022
+ const idNum = parseIdentifier(s.identifier);
8023
+ const id = serializeIdentifier(idNum);
8024
+ if (seen[id]) throw new Error("duplicated id=" + id);
8025
+ seen[id] = true;
8026
+ points.push([idNum, Fn.fromBytes(s.signingShare)]);
8027
+ }
8028
+ const xCoords = points.map(([x]) => x);
8029
+ let res = Fn.ZERO;
8030
+ for (const [x, y] of points) res = Fn.add(res, Fn.mul(y, deriveInterpolatingValue(xCoords, x)));
8031
+ return Fn.toBytes(res);
8032
+ },
8033
+ utils: Object.freeze({
8034
+ Fn,
8035
+ randomScalar: (rng = randomBytes) => Fn.toBytes(genPointScalarPair(rng).scalar),
8036
+ generateSecretPolynomial: (signers, secret, coeffs, rng) => {
8037
+ const res = generateSecretPolynomial(signers, secret, coeffs, rng);
8038
+ return {
8039
+ ...res,
8040
+ commitment: res.commitment.map(serializePoint)
8041
+ };
8042
+ }
8043
+ })
6570
8044
  };
8045
+ return Object.freeze(frost);
6571
8046
  }
6572
8047
 
6573
8048
  //#endregion
@@ -6584,16 +8059,31 @@ const _1n$1 = BigInt(1);
6584
8059
  const _2n$1 = BigInt(2);
6585
8060
  function validateOpts(curve) {
6586
8061
  validateObject(curve, {
8062
+ P: "bigint",
8063
+ type: "string",
6587
8064
  adjustScalarBytes: "function",
6588
8065
  powPminus2: "function"
6589
- });
8066
+ }, { randomBytes: "function" });
6590
8067
  return Object.freeze({ ...curve });
6591
8068
  }
8069
+ /**
8070
+ * @param curveDef - Montgomery curve definition.
8071
+ * @returns ECDH helper namespace.
8072
+ * @throws If the curve definition or derived shared point is invalid. {@link Error}
8073
+ * @example
8074
+ * Perform one X25519 key exchange through the generic Montgomery helper.
8075
+ *
8076
+ * ```ts
8077
+ * import { x25519 } from '@noble/curves/ed25519.js';
8078
+ * const alice = x25519.keygen();
8079
+ * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);
8080
+ * ```
8081
+ */
6592
8082
  function montgomery(curveDef) {
6593
8083
  const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = validateOpts(curveDef);
6594
8084
  const is25519 = type === "x25519";
6595
8085
  if (!is25519 && type !== "x448") throw new Error("invalid type");
6596
- const randomBytes_ = rand || randomBytes;
8086
+ const randomBytes_ = rand === void 0 ? randomBytes : rand;
6597
8087
  const montgomeryBits = is25519 ? 255 : 448;
6598
8088
  const fieldLen = is25519 ? 32 : 56;
6599
8089
  const Gu = is25519 ? BigInt(9) : BigInt(5);
@@ -6633,10 +8123,10 @@ function montgomery(curveDef) {
6633
8123
  };
6634
8124
  }
6635
8125
  /**
6636
- * Montgomery x-only multiplication ladder.
6637
- * @param pointU u coordinate (x) on Montgomery Curve 25519
6638
- * @param scalar by which the point would be multiplied
6639
- * @returns new Point on Montgomery curve
8126
+ * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.
8127
+ * @param pointU - decoded Montgomery u coordinate for the selected curve
8128
+ * @param scalar - decoded clamped scalar by which the point is multiplied
8129
+ * @returns resulting Montgomery u coordinate for the selected curve
6640
8130
  */
6641
8131
  function montgomeryLadder(u, scalar) {
6642
8132
  aInRange("u", u, _0n$1, P);
@@ -6679,11 +8169,14 @@ function montgomery(curveDef) {
6679
8169
  publicKey: fieldLen,
6680
8170
  seed: fieldLen
6681
8171
  };
6682
- const randomSecretKey = (seed = randomBytes_(fieldLen)) => {
8172
+ const randomSecretKey = (seed) => {
8173
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
6683
8174
  abytes(seed, lengths.seed, "seed");
6684
8175
  return seed;
6685
8176
  };
6686
8177
  const utils = { randomSecretKey };
8178
+ Object.freeze(lengths);
8179
+ Object.freeze(utils);
6687
8180
  return Object.freeze({
6688
8181
  keygen: createKeygen(randomSecretKey, getPublicKey),
6689
8182
  getSharedSecret,
@@ -6734,10 +8227,12 @@ queries private.
6734
8227
  ## Modes
6735
8228
 
6736
8229
  - OPRF: simple mode, client doesn't need to know server public key
6737
- - VOPRF: verifable mode, allows client to verify that server used secret key corresponding to known public key
8230
+ - VOPRF: verifiable mode. It lets the client verify that the server used the
8231
+ secret key corresponding to a known public key
6738
8232
  - POPRF: partially oblivious mode, VOPRF + domain separation
6739
8233
 
6740
- There is also non-interactive mode (Evaluate) that supports creating Output in non-interactive mode with knowledge of secret key.
8234
+ There is also non-interactive mode (Evaluate), which creates Output
8235
+ non-interactively with knowledge of the secret key.
6741
8236
 
6742
8237
  Flow:
6743
8238
  - (once) Server generates secret and public keys, distributes public keys to clients
@@ -6749,17 +8244,39 @@ Flow:
6749
8244
  * @module
6750
8245
  */
6751
8246
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6752
- function createORPF(opts) {
8247
+ const _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);
8248
+ /**
8249
+ * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.
8250
+ * @returns OPRF helper namespace.
8251
+ * @example
8252
+ * Instantiate an OPRF suite from curve-specific hashing hooks.
8253
+ *
8254
+ * ```ts
8255
+ * import { createOPRF } from '@noble/curves/abstract/oprf.js';
8256
+ * import { p256, p256_hasher } from '@noble/curves/nist.js';
8257
+ * import { sha256 } from '@noble/hashes/sha2.js';
8258
+ * const oprf = createOPRF({
8259
+ * name: 'P256-SHA256',
8260
+ * Point: p256.Point,
8261
+ * hash: sha256,
8262
+ * hashToGroup: p256_hasher.hashToCurve,
8263
+ * hashToScalar: p256_hasher.hashToScalar,
8264
+ * });
8265
+ * const keys = oprf.oprf.generateKeyPair();
8266
+ * ```
8267
+ */
8268
+ function createOPRF(opts) {
6753
8269
  validateObject(opts, {
6754
8270
  name: "string",
6755
8271
  hash: "function",
6756
8272
  hashToScalar: "function",
6757
8273
  hashToGroup: "function"
6758
8274
  });
8275
+ validatePointCons(opts.Point);
6759
8276
  const { name, Point, hash } = opts;
6760
8277
  const { Fn } = Point;
6761
8278
  const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, { DST: concatBytes(asciiToBytes("HashToGroup-"), ctx) });
6762
- const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalar, ctx) });
8279
+ const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) });
6763
8280
  const randomScalar = (rng = randomBytes) => {
6764
8281
  const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);
6765
8282
  return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);
@@ -6779,6 +8296,11 @@ function createORPF(opts) {
6779
8296
  }
6780
8297
  return concatBytes(...res);
6781
8298
  }
8299
+ const inputBytes = (title, bytes) => {
8300
+ abytes(bytes, void 0, title);
8301
+ if (bytes.length > 65535) throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`);
8302
+ return bytes;
8303
+ };
6782
8304
  const hashInput = (...bytes) => hash(encode(...bytes, "Finalize"));
6783
8305
  function getTranscripts(B, C, D, ctx) {
6784
8306
  const seed = hash(encode(B.toBytes(), concatBytes(asciiToBytes("Seed-"), ctx)));
@@ -6837,6 +8359,8 @@ function createORPF(opts) {
6837
8359
  };
6838
8360
  }
6839
8361
  function deriveKeyPair(ctx, seed, info) {
8362
+ abytes(seed, 32, "seed");
8363
+ info = inputBytes("keyInfo", info);
6840
8364
  const dst = concatBytes(asciiToBytes("DeriveKeyPair"), ctx);
6841
8365
  const msg = concatBytes(seed, encode(info), Uint8Array.of(0));
6842
8366
  for (let counter = 0; counter <= 255; counter++) {
@@ -6850,7 +8374,13 @@ function createORPF(opts) {
6850
8374
  }
6851
8375
  throw new Error("Cannot derive key");
6852
8376
  }
8377
+ const wirePoint = (label, bytes) => {
8378
+ const point = Point.fromBytes(bytes);
8379
+ if (point.equals(Point.ZERO)) throw new Error(label + " point at infinity");
8380
+ return point;
8381
+ };
6853
8382
  function blind(ctx, input, rng = randomBytes) {
8383
+ input = inputBytes("input", input);
6854
8384
  const blind = randomScalar(rng);
6855
8385
  const inputPoint = hashToGroup(input, ctx);
6856
8386
  if (inputPoint.equals(Point.ZERO)) throw new Error("Input point at infinity");
@@ -6861,34 +8391,38 @@ function createORPF(opts) {
6861
8391
  };
6862
8392
  }
6863
8393
  function evaluate(ctx, secretKey, input) {
8394
+ input = inputBytes("input", input);
6864
8395
  const skS = Fn.fromBytes(secretKey);
6865
8396
  const inputPoint = hashToGroup(input, ctx);
6866
8397
  if (inputPoint.equals(Point.ZERO)) throw new Error("Input point at infinity");
6867
- return hashInput(input, inputPoint.multiply(skS).toBytes());
8398
+ const unblinded = inputPoint.multiply(skS).toBytes();
8399
+ return hashInput(input, unblinded);
6868
8400
  }
6869
- const oprf = {
8401
+ const oprf = Object.freeze({
6870
8402
  generateKeyPair,
6871
8403
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo),
6872
8404
  blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng),
6873
8405
  blindEvaluate(secretKey, blindedPoint) {
6874
8406
  const skS = Fn.fromBytes(secretKey);
6875
- return Point.fromBytes(blindedPoint).multiply(skS).toBytes();
8407
+ return wirePoint("blinded", blindedPoint).multiply(skS).toBytes();
6876
8408
  },
6877
8409
  finalize(input, blindBytes, evaluatedBytes) {
8410
+ input = inputBytes("input", input);
6878
8411
  const blind = Fn.fromBytes(blindBytes);
6879
- return hashInput(input, Point.fromBytes(evaluatedBytes).multiply(Fn.inv(blind)).toBytes());
8412
+ const unblinded = wirePoint("evaluated", evaluatedBytes).multiply(Fn.inv(blind)).toBytes();
8413
+ return hashInput(input, unblinded);
6880
8414
  },
6881
8415
  evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input)
6882
- };
6883
- const voprf = {
8416
+ });
8417
+ const voprf = Object.freeze({
6884
8418
  generateKeyPair,
6885
8419
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo),
6886
8420
  blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng),
6887
8421
  blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) {
6888
8422
  if (!Array.isArray(blinded)) throw new Error("expected array");
6889
8423
  const skS = Fn.fromBytes(secretKey);
6890
- const pkS = Point.fromBytes(publicKey);
6891
- const blindedPoints = blinded.map(Point.fromBytes);
8424
+ const pkS = wirePoint("public key", publicKey);
8425
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
6892
8426
  const evaluated = blindedPoints.map((i) => i.multiply(skS));
6893
8427
  const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);
6894
8428
  return {
@@ -6905,7 +8439,7 @@ function createORPF(opts) {
6905
8439
  },
6906
8440
  finalizeBatch(items, publicKey, proof) {
6907
8441
  if (!Array.isArray(items)) throw new Error("expected array");
6908
- verifyProof(ctxVOPRF, Point.fromBytes(publicKey), items.map((i) => i.blinded).map(Point.fromBytes), items.map((i) => i.evaluated).map(Point.fromBytes), proof);
8442
+ verifyProof(ctxVOPRF, wirePoint("public key", publicKey), items.map((i) => wirePoint("blinded", i.blinded)), items.map((i) => wirePoint("evaluated", i.evaluated)), proof);
6909
8443
  return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated));
6910
8444
  },
6911
8445
  finalize(input, blind, evaluated, blinded, publicKey, proof) {
@@ -6917,15 +8451,17 @@ function createORPF(opts) {
6917
8451
  }], publicKey, proof)[0];
6918
8452
  },
6919
8453
  evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input)
6920
- };
8454
+ });
6921
8455
  const poprf = (info) => {
8456
+ info = inputBytes("info", info);
6922
8457
  const m = hashToScalarPrefixed(encode("Info", info), ctxPOPRF);
6923
8458
  const T = Point.BASE.multiply(m);
6924
- return {
8459
+ return Object.freeze({
6925
8460
  generateKeyPair,
6926
8461
  deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo),
6927
8462
  blind(input, publicKey, rng = randomBytes) {
6928
- const pkS = Point.fromBytes(publicKey);
8463
+ input = inputBytes("input", input);
8464
+ const pkS = wirePoint("public key", publicKey);
6929
8465
  const tweakedKey = T.add(pkS);
6930
8466
  if (tweakedKey.equals(Point.ZERO)) throw new Error("tweakedKey point at infinity");
6931
8467
  const blind = randomScalar(rng);
@@ -6943,7 +8479,7 @@ function createORPF(opts) {
6943
8479
  const skS = Fn.fromBytes(secretKey);
6944
8480
  const t = Fn.add(skS, m);
6945
8481
  const invT = Fn.inv(t);
6946
- const blindedPoints = blinded.map(Point.fromBytes);
8482
+ const blindedPoints = blinded.map((i) => wirePoint("blinded", i));
6947
8483
  const evalPoints = blindedPoints.map((i) => i.multiply(invT));
6948
8484
  const proof = generateProof(ctxPOPRF, t, Point.BASE.multiply(t), evalPoints, blindedPoints, rng);
6949
8485
  return {
@@ -6960,12 +8496,13 @@ function createORPF(opts) {
6960
8496
  },
6961
8497
  finalizeBatch(items, proof, tweakedKey) {
6962
8498
  if (!Array.isArray(items)) throw new Error("expected array");
6963
- const evalPoints = items.map((i) => i.evaluated).map(Point.fromBytes);
6964
- verifyProof(ctxPOPRF, Point.fromBytes(tweakedKey), evalPoints, items.map((i) => i.blinded).map(Point.fromBytes), proof);
8499
+ const inputs = items.map((i) => inputBytes("input", i.input));
8500
+ const evalPoints = items.map((i) => wirePoint("evaluated", i.evaluated));
8501
+ verifyProof(ctxPOPRF, wirePoint("tweakedKey", tweakedKey), evalPoints, items.map((i) => wirePoint("blinded", i.blinded)), proof);
6965
8502
  return items.map((i, j) => {
6966
8503
  const blind = Fn.fromBytes(i.blind);
6967
8504
  const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();
6968
- return hashInput(i.input, info, point);
8505
+ return hashInput(inputs[j], info, point);
6969
8506
  });
6970
8507
  },
6971
8508
  finalize(input, blind, evaluated, blinded, proof, tweakedKey) {
@@ -6977,22 +8514,25 @@ function createORPF(opts) {
6977
8514
  }], proof, tweakedKey)[0];
6978
8515
  },
6979
8516
  evaluate(secretKey, input) {
8517
+ input = inputBytes("input", input);
6980
8518
  const skS = Fn.fromBytes(secretKey);
6981
8519
  const inputPoint = hashToGroup(input, ctxPOPRF);
6982
8520
  if (inputPoint.equals(Point.ZERO)) throw new Error("Input point at infinity");
6983
8521
  const t = Fn.add(skS, m);
6984
8522
  const invT = Fn.inv(t);
6985
- return hashInput(input, info, inputPoint.multiply(invT).toBytes());
8523
+ const unblinded = inputPoint.multiply(invT).toBytes();
8524
+ return hashInput(input, info, unblinded);
6986
8525
  }
6987
- };
8526
+ });
6988
8527
  };
6989
- return Object.freeze({
8528
+ const res = {
6990
8529
  name,
6991
8530
  oprf,
6992
8531
  voprf,
6993
8532
  poprf,
6994
- __tests: { Fn }
6995
- });
8533
+ __tests: Object.freeze({ Fn })
8534
+ };
8535
+ return Object.freeze(res);
6996
8536
  }
6997
8537
 
6998
8538
  //#endregion
@@ -7005,9 +8545,9 @@ function createORPF(opts) {
7005
8545
  * @module
7006
8546
  */
7007
8547
  /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7008
- const _0n = /* @__PURE__ */ BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
7009
- const _5n = BigInt(5), _8n = BigInt(8);
7010
- const ed25519_CURVE_p = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
8548
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);
8549
+ const _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);
8550
+ const ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
7011
8551
  const ed25519_CURVE = {
7012
8552
  p: ed25519_CURVE_p,
7013
8553
  n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
@@ -7061,26 +8601,59 @@ const ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
7061
8601
  const Fp = ed25519_Point.Fp;
7062
8602
  const Fn = ed25519_Point.Fn;
7063
8603
  function ed(opts) {
7064
- return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes }, opts));
8604
+ return eddsa(ed25519_Point, sha512, Object.assign({
8605
+ adjustScalarBytes,
8606
+ zip215: true
8607
+ }, opts));
7065
8608
  }
7066
8609
  /**
7067
8610
  * ed25519 curve with EdDSA signatures.
8611
+ * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided
8612
+ * 32-byte seed buffer instead of copying it.
7068
8613
  * @example
8614
+ * Generate one Ed25519 keypair, sign a message, and verify it.
8615
+ *
7069
8616
  * ```js
7070
8617
  * import { ed25519 } from '@noble/curves/ed25519.js';
7071
8618
  * const { secretKey, publicKey } = ed25519.keygen();
7072
8619
  * // const publicKey = ed25519.getPublicKey(secretKey);
7073
8620
  * const msg = new TextEncoder().encode('hello noble');
7074
8621
  * const sig = ed25519.sign(msg, secretKey);
7075
- * const isValid = ed25519.verify(sig, msg, pub); // ZIP215
8622
+ * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215
7076
8623
  * // RFC8032 / FIPS 186-5
7077
- * const isValid2 = ed25519.verify(sig, msg, pub, { zip215: false });
8624
+ * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });
7078
8625
  * ```
7079
8626
  */
7080
8627
  const ed25519 = /* @__PURE__ */ ed({});
7081
8628
  /**
8629
+ * FROST threshold signatures over ed25519. RFC 9591.
8630
+ * @example
8631
+ * Create one trusted-dealer package for 2-of-3 ed25519 signing.
8632
+ *
8633
+ * ```ts
8634
+ * const alice = ed25519_FROST.Identifier.derive('alice@example.com');
8635
+ * const bob = ed25519_FROST.Identifier.derive('bob@example.com');
8636
+ * const carol = ed25519_FROST.Identifier.derive('carol@example.com');
8637
+ * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
8638
+ * ```
8639
+ */
8640
+ const ed25519_FROST = createFROST({
8641
+ name: "FROST-ED25519-SHA512-v1",
8642
+ Point: ed25519_Point,
8643
+ validatePoint: (p) => {
8644
+ p.assertValidity();
8645
+ if (!p.isTorsionFree()) throw new Error("bad point: not torsion-free");
8646
+ },
8647
+ hash: sha512,
8648
+ H2: ""
8649
+ });
8650
+ /**
7082
8651
  * ECDH using curve25519 aka x25519.
8652
+ * `getSharedSecret()` rejects low-order peer inputs by default, and seeded
8653
+ * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.
7083
8654
  * @example
8655
+ * Derive one shared secret between two X25519 peers.
8656
+ *
7084
8657
  * ```js
7085
8658
  * import { x25519 } from '@noble/curves/ed25519.js';
7086
8659
  * const alice = x25519.keygen();
@@ -7175,7 +8748,17 @@ function map_to_curve_elligator2_edwards25519(u) {
7175
8748
  y: Fp.mul(yn, yd_inv)
7176
8749
  };
7177
8750
  }
7178
- /** Hashing to ed25519 points / field. RFC 9380 methods. */
8751
+ /**
8752
+ * Hashing to ed25519 points / field. RFC 9380 methods.
8753
+ * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the
8754
+ * internal map callback below consumes one field element bigint, not `[bigint]`.
8755
+ * @example
8756
+ * Hash one message onto the ed25519 curve.
8757
+ *
8758
+ * ```ts
8759
+ * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
8760
+ * ```
8761
+ */
7179
8762
  const ed25519_hasher = createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {
7180
8763
  DST: "edwards25519_XMD:SHA-512_ELL2_RO_",
7181
8764
  encodeDST: "edwards25519_XMD:SHA-512_ELL2_NU_",
@@ -7195,8 +8778,9 @@ const MAX_255B = /* @__PURE__ */ BigInt("0x7ffffffffffffffffffffffffffffffffffff
7195
8778
  const bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);
7196
8779
  /**
7197
8780
  * Computes Elligator map for Ristretto255.
7198
- * Described in [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#appendix-B) and on
7199
- * the [website](https://ristretto.group/formulas/elligator.html).
8781
+ * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds
8782
+ * `hash_to_ristretto255` on top of this helper.
8783
+ * Returns an internal Edwards representative, not a public `_RistrettoPoint`.
7200
8784
  */
7201
8785
  function calcElligatorRistrettoMap(r0) {
7202
8786
  const { d } = ed25519_CURVE;
@@ -7236,6 +8820,12 @@ var _RistrettoPoint = class _RistrettoPoint extends PrimeEdwardsPoint {
7236
8820
  constructor(ep) {
7237
8821
  super(ep);
7238
8822
  }
8823
+ /**
8824
+ * Create one Ristretto255 point from affine Edwards coordinates.
8825
+ * This wraps the internal Edwards representative directly and is not a
8826
+ * canonical ristretto255 decoding path.
8827
+ * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.
8828
+ */
7239
8829
  static fromAffine(ap) {
7240
8830
  return new _RistrettoPoint(ed25519_Point.fromAffine(ap));
7241
8831
  }
@@ -7246,7 +8836,7 @@ var _RistrettoPoint = class _RistrettoPoint extends PrimeEdwardsPoint {
7246
8836
  return new _RistrettoPoint(ep);
7247
8837
  }
7248
8838
  static fromBytes(bytes) {
7249
- abytes(bytes, 32);
8839
+ abytes$1(bytes, 32);
7250
8840
  const { a, d } = ed25519_CURVE;
7251
8841
  const P = ed25519_CURVE_p;
7252
8842
  const mod = (n) => Fp.create(n);
@@ -7271,10 +8861,10 @@ var _RistrettoPoint = class _RistrettoPoint extends PrimeEdwardsPoint {
7271
8861
  /**
7272
8862
  * Converts ristretto-encoded string to ristretto point.
7273
8863
  * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).
7274
- * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
8864
+ * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding
7275
8865
  */
7276
8866
  static fromHex(hex) {
7277
- return _RistrettoPoint.fromBytes(hexToBytes(hex));
8867
+ return _RistrettoPoint.fromBytes(hexToBytes$2(hex));
7278
8868
  }
7279
8869
  /**
7280
8870
  * Encodes ristretto point to Uint8Array.
@@ -7320,11 +8910,26 @@ var _RistrettoPoint = class _RistrettoPoint extends PrimeEdwardsPoint {
7320
8910
  return this.equals(_RistrettoPoint.ZERO);
7321
8911
  }
7322
8912
  };
7323
- /** Hashing to ristretto255 points / field. RFC 9380 methods. */
7324
- const ristretto255_hasher = {
8913
+ Object.freeze(_RistrettoPoint.BASE);
8914
+ Object.freeze(_RistrettoPoint.ZERO);
8915
+ Object.freeze(_RistrettoPoint.prototype);
8916
+ Object.freeze(_RistrettoPoint);
8917
+ /**
8918
+ * Hashing to ristretto255 points / field. RFC 9380 methods.
8919
+ * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496
8920
+ * §4.3.4 element-derivation building block, and `hashToScalar()` is a
8921
+ * library-specific helper for OPRF-style use.
8922
+ * @example
8923
+ * Hash one message onto ristretto255.
8924
+ *
8925
+ * ```ts
8926
+ * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));
8927
+ * ```
8928
+ */
8929
+ const ristretto255_hasher = Object.freeze({
7325
8930
  Point: _RistrettoPoint,
7326
8931
  hashToCurve(msg, options) {
7327
- const xmd = expand_message_xmd(msg, options?.DST || "ristretto255_XMD:SHA-512_R255MAP_RO_", 64, sha512);
8932
+ const xmd = expand_message_xmd(msg, options?.DST === void 0 ? "ristretto255_XMD:SHA-512_R255MAP_RO_" : options.DST, 64, sha512);
7328
8933
  return ristretto255_hasher.deriveToCurve(xmd);
7329
8934
  },
7330
8935
  hashToScalar(msg, options = { DST: _DST_scalar }) {
@@ -7332,34 +8937,75 @@ const ristretto255_hasher = {
7332
8937
  return Fn.create(bytesToNumberLE(xmd));
7333
8938
  },
7334
8939
  deriveToCurve(bytes) {
7335
- abytes(bytes, 64);
8940
+ abytes$1(bytes, 64);
7336
8941
  const R1 = calcElligatorRistrettoMap(bytes255ToNumberLE(bytes.subarray(0, 32)));
7337
8942
  const R2 = calcElligatorRistrettoMap(bytes255ToNumberLE(bytes.subarray(32, 64)));
7338
8943
  return new _RistrettoPoint(R1.add(R2));
7339
8944
  }
7340
- };
7341
- /** ristretto255 OPRF, defined in RFC 9497. */
7342
- const ristretto255_oprf = createORPF({
8945
+ });
8946
+ /**
8947
+ * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.
8948
+ * @example
8949
+ * Run one blind/evaluate/finalize OPRF round over ristretto255.
8950
+ *
8951
+ * ```ts
8952
+ * const input = new TextEncoder().encode('hello noble');
8953
+ * const keys = ristretto255_oprf.oprf.generateKeyPair();
8954
+ * const blind = ristretto255_oprf.oprf.blind(input);
8955
+ * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);
8956
+ * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);
8957
+ * ```
8958
+ */
8959
+ const ristretto255_oprf = createOPRF({
7343
8960
  name: "ristretto255-SHA512",
7344
8961
  Point: _RistrettoPoint,
7345
8962
  hash: sha512,
7346
8963
  hashToGroup: ristretto255_hasher.hashToCurve,
7347
8964
  hashToScalar: ristretto255_hasher.hashToScalar
7348
8965
  });
8966
+ /**
8967
+ * FROST threshold signatures over ristretto255. RFC 9591.
8968
+ * @example
8969
+ * Create one trusted-dealer package for 2-of-3 ristretto255 signing.
8970
+ *
8971
+ * ```ts
8972
+ * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');
8973
+ * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');
8974
+ * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');
8975
+ * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);
8976
+ * ```
8977
+ */
8978
+ const ristretto255_FROST = createFROST({
8979
+ name: "FROST-RISTRETTO255-SHA512-v1",
8980
+ Point: _RistrettoPoint,
8981
+ validatePoint: (p) => {
8982
+ p.assertValidity();
8983
+ },
8984
+ hash: sha512
8985
+ });
7349
8986
 
7350
8987
  //#endregion
7351
- //#region node_modules/@noble/hashes/esm/hmac.js
8988
+ //#region node_modules/@noble/hashes/hmac.js
7352
8989
  /**
7353
8990
  * HMAC: RFC2104 message authentication code.
7354
8991
  * @module
7355
8992
  */
7356
- var HMAC = class extends Hash {
7357
- constructor(hash, _key) {
7358
- super();
7359
- this.finished = false;
7360
- this.destroyed = false;
8993
+ /**
8994
+ * Internal class for HMAC.
8995
+ * Accepts any byte key, although RFC 2104 §3 recommends keys at least
8996
+ * `HashLen` bytes long.
8997
+ */
8998
+ var _HMAC = class {
8999
+ oHash;
9000
+ iHash;
9001
+ blockLen;
9002
+ outputLen;
9003
+ canXOF = false;
9004
+ finished = false;
9005
+ destroyed = false;
9006
+ constructor(hash, key) {
7361
9007
  ahash(hash);
7362
- const key = toBytes(_key);
9008
+ abytes$1(key, void 0, "key");
7363
9009
  this.iHash = hash.create();
7364
9010
  if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
7365
9011
  this.blockLen = this.iHash.blockLen;
@@ -7372,20 +9018,21 @@ var HMAC = class extends Hash {
7372
9018
  this.oHash = hash.create();
7373
9019
  for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
7374
9020
  this.oHash.update(pad);
7375
- clean$1(pad);
9021
+ clean(pad);
7376
9022
  }
7377
9023
  update(buf) {
7378
- aexists$1(this);
9024
+ aexists(this);
7379
9025
  this.iHash.update(buf);
7380
9026
  return this;
7381
9027
  }
7382
9028
  digestInto(out) {
7383
- aexists$1(this);
7384
- abytes$1(out, this.outputLen);
9029
+ aexists(this);
9030
+ aoutput(out, this);
7385
9031
  this.finished = true;
7386
- this.iHash.digestInto(out);
7387
- this.oHash.update(out);
7388
- this.oHash.digestInto(out);
9032
+ const buf = out.subarray(0, this.outputLen);
9033
+ this.iHash.digestInto(buf);
9034
+ this.oHash.update(buf);
9035
+ this.oHash.digestInto(buf);
7389
9036
  this.destroy();
7390
9037
  }
7391
9038
  digest() {
@@ -7394,7 +9041,7 @@ var HMAC = class extends Hash {
7394
9041
  return out;
7395
9042
  }
7396
9043
  _cloneInto(to) {
7397
- to || (to = Object.create(Object.getPrototypeOf(this), {}));
9044
+ to ||= Object.create(Object.getPrototypeOf(this), {});
7398
9045
  const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
7399
9046
  to = to;
7400
9047
  to.finished = finished;
@@ -7414,54 +9061,71 @@ var HMAC = class extends Hash {
7414
9061
  this.iHash.destroy();
7415
9062
  }
7416
9063
  };
7417
- /**
7418
- * HMAC: RFC2104 message authentication code.
7419
- * @param hash - function that would be used e.g. sha256
7420
- * @param key - message key
7421
- * @param message - message data
7422
- * @example
7423
- * import { hmac } from '@noble/hashes/hmac';
7424
- * import { sha256 } from '@noble/hashes/sha2';
7425
- * const mac1 = hmac(sha256, 'key', 'message');
7426
- */
7427
- const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
7428
- hmac.create = (hash, key) => new HMAC(hash, key);
9064
+ const hmac = /* @__PURE__ */ (() => {
9065
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
9066
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
9067
+ return hmac_;
9068
+ })();
7429
9069
 
7430
9070
  //#endregion
7431
- //#region node_modules/@noble/hashes/esm/hkdf.js
9071
+ //#region node_modules/@noble/hashes/hkdf.js
7432
9072
  /**
7433
9073
  * HKDF (RFC 5869): extract + expand in one step.
7434
- * See https://soatok.blog/2021/11/17/understanding-hkdf/.
9074
+ * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.
7435
9075
  * @module
7436
9076
  */
7437
9077
  /**
7438
9078
  * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
7439
9079
  * Arguments position differs from spec (IKM is first one, since it is not optional)
9080
+ * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
7440
9081
  * @param hash - hash function that would be used (e.g. sha256)
7441
9082
  * @param ikm - input keying material, the initial key
7442
9083
  * @param salt - optional salt value (a non-secret random value)
9084
+ * @returns Pseudorandom key derived from input keying material.
9085
+ * @example
9086
+ * Run the HKDF extract step.
9087
+ * ```ts
9088
+ * import { extract } from '@noble/hashes/hkdf.js';
9089
+ * import { sha256 } from '@noble/hashes/sha2.js';
9090
+ * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
9091
+ * ```
7443
9092
  */
7444
9093
  function extract(hash, ikm, salt) {
7445
9094
  ahash(hash);
7446
9095
  if (salt === void 0) salt = new Uint8Array(hash.outputLen);
7447
- return hmac(hash, toBytes(salt), toBytes(ikm));
9096
+ return hmac(hash, salt, ikm);
7448
9097
  }
7449
- const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
9098
+ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
7450
9099
  const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
7451
9100
  /**
7452
9101
  * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
7453
9102
  * @param hash - hash function that would be used (e.g. sha256)
7454
- * @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
9103
+ * @param prk - a pseudorandom key of at least HashLen octets
9104
+ * (usually, the output from the extract step)
7455
9105
  * @param info - optional context and application specific information (can be a zero-length string)
7456
- * @param length - length of output keying material in bytes
9106
+ * @param length - length of output keying material in bytes.
9107
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
9108
+ * @returns Output keying material with the requested length.
9109
+ * @throws If the requested output length exceeds the HKDF limit
9110
+ * for the selected hash. {@link Error}
9111
+ * @example
9112
+ * Run the HKDF expand step.
9113
+ * ```ts
9114
+ * import { expand } from '@noble/hashes/hkdf.js';
9115
+ * import { sha256 } from '@noble/hashes/sha2.js';
9116
+ * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
9117
+ * ```
7457
9118
  */
7458
9119
  function expand(hash, prk, info, length = 32) {
7459
9120
  ahash(hash);
7460
- anumber$1(length);
9121
+ anumber$1(length, "length");
9122
+ abytes$1(prk, void 0, "prk");
7461
9123
  const olen = hash.outputLen;
7462
- if (length > 255 * olen) throw new Error("Length should be <= 255*HashLen");
9124
+ if (prk.length < olen) throw new Error("\"prk\" must be at least HashLen octets");
9125
+ if (length > 255 * olen) throw new Error("Length must be <= 255*HashLen");
7463
9126
  const blocks = Math.ceil(length / olen);
7464
9127
  if (info === void 0) info = EMPTY_BUFFER;
9128
+ else abytes$1(info, void 0, "info");
7465
9129
  const okm = new Uint8Array(blocks * olen);
7466
9130
  const HMAC = hmac.create(hash, prk);
7467
9131
  const HMACTmp = HMAC._cloneInto();
@@ -7474,7 +9138,7 @@ function expand(hash, prk, info, length = 32) {
7474
9138
  }
7475
9139
  HMAC.destroy();
7476
9140
  HMACTmp.destroy();
7477
- clean$1(T, HKDF_COUNTER);
9141
+ clean(T, HKDF_COUNTER);
7478
9142
  return okm.slice(0, length);
7479
9143
  }
7480
9144
  /**
@@ -7483,16 +9147,23 @@ function expand(hash, prk, info, length = 32) {
7483
9147
  * @param hash - hash function that would be used (e.g. sha256)
7484
9148
  * @param ikm - input keying material, the initial key
7485
9149
  * @param salt - optional salt value (a non-secret random value)
7486
- * @param info - optional context and application specific information (can be a zero-length string)
7487
- * @param length - length of output keying material in bytes
9150
+ * @param info - optional context and application specific information bytes
9151
+ * @param length - length of output keying material in bytes.
9152
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
9153
+ * @returns Output keying material derived from the input key.
9154
+ * @throws If the requested output length exceeds the HKDF limit
9155
+ * for the selected hash. {@link Error}
7488
9156
  * @example
7489
- * import { hkdf } from '@noble/hashes/hkdf';
7490
- * import { sha256 } from '@noble/hashes/sha2';
7491
- * import { randomBytes } from '@noble/hashes/utils';
9157
+ * HKDF (RFC 5869): derive keys from an initial input.
9158
+ * ```ts
9159
+ * import { hkdf } from '@noble/hashes/hkdf.js';
9160
+ * import { sha256 } from '@noble/hashes/sha2.js';
9161
+ * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';
7492
9162
  * const inputKey = randomBytes(32);
7493
9163
  * const salt = randomBytes(32);
7494
- * const info = 'application-key';
7495
- * const hk1 = hkdf(sha256, inputKey, salt, info, 32);
9164
+ * const info = utf8ToBytes('application-key');
9165
+ * const okm = hkdf(sha256, inputKey, salt, info, 32);
9166
+ * ```
7496
9167
  */
7497
9168
  const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
7498
9169
 
@@ -9046,7 +10717,11 @@ var AbracadabraClient = class {
9046
10717
  async getDocumentAccess(docId) {
9047
10718
  return this.request("GET", `/docs/${encodeURIComponent(docId)}/access`);
9048
10719
  }
9049
- /** Update document metadata (label, description, kind). Requires manage permission. */
10720
+ /**
10721
+ * Update document metadata (label, description, kind, parent_id). Requires
10722
+ * manage permission on the doc; reparenting additionally requires manage on
10723
+ * the new parent (or admin if moving under the server root).
10724
+ */
9050
10725
  async updateDocumentMeta(docId, opts) {
9051
10726
  await this.request("PATCH", `/docs/${encodeURIComponent(docId)}`, { body: opts });
9052
10727
  }
@@ -9494,8 +11169,9 @@ const ConnectionTimeout = {
9494
11169
  };
9495
11170
 
9496
11171
  //#endregion
9497
- //#region node_modules/@scure/bip39/esm/wordlists/english.js
9498
- const wordlist = `abandon
11172
+ //#region node_modules/@scure/bip39/wordlists/english.js
11173
+ /** English BIP39 wordlist. */
11174
+ const wordlist = /* @__PURE__ */ Object.freeze(`abandon
9499
11175
  ability
9500
11176
  able
9501
11177
  about
@@ -11542,7 +13218,7 @@ youth
11542
13218
  zebra
11543
13219
  zero
11544
13220
  zone
11545
- zoo`.split("\n");
13221
+ zoo`.split("\n"));
11546
13222
 
11547
13223
  //#endregion
11548
13224
  //#region packages/provider/src/MnemonicKeyDerivation.ts
@@ -11567,6 +13243,8 @@ zoo`.split("\n");
11567
13243
  *
11568
13244
  * Dependencies: @scure/bip39, @noble/ed25519, @noble/hashes, @noble/curves
11569
13245
  */
13246
+ _noble_ed25519.hashes.sha512 = sha512;
13247
+ _noble_ed25519.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
11570
13248
  /** HKDF salt for mnemonic → Ed25519 seed derivation. */
11571
13249
  const MNEMONIC_HKDF_SALT = /* @__PURE__ */ new TextEncoder().encode("abracadabra-mnemonic-v1");
11572
13250
  /** HKDF info string — intentionally matches the passkey path's HKDF_INFO. */
@@ -11690,6 +13368,8 @@ async function unwrapSeed(ciphertext, iv, wrappingKeyBytes) {
11690
13368
  *
11691
13369
  * Dependencies: @noble/ed25519, @noble/hashes, @noble/curves, @scure/bip39
11692
13370
  */
13371
+ _noble_ed25519.hashes.sha512 = sha512;
13372
+ _noble_ed25519.hashes.sha512Async = (m) => Promise.resolve(sha512(m));
11693
13373
  /**
11694
13374
  * Fixed PRF eval salt. Must be constant across all devices so the same synced
11695
13375
  * passkey produces the same PRF output everywhere.