@toon-protocol/client-mcp 0.20.3 → 0.20.4

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/utils.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_md.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/_u64.ts","../../../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/src/sha2.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/utils.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/modular.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/curve.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/fft.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/frost.ts"],"sourcesContent":["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg<Uint8Array>,\n length?: number,\n title: string = ''\n): TRet<Uint8Array> {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet<Uint8Array>;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg<CHash>): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg<TypedArray>): TRet<Uint8Array> {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet<Uint8Array>;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg<TypedArray>): TRet<Uint32Array> {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet<Uint32Array>;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg<TypedArray[]>): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg<TypedArray>): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg<Uint32Array>): TRet<Uint32Array> {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet<Uint32Array>;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array> = isLE\n ? (u: TArg<Uint32Array>) => u as TRet<Uint32Array>\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg<Uint8Array>): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet<Uint8Array> {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise<void> => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise<void> {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet<Uint8Array> {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg<KDFInput>, errorTitle = ''): TRet<Uint8Array> {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash<T> {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg<Uint8Array>): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg<Uint8Array>): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet<Uint8Array>;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg<Uint8Array>): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet<Uint8Array>;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet<Uint8Array>;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg<Uint8Array>): TRet<Uint8Array>;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons<T, Opts = undefined> = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet<Uint8Array>;\n};\n/** Callable hash function type. */\nexport type CHash<T extends Hash<T> = Hash<any>, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg<Uint8Array>): TRet<Uint8Array>;\n create(): T;\n }\n : {\n (msg: TArg<Uint8Array>, opts?: TArg<Opts>): TRet<Uint8Array>;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF<T extends HashXOF<T> = HashXOF<any>, Opts = undefined> = CHash<T, Opts>;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher<T extends Hash<T>, Opts = undefined>(\n hashCons: HasherCons<T, Opts>,\n info: TArg<HashInfo> = {}\n): TRet<CHash<T, Opts>> {\n const hashC: any = (msg: TArg<Uint8Array>, opts?: TArg<Opts>) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet<CHash<T, Opts>>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet<Uint8Array> {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet<Required<HashInfo>> => ({\n // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.\n // Larger suffix values would need base-128 OID encoding and a different length byte.\n oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),\n});\n","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD<T extends HashMD<T>> implements Hash<T> {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg<Uint8Array>): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg<Uint8Array>): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet<Uint8Array> {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet<Uint8Array>;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet<Uint32Array> = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n","/**\n * Internal helpers for u64.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst: bigint[], le = false): TRet<Uint32Array[]> {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al] as TRet<Uint32Array[]>;\n}\n\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h: number, l: number): number => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = <T extends TArg<Uint8Array>>(value: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> =>\n concatBytes_(...arrays) as TRet<Uint8Array>;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet<Uint8Array> => hexToBytes_(hex) as TRet<Uint8Array>;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet<Uint8Array> =>\n randomBytes_(bytesLength) as TRet<Uint8Array>;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg<Uint8Array>): TRet<Uint8Array>;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg<Uint8Array>, message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber<T extends number | bigint>(n: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet<Uint8Array>;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet<Uint8Array> {\n return numberToBytesBE(n, len).reverse() as TRet<Uint8Array>;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet<Uint8Array> {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet<Uint8Array>;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet<Uint8Array> {\n if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet<Uint8Array>;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: TArg<Uint8Array>) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg<HmacFn>\n): TRet<(seed: Uint8Array, predicate: Pred<T>) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet<Uint8Array> => new Uint8Array(len) as TRet<Uint8Array>;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs: TArg<Uint8Array[]>) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg<Uint8Array> = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: TArg<Uint8Array>, pred: TArg<Pred<T>>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred<T>)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred<T>) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: TArg<IField<T>>, root: T, n: T): void {\n const F = Fp as IField<T>;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (<T>(Fp: TArg<IField<T>>, n: T): T => {\n const F = Fp as IField<T>;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n }) as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: TArg<IField<T>>, n: T): T {\n const F = Fp as IField<T>;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n } as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField<T> {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet<IField<T>>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T {\n const F = Fp as IField<T>;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero = false): T[] {\n const F = Fp as IField<T>;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField<T>;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1 {\n const F = Fp as IField<T>;\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean {\n const l = FpLegendre(Fp as IField<T>, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap<object, ReturnType<typeof FpSqrt>>();\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet<Readonly<FpField>> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * 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},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n key: TArg<Uint8Array>,\n fieldOrder: bigint,\n isLE = false\n): TRet<Uint8Array> {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint<T> = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint<F>;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void {\n const pc = Point as unknown as CurvePointCons<any>;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper<T> = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams<T> = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: TArg<IField<T>>, isLE?: boolean): TRet<IField<T>> {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet<IField<T>>;\n } else {\n return Field(order, { isLE }) as unknown as TRet<IField<T>>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn<T> = {\n /** Base field used for curve coordinates. */\n Fp: IField<T>;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField<bigint>;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: TArg<Partial<FpFn<T>>> = {},\n FpFnLE?: boolean\n): TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn } as TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: TArg<Signer['getPublicKey']>\n): TRet<KeygenFn> {\n return function keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed) as TRet<Uint8Array>;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet<Uint8Array> };\n };\n}\n","/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash, TArg, TRet } from '../utils.ts';\nimport {\n abytes,\n asafenumber,\n asciiToBytes,\n bytesToNumberBE,\n copyBytes,\n concatBytes,\n isBytes,\n validateObject,\n} from '../utils.ts';\nimport type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\n/** ASCII domain-separation tag or raw bytes. */\nexport type AsciiOrBytes = string | Uint8Array;\ntype H2CDefaults = {\n DST: AsciiOrBytes;\n expand: 'xmd' | 'xof';\n hash: CHash;\n p: bigint;\n m: number;\n k: number;\n encodeDST?: AsciiOrBytes;\n};\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n /** Domain separation tag. */\n DST: AsciiOrBytes;\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n /** Base-field characteristic. */\n p: bigint;\n /** Extension degree (`1` for prime fields). */\n m: number;\n /** Target security level in bits. */\n k: number;\n};\n/** Hash-only subset of RFC 9380 options used by per-call overrides. */\nexport type H2CHashOpts = {\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n};\n/**\n * Map one hash-to-field output tuple onto affine curve coordinates.\n * Implementations receive the validated scalar tuple by reference for performance and MUST treat it\n * as read-only. Callers that need scratch space should copy before mutating.\n * @param scalar - Field-element tuple produced by `hash_to_field`.\n * @returns Affine point before subgroup clearing.\n */\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\n/** Per-call override for the domain-separation tag. */\nexport type H2CDSTOpts = {\n /** Domain-separation tag override. */\n DST: AsciiOrBytes;\n};\n/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */\nexport type H2CHasherBase<PC extends PC_ANY> = {\n /**\n * Hash arbitrary bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after hash-to-curve.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /**\n * Hash arbitrary bytes to one scalar.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Scalar reduced into the target field.\n */\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;\n /**\n * Derive one curve point from non-uniform bytes without the random-oracle\n * guarantees of `hashToCurve`.\n * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve\n * path instead of the random-oracle construction.\n */\n deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Point constructor for the target curve. */\n Point: PC;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {\n /**\n * Encode non-uniform bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after encode-to-curve.\n */\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Deterministic map from `hash_to_field` tuples into affine coordinates. */\n mapToCurve: MapToCurve<PC_F<PC>>;\n /** Default RFC 9380 options captured by this hasher bundle. */\n defaults: H2CDefaults;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value: number, length: number): TRet<Uint8Array> {\n asafenumber(value);\n asafenumber(length);\n // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length);\n if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res) as TRet<Uint8Array>;\n}\n\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a: TArg<Uint8Array>, b: TArg<Uint8Array>): TRet<Uint8Array> {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr as TRet<Uint8Array>;\n}\n\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST: TArg<AsciiOrBytes>): TRet<Uint8Array> {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n // RFC 9380 §3.1 requirement 2: tags \"MUST have nonzero length\".\n if (dst.length === 0) throw new Error('DST must be non-empty');\n return dst as TRet<Uint8Array>;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n // by reaching `I2OSP(256, 1)`.\n for (let i = 1; i < ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n * new TextEncoder().encode('hello noble'),\n * 'DST',\n * 32,\n * 128,\n * shake256\n * );\n * ```\n */\nexport function expand_message_xof(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n k: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // RFC 9380 §5.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n * DST: 'DST',\n * p: 17n,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(\n msg: TArg<Uint8Array>,\n count: number,\n options: TArg<H2COpts>\n): bigint[][] {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires\n // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n if (count < 1) throw new Error('hash_to_field: expected count >= 1');\n if (m < 1) throw new Error('hash_to_field: expected m >= 1');\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\ntype XY<T> = (x: T, y: T) => { x: T; y: T };\ntype XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must\n // return the identity on E.\n // Shipped Weierstrass consumers encode that affine identity as all-zero\n // coordinates, so `passZero=true` intentionally collapses zero\n // denominators to `{ x: 0, y: 0 }`.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-' as const;\n\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n * the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n * DST: 'P256_XMD:SHA-256_SSWU_RO_',\n * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n * p: p256.Point.Fp.ORDER,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher<PC extends PC_ANY>(\n Point: PC,\n mapToCurve: MapToCurve<PC_F<PC>>,\n defaults: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>\n): H2CHasher<PC> {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n const snapshot = (src: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>): TRet<H2CDefaults> =>\n Object.freeze({\n ...src,\n DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n ...(src.encodeDST === undefined\n ? {}\n : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n }) as TRet<H2CDefaults>;\n // Keep one private defaults snapshot for actual hashing and expose fresh\n // detached snapshots via the public getter.\n // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n // the singleton hasher for every other consumer in the same process.\n const safeDefaults = snapshot(defaults);\n function map(num: bigint[]): PC_P<PC> {\n return Point.fromAffine(mapToCurve(num)) as PC_P<PC>;\n }\n function clear(initial: PC_P<PC>): PC_P<PC> {\n const P = initial.clearCofactor();\n // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n if (P.equals(Point.ZERO)) return Point.ZERO as PC_P<PC>;\n P.assertValidity();\n return P as PC_P<PC>;\n }\n\n return Object.freeze({\n get defaults() {\n return snapshot(safeDefaults);\n },\n Point,\n\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const opts = Object.assign({}, safeDefaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1) as PC_P<PC>);\n },\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n const opts = Object.assign({}, safeDefaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars: bigint | bigint[]): PC_P<PC> {\n // Curves with m=1 accept only single scalar\n if (safeDefaults.m === 1) {\n if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n });\n}\n","/**\n * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.\n * API may change at any time. The code has not been audited. Feature requests are welcome.\n * @module\n */\nimport type { TArg } from '../utils.ts';\nimport type { IField } from './modular.ts';\n\n/** Array-like coefficient storage that can be mutated in place. */\nexport interface MutableArrayLike<T> {\n /** Element access by numeric index. */\n [index: number]: T;\n /** Current amount of stored coefficients. */\n length: number;\n /**\n * Return a sliced copy using the same storage shape.\n * @param start - Inclusive start index.\n * @param end - Exclusive end index.\n * @returns Sliced copy.\n */\n slice(start?: number, end?: number): this;\n /**\n * Iterate over stored coefficients in order.\n * @returns Coefficient iterator.\n */\n [Symbol.iterator](): Iterator<T>;\n}\n\n/**\n * Concrete polynomial containers accepted by the high-level `poly(...)` helpers.\n * Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)`\n * intentionally keeps runtime dispatch on plain arrays and typed-array views.\n */\nexport type PolyStorage<T> = T[] | (MutableArrayLike<T> & ArrayBufferView);\n\nfunction checkU32(n: number) {\n // 0xff_ff_ff_ff\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new Error('wrong u32 integer:' + n);\n return n;\n}\n\n/**\n * Checks if integer is in form of `1 << X`.\n * @param x - Integer to inspect.\n * @returns `true` when the value is a power of two.\n * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Validate that an FFT size is a power of two.\n *\n * ```ts\n * isPowerOfTwo(8);\n * ```\n */\nexport function isPowerOfTwo(x: number): boolean {\n checkU32(x);\n return (x & (x - 1)) === 0 && x !== 0;\n}\n\n/**\n * @param n - Input value.\n * @returns Next power of two within the u32/array-length domain.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Round an integer up to the FFT size it needs.\n *\n * ```ts\n * nextPowerOfTwo(9);\n * ```\n */\nexport function nextPowerOfTwo(n: number): number {\n checkU32(n);\n if (n <= 1) return 1;\n // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:\n // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.\n if (n > 0x8000_0000) throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\n\n/**\n * @param n - Value to reverse.\n * @param bits - Number of bits to use.\n * @returns Bit-reversed integer.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Reverse the low `bits` bits of one index.\n *\n * ```ts\n * reverseBits(3, 3);\n * ```\n */\nexport function reverseBits(n: number, bits: number): number {\n checkU32(n);\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);\n let reversed = 0;\n for (let i = 0; i < bits; i++, n >>>= 1) reversed = (reversed << 1) | (n & 1);\n // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.\n return reversed >>> 0;\n}\n\n/**\n * Similar to `bitLen(x)-1` but much faster for small integers, like indices.\n * @param n - Input value.\n * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Compute the radix-2 stage count for one transform size.\n *\n * ```ts\n * log2(8);\n * ```\n */\nexport function log2(n: number): number {\n checkU32(n);\n return 31 - Math.clz32(n);\n}\n\n/**\n * Moves lowest bit to highest position, which at first step splits\n * array on even and odd indices, then it applied again to each part,\n * which is core of fft\n * @param values - Mutable coefficient array.\n * @returns Mutated input array.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Reorder coefficients into bit-reversed order in place.\n *\n * ```ts\n * const values = Uint8Array.from([0, 1, 2, 3]);\n * bitReversalInplace(values);\n * ```\n */\nexport function bitReversalInplace<T extends MutableArrayLike<any>>(values: T): T {\n const n = values.length;\n // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.\n if (!isPowerOfTwo(n)) throw new Error('expected positive power-of-two length, got ' + n);\n const bits = log2(n);\n for (let i = 0; i < n; i++) {\n const j = reverseBits(i, bits);\n if (i < j) {\n const tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n }\n return values;\n}\n\n/**\n * @param values - Input values.\n * @returns Reordered copy.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Return a reordered copy instead of mutating the input in place.\n *\n * ```ts\n * const reordered = bitReversalPermutation([0, 1, 2, 3]);\n * ```\n */\nexport function bitReversalPermutation<T>(values: T[]): T[] {\n return bitReversalInplace(values.slice()) as T[];\n}\n\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field: TArg<IField<bigint>>) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++);\n return G;\n}\n\n/** Cached roots-of-unity tables derived from one finite field. */\nexport type RootsOfUnity = {\n /** Generator and 2-adicity metadata for the cached field. */\n info: { G: bigint; oddFactor: bigint; powerOfTwo: number };\n /**\n * Return the natural-order roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Natural-order roots for that size.\n */\n roots: (bits: number) => bigint[];\n /**\n * Return the bit-reversal permutation of the roots for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Bit-reversed roots.\n */\n brp(bits: number): bigint[];\n /**\n * Return the inverse roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Inverse roots.\n */\n inverse(bits: number): bigint[];\n /**\n * Return one primitive root used by a radix-2 stage.\n * @param bits - Transform size as `log2(N)`.\n * @returns Primitive root for that stage.\n */\n omega: (bits: number) => bigint;\n /**\n * Drop all cached root tables.\n * @returns Nothing.\n */\n clear: () => void;\n};\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.\n * @param field - Field implementation.\n * @param generator - Optional generator override.\n * @returns Roots-of-unity cache.\n * @example\n * Cache roots once, then ask for the omega table of one FFT size.\n *\n * ```ts\n * import { rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const roots = rootsOfUnity(Field(17n));\n * const omega = roots.omega(4);\n * ```\n */\nexport function rootsOfUnity(field: TArg<IField<bigint>>, generator?: bigint): RootsOfUnity {\n // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo\n let oddFactor = field.ORDER - _1n;\n let powerOfTwo = 0;\n for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n);\n\n // Find non quadratic residue\n let G = generator !== undefined ? BigInt(generator) : findGenerator(field);\n // Powers of generator\n const omegas: bigint[] = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache: bigint[][] = [];\n const checkBits = (bits: number) => {\n checkU32(bits);\n if (bits > 31 || bits > powerOfTwo)\n throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);\n return bits;\n };\n const precomputeRoots = (maxPower: number) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power]) continue; // Skip if we've already computed roots for this power\n const rootsAtPower: bigint[] = [];\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\n rootsCache[power] = rootsAtPower;\n }\n return rootsCache[maxPower];\n };\n const brpCache = new Map<number, bigint[]>();\n const inverseCache = new Map<number, bigint[]>();\n // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.\n\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not neccesary isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits: number): bigint[] => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits: number): bigint[] {\n const b = checkBits(bits);\n if (brpCache.has(b)) return brpCache.get(b)!;\n else {\n const res = bitReversalPermutation(this.roots(b));\n brpCache.set(b, res);\n return res;\n }\n },\n inverse(bits: number): bigint[] {\n const b = checkBits(bits);\n if (inverseCache.has(b)) return inverseCache.get(b)!;\n else {\n const res = field.invertBatch(this.roots(b));\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits: number): bigint => omegas[checkBits(bits)],\n clear: (): void => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n\n/** Polynomial coefficient container used by the FFT helpers. */\nexport type Polynomial<T> = MutableArrayLike<T>;\n\n/**\n * Arithmetic operations used by the generic FFT implementation.\n *\n * Maps great to Field<bigint>, but not to Group (EC points):\n * - inv from scalar field\n * - we need multiplyUnsafe here, instead of multiply for speed\n * - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse\n */\nexport type FFTOpts<T, R> = {\n /**\n * Add two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Sum coefficient.\n */\n add: (a: T, b: T) => T;\n /**\n * Subtract two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Difference coefficient.\n */\n sub: (a: T, b: T) => T;\n /**\n * Multiply one coefficient by a scalar/root factor.\n * @param a - Coefficient value.\n * @param scalar - Scalar/root factor.\n * @returns Scaled coefficient.\n */\n mul: (a: T, scalar: R) => T;\n /**\n * Invert one scalar/root factor.\n * @param a - Scalar/root factor.\n * @returns Inverse factor.\n */\n inv: (a: R) => R;\n};\n\n/** Configuration for one low-level FFT loop. */\nexport type FFTCoreOpts<R> = {\n /** Transform size. Must be a power of two. */\n N: number;\n /** Stage roots for the selected transform size. */\n roots: Polynomial<R>;\n /** Whether to run the DIT variant instead of DIF. */\n dit: boolean;\n /** Whether to invert butterfly placement for decode-oriented layouts. */\n invertButterflies?: boolean;\n /** Number of initial stages to skip. */\n skipStages?: number;\n /** Whether to apply bit-reversal permutation at the boundary. */\n brp?: boolean;\n};\n\n/**\n * Callable low-level FFT loop over one polynomial storage shape.\n * @param values - Polynomial coefficients to transform in place.\n * @returns The mutated input polynomial.\n */\nexport type FFTCoreLoop<T> = <P extends Polynomial<T>>(values: P) => P;\n\n/**\n * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:\n *\n * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey\n * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande\n *\n * DIT takes brp input, returns natural output.\n * DIF takes natural input, returns brp output.\n *\n * The output is actually identical. Time / frequence distinction is not meaningful\n * for Polynomial multiplication in fields.\n * Which means if protocol supports/needs brp output/inputs, then we can skip this step.\n *\n * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega\n * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa\n * @param F - Field operations.\n * @param coreOpts - FFT configuration:\n * - `N`: Transform size. Must be a power of two.\n * - `roots`: Stage roots for the selected transform size.\n * - `dit`: Whether to run the DIT variant instead of DIF.\n * - `invertButterflies` (optional): Whether to invert butterfly placement.\n * - `skipStages` (optional): Number of initial stages to skip.\n * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.\n * @returns Low-level FFT loop.\n * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}\n * @example\n * Constructs different flavors of FFT.\n *\n * ```ts\n * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const roots = rootsOfUnity(Fp).roots(2);\n * const loop = FFTCore(Fp, { N: 4, roots, dit: true });\n * const values = loop([1n, 2n, 3n, 4n]);\n * ```\n */\nexport const FFTCore = <T, R>(F: FFTOpts<T, R>, coreOpts: FFTCoreOpts<R>): FFTCoreLoop<T> => {\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n const bits = log2(N);\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.\n if (roots.length !== N)\n throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);\n const isDit = dit !== invertButterflies;\n isDit;\n return <P extends Polynomial<T>>(values: P): P => {\n if (values.length !== N) throw new Error('FFT: wrong Polynomial length');\n if (dit && brp) bitReversalInplace(values);\n for (let i = 0, g = 1; i < bits - skipStages; i++) {\n // For each stage s (sub-FFT length m = 2^s)\n const s = dit ? i + 1 + skipStages : bits - i;\n const m = 1 << s;\n const m2 = m >> 1;\n const stride = N >> s;\n // Loop over each subarray of length m\n for (let k = 0; k < N; k += m) {\n // Loop over each butterfly within the subarray\n for (let j = 0, grp = g++; j < m2; j++) {\n const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;\n const i0 = k + j;\n const i1 = k + j + m2;\n const omega = roots[rootPos];\n const b = values[i1];\n const a = values[i0];\n // Inlining gives us 10% perf in kyber vs functions\n if (isDit) {\n const t = F.mul(b, omega); // Standard DIT butterfly\n values[i0] = F.add(a, t);\n values[i1] = F.sub(a, t);\n } else if (invertButterflies) {\n values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)\n values[i1] = F.mul(F.sub(b, a), omega);\n } else {\n values[i0] = F.add(a, b); // Standard DIF butterfly\n values[i1] = F.mul(F.sub(a, b), omega);\n }\n }\n }\n }\n if (!dit && brp) bitReversalInplace(values);\n return values;\n };\n};\n\n/** Forward and inverse FFT helpers for one coefficient domain. */\nexport type FFTMethods<T> = {\n /**\n * Apply the forward transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Transformed copy.\n */\n direct<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\n /**\n * Apply the inverse transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Inverse-transformed copy.\n */\n inverse<P extends Polynomial<T>>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\n};\n\n/**\n * NTT aka FFT over finite field (NOT over complex numbers).\n * Naming mirrors other libraries.\n * @param roots - Roots-of-unity cache.\n * @param opts - Field operations. See {@link FFTOpts}.\n * @returns Forward and inverse FFT helpers.\n * @example\n * NTT aka FFT over finite field (NOT over complex numbers).\n *\n * ```ts\n * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const fft = FFT(rootsOfUnity(Fp), Fp);\n * const values = fft.direct([1n, 2n, 3n, 4n]);\n * ```\n */\nexport function FFT<T>(roots: RootsOfUnity, opts: FFTOpts<T, bigint>): FFTMethods<T> {\n const getLoop = (\n N: number,\n roots: Polynomial<bigint>,\n brpInput = false,\n brpOutput = false\n ): (<P extends Polynomial<T>>(values: P) => P) => {\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n return (values) =>\n FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));\n }\n if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false });\n if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false });\n return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural\n };\n return {\n direct<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n return getLoop(N, roots.roots(bits), brpInput, brpOutput)<P>(values.slice());\n },\n inverse<P extends Polynomial<T>>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());\n const ivm = opts.inv(BigInt(values.length)); // scale\n // we can get brp output if we use dif instead of dit!\n for (let i = 0; i < res.length; i++) res[i] = opts.mul(res[i], ivm);\n // Allows to re-use non-inverted roots, but is VERY fragile\n // return [res[0]].concat(res.slice(1).reverse());\n // inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices)\n return res;\n },\n };\n}\n\n/**\n * Factory that allocates one polynomial storage container.\n * Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted,\n * because the quadratic `mul()` / `convolve()` paths and the Kronecker-δ shortcut in\n * `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly.\n * @param len - Requested amount of coefficients.\n * @param elm - Optional fill value.\n * @returns Newly allocated polynomial container.\n */\nexport type CreatePolyFn<P extends PolyStorage<T>, T> = (len: number, elm?: T) => P;\n\n/** High-level polynomial helpers layered on top of FFT and field arithmetic. */\nexport type PolyFn<P extends PolyStorage<T>, T> = {\n /** Roots-of-unity cache used by the helper namespace. */\n roots: RootsOfUnity;\n /** Factory used to allocate new polynomial containers. */\n create: CreatePolyFn<P, T>;\n /** Optional enforced polynomial length. */\n length?: number;\n\n /**\n * Compute the polynomial degree.\n * @param a - Polynomial coefficients.\n * @returns Polynomial degree.\n */\n degree: (a: P) => number;\n /**\n * Extend or truncate one polynomial to a requested length.\n * @param a - Polynomial coefficients.\n * @param len - Target length.\n * @returns Resized polynomial.\n */\n extend: (a: P, len: number) => P;\n /**\n * Add two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Sum polynomial.\n */\n add: (a: P, b: P) => P;\n /**\n * Subtract two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Difference polynomial.\n */\n sub: (a: P, b: P) => P;\n /**\n * Multiply by another polynomial or by one scalar.\n * @param a - Left polynomial.\n * @param b - Right polynomial or scalar.\n * @returns Product polynomial.\n */\n mul: (a: P, b: P | T) => P;\n /**\n * Multiply coefficients point-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Point-wise product polynomial.\n */\n dot: (a: P, b: P) => P;\n /**\n * Multiply two polynomials with convolution.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Convolution product.\n */\n convolve: (a: P, b: P) => P;\n /**\n * Apply a point-wise coefficient shift by powers of one factor.\n * @param p - Polynomial coefficients.\n * @param factor - Shift factor.\n * @returns Shifted polynomial.\n */\n shift: (p: P, factor: bigint) => P;\n /**\n * Clone one polynomial container.\n * @param a - Polynomial coefficients.\n * @returns Cloned polynomial.\n */\n clone: (a: P) => P;\n /**\n * Evaluate one polynomial on a basis vector.\n * @param a - Polynomial coefficients.\n * @param basis - Basis vector.\n * @returns Evaluated field element.\n */\n eval: (a: P, basis: P) => T;\n /** Helpers for monomial-basis polynomials. */\n monomial: {\n /** Build the monomial basis vector for one evaluation point. */\n basis: (x: T, n: number) => P;\n /** Evaluate a polynomial in the monomial basis. */\n eval: (a: P, x: T) => T;\n };\n /** Helpers for Lagrange-basis polynomials. */\n lagrange: {\n /** Build the Lagrange basis vector for one evaluation point. */\n basis: (x: T, n: number, brp?: boolean) => P;\n /** Evaluate a polynomial in the Lagrange basis. */\n eval: (a: P, x: T, brp?: boolean) => T;\n };\n /**\n * Build the vanishing polynomial for a root set.\n * @param roots - Root set.\n * @returns Vanishing polynomial.\n */\n vanishing: (roots: P) => P;\n};\n\n/**\n * Poly wants a cracker.\n *\n * Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is\n * function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:\n *\n * - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`\n * - **Basis** is array of functions\n * - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)\n * - **Array size** is domain size\n * - **Lattice** is matrix (Polynomial of Polynomials)\n * @param field - Field implementation.\n * @param roots - Roots-of-unity cache.\n * @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array`\n * and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected.\n * @param fft - Optional FFT implementation.\n * @param length - Optional fixed polynomial length.\n * @returns Polynomial helper namespace.\n * @example\n * Build polynomial helpers, then convolve two coefficient arrays.\n *\n * ```ts\n * import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const poly17 = poly(Fp, rootsOfUnity(Fp));\n * const product = poly17.convolve([1n, 2n], [3n, 4n]);\n * ```\n */\nexport function poly<T>(\n field: TArg<IField<T>>,\n roots: RootsOfUnity,\n create?: undefined,\n fft?: FFTMethods<T>,\n length?: number\n): PolyFn<T[], T>;\nexport function poly<T, P extends PolyStorage<T>>(\n field: TArg<IField<T>>,\n roots: RootsOfUnity,\n create: CreatePolyFn<P, T>,\n fft?: FFTMethods<T>,\n length?: number\n): PolyFn<P, T>;\nexport function poly<T, P extends PolyStorage<T>>(\n field: TArg<IField<T>>,\n roots: RootsOfUnity,\n create?: CreatePolyFn<P, T>,\n fft?: FFTMethods<T>,\n length?: number\n): PolyFn<any, T> {\n const F = field as IField<T>;\n const _create =\n create ||\n (((len: number, elm?: T): T[] => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn<P, T>);\n\n // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted\n // polynomial containers concrete instead of trying to support arbitrary wrappers.\n const isPoly = (x: any): x is P => {\n if (Array.isArray(x)) return true;\n if (!ArrayBuffer.isView(x)) return false;\n const v = x as unknown as ArrayLike<unknown> & { slice?: unknown; [Symbol.iterator]?: unknown };\n return (\n typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function'\n );\n };\n const checkLength = (...lst: P[]): number => {\n if (!lst.length) return 0;\n for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i);\n const L = lst[0].length;\n for (let i = 1; i < lst.length; i++)\n if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);\n if (length !== undefined && L !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${L}`);\n return L;\n };\n function findOmegaIndex(x: T, n: number, brp = false): number {\n const bits = log2(n);\n const omega = brp ? roots.brp(bits) : roots.roots(bits);\n for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) return i;\n return -1;\n }\n // TODO: mutating versions for mlkem/mldsa\n return {\n roots,\n create: _create,\n length,\n extend: (a: P, len: number): P => {\n checkLength(a);\n const out = _create(len, F.ZERO);\n // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep\n // `extend()` consistent with typed arrays and with its documented truncate behavior.\n for (let i = 0; i < Math.min(a.length, len); i++) out[i] = a[i];\n return out;\n },\n degree: (a: P): number => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;\n return -1;\n },\n add: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a: P, b: P | T): P => {\n if (isPoly(b)) {\n const len = checkLength(a, b);\n if (fft) {\n const A = fft.direct(a, false, true);\n const B = fft.direct(b, false, true);\n for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false) as P;\n } else {\n // NOTE: this is quadratic and mostly for compat tests with FFT\n const res = _create(len);\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n const k = (i + j) % len; // wrap mod length\n res[k] = F.add(res[k], F.mul(a[i], b[j]));\n }\n }\n return res;\n }\n } else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a: P, b: P): P {\n const len = nextPowerOfTwo(a.length + b.length - 1);\n return this.mul(this.extend(a, len), this.extend(b, len));\n },\n shift(p: P, factor: bigint): P {\n const out = _create(checkLength(p));\n out[0] = p[0];\n for (let i = 1, power = F.ONE; i < p.length; i++) {\n power = F.mul(power, factor);\n out[i] = F.mul(p[i], power);\n }\n return out;\n },\n clone: (a: P): P => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++) out[i] = a[i];\n return out;\n },\n eval: (a: P, basis: P): T => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x: T, n: number): P => {\n const out = _create(n);\n let pow = F.ONE;\n for (let i = 0; i < n; i++) {\n out[i] = pow;\n pow = F.mul(pow, x);\n }\n return out;\n },\n eval: (a: P, x: T): T => {\n checkLength(a);\n // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way\n let acc = F.ZERO;\n for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x: T, n: number, brp = false, weights?: P): P => {\n const bits = log2(n);\n const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [ω⁰, ω¹, ..., ωⁿ⁻¹]\n const out = _create(n);\n // Fast Kronecker-δ shortcut\n const idx = findOmegaIndex(x, n, brp);\n if (idx !== -1) {\n out[idx] = F.ONE;\n return out;\n }\n const tm = F.pow(x, BigInt(n));\n const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n) as T)); // c = (xⁿ - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T);\n const inv = F.invertBatch(denom as any as T[]);\n for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i]));\n return out;\n },\n eval(a: P, x: T, brp = false): T {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1) return a[idx]; // fast path\n const L = this.basis(x, a.length, brp); // Lᵢ(x)\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots: P): P {\n checkLength(roots);\n const out = _create(roots.length + 1, F.ZERO);\n out[0] = F.ONE;\n for (const r of roots) {\n const neg = F.neg(r);\n for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]);\n out[0] = F.mul(out[0], neg);\n }\n return out;\n },\n };\n}\n","/**\n * FROST: Flexible Round-Optimized Schnorr Threshold Protocol for Two-Round Schnorr Signatures.\n *\n * See [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/) and [frost.zfnd.org](https://frost.zfnd.org).\n * @module\n */\nimport { utf8ToBytes } from '@noble/hashes/utils.js';\nimport {\n bytesToHex,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n hexToBytes,\n randomBytes,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport { pippenger, validatePointCons, type CurvePoint, type CurvePointCons } from './curve.ts';\nimport { poly, type RootsOfUnity } from './fft.ts';\nimport { type H2CDSTOpts } from './hash-to-curve.ts';\nimport { getMinHashLength, mapHashToField, type IField } from './modular.ts';\n\nexport type RNG = typeof randomBytes;\nexport type Identifier = string; // Identifiers are hex to make comparison easier\nexport type Commitment = Uint8Array; // serialized point\nexport type Coefficient = Uint8Array; // serialized scalar\nexport type Signature = Uint8Array;\nexport type Signers = { min: number; max: number };\nexport type SecretKey = Uint8Array; // Secret key\nexport type Bytes = Uint8Array;\ntype Point = Uint8Array;\n\nexport type DKG_Round1 = {\n // If identifiers were assigned via fromNumber before, it is worth checking\n // that a party doesn't impersonate another one.\n // But we throw on duplicate identifiers.\n identifier: Identifier;\n commitment: TRet<Commitment[]>; // sender identifier\n proofOfKnowledge: TRet<Signature>;\n};\nexport type DKG_Round2 = {\n identifier: Identifier; // sender identifier\n signingShare: TRet<Bytes>;\n};\n// This is internal, so we can use bigints\nexport type DKG_Secret = {\n identifier: bigint;\n coefficients?: bigint[];\n commitment: TRet<Point[]>;\n signers: Signers;\n // Keep the local polynomial until round3 succeeds so late DKG failures can be retried.\n step?: 1 | 2 | 3;\n};\n\nexport type FrostPublic = {\n signers: Signers;\n commitments: TRet<Bytes[]>; // Point[], where commitments[0] is the group public key\n verifyingShares: TRet<Record<Identifier, Bytes>>; // id -> Point\n};\nexport type FrostSecret = {\n identifier: Identifier;\n signingShare: TRet<Bytes>; // Scalar\n};\nexport type Key = { public: FrostPublic; secret: FrostSecret };\nexport type DealerShares = {\n public: FrostPublic;\n secretShares: Record<Identifier, FrostSecret>;\n};\n// Sign stuff\nexport type Nonces = {\n hiding: TRet<Bytes>; // Scalar\n binding: TRet<Bytes>; // Scalar\n};\nexport type NonceCommitments = {\n identifier: Identifier;\n hiding: TRet<Bytes>; // Point\n binding: TRet<Bytes>; // Point\n};\nexport type GenNonce = {\n nonces: Nonces;\n commitments: NonceCommitments;\n};\n\nexport interface FROSTPoint<T extends CurvePoint<any, T>> extends CurvePoint<any, T> {\n add(rhs: T): T;\n multiply(rhs: bigint): T;\n equals(rhs: T): boolean;\n toBytes(compressed?: boolean): Bytes;\n clearCofactor(): T;\n}\nexport interface FROSTPointConstructor<T extends FROSTPoint<T>> extends CurvePointCons<T> {\n fromBytes(a: Bytes): T;\n Fn: IField<bigint>;\n}\n\n// Opts\nexport type FrostOpts<P extends FROSTPoint<P>> = {\n readonly name: string;\n readonly Point: FROSTPointConstructor<P>;\n readonly Fn?: IField<bigint>;\n /** Optional suite hook that tightens canonical decoding with subgroup / identity checks. */\n readonly validatePoint?: (p: P) => void;\n /** Optional public-key parser. Implementations MUST preserve the same subgroup / identity policy\n * as `validatePoint`, because this bypasses generic canonical decoding in `parsePoint()`. */\n readonly parsePublicKey?: (bytes: TArg<Uint8Array>) => P;\n readonly hash: (msg: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Custom scalar hash hook. Implementations MUST treat `msg` and `options` as read-only. */\n readonly hashToScalar?: (msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>) => bigint;\n // Hacks for taproot support\n readonly adjustScalar?: (n: bigint) => bigint;\n readonly adjustPoint?: (n: P) => P;\n readonly challenge?: (R: P, PK: P, msg: TArg<Uint8Array>) => bigint;\n readonly adjustNonces?: (PK: P, nonces: TArg<Nonces>) => TRet<Nonces>;\n readonly adjustSecret?: (secret: TArg<FrostSecret>, pub: TArg<FrostPublic>) => TRet<FrostSecret>;\n readonly adjustPublic?: (pub: TArg<FrostPublic>) => TRet<FrostPublic>;\n readonly adjustGroupCommitmentShare?: (GC: P, GCShare: P) => P;\n readonly adjustTx?: {\n readonly encode: (tx: TArg<Uint8Array>) => TRet<Uint8Array>;\n readonly decode: (tx: TArg<Uint8Array>) => TRet<Uint8Array>;\n };\n readonly adjustDKG?: (k: TArg<Key>) => TRet<Key>;\n // Hash function prefixes\n readonly H1?: string;\n readonly H2?: string;\n readonly H3?: string;\n readonly H4?: string;\n readonly H5?: string;\n readonly HDKG?: string;\n readonly HID?: string;\n};\n\n/**\n * FROST: Threshold Protocol for Two‑Round Schnorr Signatures\n * from [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/).\n */\nexport type FROST = {\n /**\n * Methods to construct participant identifiers.\n */\n Identifier: {\n /**\n * Constructs an identifier from a numeric index.\n * @param n - A positive integer.\n * @returns A canonical serialized Identifier.\n */\n fromNumber(n: number): Identifier;\n /**\n * Derives an identifier deterministically from a string (e.g. an email).\n * @param s - Arbitrary string.\n * @returns A canonical serialized Identifier.\n */\n derive(s: string): Identifier;\n };\n /**\n * Distributed Key Generation (DKG) protocol interface.\n * RFC 9591 leaves DKG out of scope; Appendix C only specifies dealer/VSS key generation.\n * These helpers follow the split-round API used by frost-rs for interoperable testing.\n */\n DKG: {\n /**\n * Generates the first round of DKG.\n * @param id - Participant's identifier.\n * @param signers - Set of all participants (min/max threshold).\n * @param secret - Optional initial secret scalar.\n * @param rng - Optional RNG for nonce generation.\n * @returns Public broadcast and private DKG state. The returned `secret` package is mutable\n * round state that will be consumed by `round2()` and `round3()`.\n */\n round1: (\n id: Identifier,\n signers: Signers,\n secret?: TArg<SecretKey>,\n rng?: RNG\n ) => {\n public: DKG_Round1;\n secret: DKG_Secret;\n };\n /**\n * Executes DKG round 2 given public round1 data from others.\n * @param secret - Private DKG state from round1. This mutates `secret.step` in place.\n * @param others - Public round1 broadcasts from other participants.\n * @returns A map of round2 messages to be sent to others.\n */\n round2: (\n secret: TArg<DKG_Secret>,\n others: TArg<DKG_Round1[]>\n ) => TRet<Record<string, DKG_Round2>>;\n /**\n * Finalizes key generation in round3 using received round1 + round2 messages.\n * @param secret - Private DKG state. This consumes the remaining local polynomial coefficients\n * and transitions the package to its final post-round3 state.\n * @param round1 - Public round1 broadcasts from all participants.\n * @param round2 - Round2 messages received from others.\n * @returns Final secret/public key information for the participant.\n * Callers MUST pass the same verified remote `round1` package set that was already\n * accepted in `round2()`, rather than re-fetching or rebuilding it from the network.\n */\n round3: (\n secret: TArg<DKG_Secret>,\n round1: TArg<DKG_Round1[]>,\n round2: TArg<DKG_Round2[]>\n ) => TRet<Key>;\n /**\n * Best-effort erasure of internal secret state. Bigint/JIT copies may still survive outside the\n * local object even after cleanup.\n * @param secret - Private DKG state from round1.\n */\n clean(secret: TArg<DKG_Secret>): void;\n };\n /**\n * Trusted dealer mode: generates key shares from a central trusted authority.\n * Mirrors RFC 9591 Appendix C and returns one shared VSS commitment package\n * plus per-participant shares.\n * @param signers - Threshold parameters (min/max).\n * @param identifiers - Optional explicit participant list.\n * @param secret - Optional secret scalar.\n * @param rng - Optional RNG.\n * @returns One shared public package plus the participant secret-share packages.\n */\n trustedDealer(\n signers: Signers,\n identifiers?: Identifier[],\n secret?: TArg<SecretKey>,\n rng?: RNG\n ): TRet<DealerShares>;\n /**\n * Validates the consistency of a secret share against the shared public commitments.\n * This is the RFC 9591 Appendix C.2 `vss_verify` check against the shared dealer/DKG commitment.\n * It does not relax RFC 9591 Section 3.1: public identity elements are still invalid even when\n * the scalar/share algebra would otherwise be self-consistent.\n * Throws if invalid.\n * @param secret - A FrostSecret containing identifier and signing share.\n * @param pub - Shared public package containing commitments.\n */\n validateSecret(secret: TArg<FrostSecret>, pub: TArg<FrostPublic>): void;\n /**\n * Produces nonces and public commitments used in signing.\n * RFC 9591 Section 5.1 `commit()`.\n * @param secret - Participant's secret share.\n * @param rng - Optional RNG.\n * @returns Nonce values and their public commitments.\n * Returned nonces are one-time-use and MUST NOT be reused across signing sessions.\n * This API does not mutate or zeroize caller-owned nonce objects.\n */\n commit(secret: TArg<FrostSecret>, rng?: RNG): TRet<GenNonce>;\n /**\n * Signs a message using the participant's secret and nonce.\n * @param secret - Participant's secret share.\n * @param pub - Shared public package containing commitments.\n * @param nonces - Participant's nonce pair.\n * @param commitmentList - Commitments from all signing participants.\n * @param msg - Message to be signed.\n * @returns Signature share as a byte array.\n * RFC 9591 Sections 4.1/5.1 require round-one commitments to be one-time-use, and\n * Section 5.2 signs with the nonce corresponding to that published commitment.\n * The caller MUST pass fresh nonces from `commit()`. On successful signing, this helper\n * consumes the caller-owned nonce object by zeroing both nonce byte arrays in place.\n * Later calls reject an all-zero nonce package, so same-object reuse fails closed and an\n * accidentally generated zero nonce package is not silently used for signing.\n */\n signShare(\n secret: TArg<FrostSecret>,\n pub: TArg<FrostPublic>,\n nonces: TArg<Nonces>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>\n ): TRet<Uint8Array>;\n /**\n * Verifies a signature share against public commitments.\n * Matches the coordinator-side individual-share verification from RFC 9591 Section 5.4.\n * @param pub - Group public key information.\n * @param commitmentList - Commitments from all signing participants.\n * @param msg - Message being signed.\n * @param identifier - Identifier of the signer whose share is being verified.\n * @param sigShare - Signature share to verify.\n * @returns True if valid, false otherwise.\n */\n verifyShare(\n pub: TArg<FrostPublic>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>,\n identifier: Identifier,\n sigShare: TArg<Uint8Array>\n ): boolean;\n /**\n * Aggregates signature shares into a full signature.\n * RFC 9591 Section 5.3 `aggregate()`.\n * @param pub - Group public key.\n * @param commitmentList - Nonce commitments from all signers.\n * @param msg - Message to sign.\n * @param sigShares - Map from identifier to their signature share.\n * @returns Final aggregated signature.\n */\n aggregate(\n pub: TArg<FrostPublic>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>,\n sigShares: TArg<Record<Identifier, Uint8Array>>\n ): TRet<Uint8Array>;\n /**\n * Signs a message using a raw secret key (e.g. from combineSecret).\n * @param msg - Message to sign.\n * @param secretKey - Group secret key as bytes.\n * @returns Signature bytes.\n */\n sign(msg: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array>;\n /**\n * Verifies a full signature against the group public key.\n * @param sig - Signature bytes.\n * @param msg - Message that was signed.\n * @param publicKey - Group public key.\n * @returns True if valid, false otherwise.\n */\n verify(sig: TArg<Signature>, msg: TArg<Uint8Array>, publicKey: TArg<Uint8Array>): boolean;\n /**\n * Combines multiple secret shares into a single secret key (e.g. for recovery).\n * @param shares - Set of FrostSecret shares.\n * @param signers - Threshold parameters.\n * @returns Group secret key as bytes.\n */\n combineSecret(shares: TArg<FrostSecret[]>, signers: Signers): TRet<Uint8Array>;\n /**\n * Low-level helper utilities (field arithmetic and polynomial tools).\n */\n utils: {\n /**\n * Finite field used for scalars.\n */\n Fn: IField<bigint>;\n /**\n * Generates a random scalar (private key).\n * @param rng - Optional RNG source.\n * @returns Scalar as 32-byte Uint8Array.\n */\n randomScalar: (rng?: RNG) => TRet<Uint8Array>;\n /**\n * Generates a secret-sharing polynomial and its public commitments.\n * @param signers - Threshold parameters.\n * @param secret - Optional initial secret scalar.\n * @param coeffs - Optional manual coefficients.\n * @param rng - Optional RNG.\n * @returns Polynomial coefficients, commitments, and secret value.\n */\n generateSecretPolynomial: (\n signers: Signers,\n secret?: TArg<Uint8Array>,\n coeffs?: bigint[],\n rng?: RNG\n ) => {\n coefficients: bigint[];\n commitment: TRet<Point[]>;\n secret: bigint;\n };\n };\n};\n\n// PubKey = commitments, verifyingShares\n// PrivKey = id, signingShare, commitment\n\nconst validateSigners = (signers: Signers) => {\n if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max))\n throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max);\n // Compatibility with frost-rs intentionally narrows RFC 9591's positive-nonzero threshold rule\n // to `min >= 2`, even though the RFC text itself allows `MIN_PARTICIPANTS = 1`.\n // This API is for actual threshold signing across participants; 1-of-n degenerates to ordinary\n // single-signer mode, which does not need FROST's network/coordination machinery at all.\n if (signers.min < 2 || signers.max < 2 || signers.min > signers.max)\n throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max);\n};\nconst validateCommitmentsNum = (signers: Signers, len: number) => {\n // RFC 9591 Sections 5.2/5.3 require MIN_PARTICIPANTS <= NUM_PARTICIPANTS <= MAX_PARTICIPANTS.\n if (len < signers.min || len > signers.max) throw new Error('Wrong number of commitments=' + len);\n};\n\nclass AggErr extends Error {\n // Empty means aggregation failed before per-share verification could attribute a signer.\n public cheaters: Identifier[];\n constructor(msg: string, cheaters: Identifier[]) {\n super(msg);\n this.cheaters = cheaters;\n }\n}\n\nexport function createFROST<P extends FROSTPoint<P>>(opts: FrostOpts<P>): TRet<FROST> {\n validateObject(\n opts,\n {\n name: 'string',\n hash: 'function',\n },\n {\n hashToScalar: 'function',\n validatePoint: 'function',\n parsePublicKey: 'function',\n adjustScalar: 'function',\n adjustPoint: 'function',\n challenge: 'function',\n adjustNonces: 'function',\n adjustSecret: 'function',\n adjustPublic: 'function',\n adjustGroupCommitmentShare: 'function',\n adjustDKG: 'function',\n }\n );\n // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that\n // FROST consumes, but it does not certify point semantics like BASE/ZERO correctness.\n validatePointCons(opts.Point);\n const { Point } = opts;\n const Fn = opts.Fn === undefined ? Point.Fn : opts.Fn;\n // Hashes\n const hashBytes = opts.hash;\n const hashToScalar =\n opts.hashToScalar === undefined\n ? (msg: TArg<Uint8Array>, opts: TArg<H2CDSTOpts> = { DST: new Uint8Array() }) => {\n const t = hashBytes(concatBytes(opts.DST as Uint8Array, msg));\n return Fn.create(Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t));\n }\n : opts.hashToScalar;\n const H1Prefix = utf8ToBytes(opts.H1 !== undefined ? opts.H1 : opts.name + 'rho');\n const H2Prefix = utf8ToBytes(opts.H2 !== undefined ? opts.H2 : opts.name + 'chal');\n const H3Prefix = utf8ToBytes(opts.H3 !== undefined ? opts.H3 : opts.name + 'nonce');\n const H4Prefix = utf8ToBytes(opts.H4 !== undefined ? opts.H4 : opts.name + 'msg');\n const H5Prefix = utf8ToBytes(opts.H5 !== undefined ? opts.H5 : opts.name + 'com');\n const HDKGPrefix = utf8ToBytes(opts.HDKG !== undefined ? opts.HDKG : opts.name + 'dkg');\n const HIDPrefix = utf8ToBytes(opts.HID !== undefined ? opts.HID : opts.name + 'id');\n const H1 = (msg: TArg<Uint8Array>) => hashToScalar(msg, { DST: H1Prefix });\n // Empty H2 still passes `{ DST: new Uint8Array() }` into custom hashToScalar hooks.\n // The built-in fallback hashes that identically to omitted DST, which is how\n // the Ed25519 suite models RFC 9591's undecorated H2 challenge hash.\n const H2 = (msg: TArg<Uint8Array>) => hashToScalar(msg, { DST: H2Prefix });\n const H3 = (msg: TArg<Uint8Array>) => hashToScalar(msg, { DST: H3Prefix });\n const H4 = (msg: TArg<Uint8Array>) => hashBytes(concatBytes(H4Prefix, msg));\n const H5 = (msg: TArg<Uint8Array>) => hashBytes(concatBytes(H5Prefix, msg));\n const HDKG = (msg: TArg<Uint8Array>) => hashToScalar(msg, { DST: HDKGPrefix });\n const HID = (msg: TArg<Uint8Array>) => hashToScalar(msg, { DST: HIDPrefix });\n // /Hashes\n const randomScalar = (rng: RNG = randomBytes) => {\n // Intentional divergence from RFC 9591 §4.1 / §5.1: the RFC nonce_generate helper outputs a\n // Scalar in [0, p-1], but round-one commit publishes ScalarBaseMult(nonce) values and §3.1\n // requires SerializeElement / DeserializeElement to reject the identity element. Keep noble's\n // mapHashToField generation here so round-one public nonce commitments stay in 1..n-1.\n const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);\n // We cannot use Fn.fromBytes here because the field can have a different\n // byte width, like ed448.\n return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);\n };\n const serializePoint = (p: P) => p.toBytes();\n const parsePoint = (bytes: TArg<Uint8Array>) => {\n // RFC 9591 Section 3.1 requires DeserializeElement validation. Suite-specific validatePoint\n // hooks tighten this further for ciphersuites in Section 6. Bare createFROST(...) only gets\n // canonical point decoding unless the caller installs those extra subgroup / identity checks.\n const p = Point.fromBytes(bytes);\n if (opts.validatePoint) opts.validatePoint(p);\n return p;\n };\n // RFC 9591 Sections 4.1/5.1 model each participant's round-one output as two public commitments.\n const nonceCommitments = (identifier: Identifier, nonces: TArg<Nonces>): TRet<NonceCommitments> =>\n ({\n identifier,\n hiding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.hiding))),\n binding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.binding))),\n }) as TRet<NonceCommitments>;\n const adjustPoint = opts.adjustPoint === undefined ? (n: P) => n : opts.adjustPoint;\n // We use hex to make it easier to use inside objects\n const validateIdentifier = (n: bigint) => {\n // Identifiers are canonical non-zero scalars. Custom / derived identifiers are allowed, so this\n // is intentionally not bounded by the current signers.max slot count.\n if (!Fn.isValid(n) || Fn.is0(n)) throw new Error('Invalid identifier ' + n);\n return n;\n };\n const serializeIdentifier = (id: bigint) => bytesToHex(Fn.toBytes(validateIdentifier(id)));\n const parseIdentifier = (id: string) => {\n const n = validateIdentifier(Fn.fromBytes(hexToBytes(id)));\n // Keep string-keyed maps stable by accepting only the canonical serialized form.\n if (serializeIdentifier(n) !== id) throw new Error('expected canonical identifier hex');\n return n;\n };\n\n const Signature = {\n // RFC 9591 Appendix A encodes signatures canonically as\n // SerializeElement(R) || SerializeScalar(z).\n encode: (R: P, z: bigint): TRet<Signature> => {\n let res: Uint8Array = concatBytes(serializePoint(R), Fn.toBytes(z));\n if (opts.adjustTx) res = opts.adjustTx.encode(res);\n return res as TRet<Signature>;\n },\n decode: (sig: TArg<Uint8Array>) => {\n if (opts.adjustTx) sig = opts.adjustTx.decode(sig);\n // We don't know size of point, but we know size of scalar\n const R = parsePoint(sig.subarray(0, -Fn.BYTES));\n const z = Fn.fromBytes(sig.subarray(-Fn.BYTES));\n return { R, z };\n },\n };\n // Generates pair of (scalar, point)\n const genPointScalarPair = (rng: RNG = randomBytes) => {\n let n = randomScalar(rng);\n if (opts.adjustScalar) n = opts.adjustScalar(n);\n let p = Point.BASE.multiply(n);\n return { scalar: n, point: p };\n };\n // No roots here: root-based methods will throw.\n // `poly` expects a structured roots-of-unity domain, but FROST uses an\n // arbitrary domain and only needs the non-root operations below.\n const nrErr = 'roots are unavailable in FROST polynomial mode';\n const noRoots: RootsOfUnity = {\n info: { G: Fn.ZERO, oddFactor: Fn.ZERO, powerOfTwo: 0 },\n roots() {\n throw new Error(nrErr);\n },\n brp() {\n throw new Error(nrErr);\n },\n inverse() {\n throw new Error(nrErr);\n },\n omega() {\n throw new Error(nrErr);\n },\n clear() {},\n };\n const Poly = poly(Fn, noRoots);\n const msm = (points: P[], scalars: bigint[]) => pippenger(Point, points, scalars);\n\n // Internal stuff uses bigints & Points, external Uint8Arrays\n const polynomialEvaluate = (x: bigint, coeffs: bigint[]): bigint => {\n if (!coeffs.length) throw new Error('empty coefficients');\n return Poly.monomial.eval(coeffs, x);\n };\n const deriveInterpolatingValue = (L: bigint[], xi: bigint): bigint => {\n const err = 'invalid parameters';\n // Generates lagrange coefficient\n if (!L.some((x) => Fn.eql(x, xi))) throw new Error(err);\n // Throws error if any x-coordinate is represented more than once in L.\n const Lset = new Set(L);\n if (Lset.size !== L.length) throw new Error(err);\n // Or if xi is missing\n if (!Lset.has(xi)) throw new Error(err);\n let num = Fn.ONE;\n let den = Fn.ONE;\n for (const x of L) {\n if (Fn.eql(x, xi)) continue;\n num = Fn.mul(num, x); // num *= x\n den = Fn.mul(den, Fn.sub(x, xi)); // RFC 9591 §4.2: denominator *= x_j - x_i\n }\n return Fn.div(num, den);\n };\n const evalutateVSS = (identifier: bigint, commitment: P[]) => {\n // RFC 9591 Appendix C.2: S_i' = Σ_j ScalarMult(vss_commitment[j], i^j).\n const monomial = Poly.monomial.basis(identifier, commitment.length);\n return msm(commitment, monomial);\n };\n // High-level internal stuff\n const generateSecretPolynomial = (\n signers: Signers,\n secret?: TArg<Uint8Array>,\n coeffs?: bigint[],\n rng: RNG = randomBytes\n ) => {\n validateSigners(signers);\n // Dealer/DKG polynomial sampling reuses the same hardened scalar derivation as round-one\n // nonces: overriding `rng` only swaps the entropy source, not the non-zero `1..n-1` policy.\n const secretScalar = secret === undefined ? randomScalar(rng) : Fn.fromBytes(secret);\n if (!coeffs) {\n coeffs = [];\n for (let i = 0; i < signers.min - 1; i++) coeffs.push(randomScalar(rng));\n }\n if (coeffs.length !== signers.min - 1) throw new Error('wrong coefficients length');\n const coefficients: bigint[] = [secretScalar, ...coeffs];\n // RFC 9591 Appendix C.2 commits to every polynomial coefficient with ScalarBaseMult.\n const commitment = coefficients.map((i) => Point.BASE.multiply(i));\n return { coefficients, commitment, secret: secretScalar };\n };\n // Pretty much sign+verify, same as basic\n const ProofOfKnowledge = {\n challenge: (id: bigint, verKey: P, R: P) =>\n HDKG(concatBytes(Fn.toBytes(id), serializePoint(verKey), serializePoint(R))),\n compute(id: bigint, coefficents: bigint[], commitments: P[], rng: RNG = randomBytes) {\n if (coefficents.length < 1) throw new Error('coefficients should have at least one element');\n const { point: R, scalar: k } = genPointScalarPair(rng);\n const verKey = commitments[0]; // verify key is first one\n const c = this.challenge(id, verKey, R);\n const mu = Fn.add(k, Fn.mul(coefficents[0], c)); // mu = k + coeff[0] * c\n return Signature.encode(R, mu);\n },\n validate(id: bigint, commitment: TArg<Commitment[]>, proof: TArg<Uint8Array>) {\n if (commitment.length < 1) throw new Error('commitment should have at least one element');\n const { R, z } = Signature.decode(proof);\n const phi = parsePoint(commitment[0]);\n const c = this.challenge(id, phi, R);\n // R === z*G - phi*c\n if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c))))\n throw new Error('invalid proof of knowledge');\n },\n };\n const Basic = {\n challenge: (R: P, PK: P, msg: TArg<Uint8Array>) => {\n if (opts.challenge) return opts.challenge(R, PK, msg);\n return H2(concatBytes(serializePoint(R), serializePoint(PK), msg));\n },\n sign(msg: TArg<Uint8Array>, sk: bigint, rng: RNG = randomBytes): [P, bigint] {\n const { point: R, scalar: r } = genPointScalarPair(rng);\n const PK = Point.BASE.multiply(sk); // sk*G\n const c = this.challenge(R, PK, msg);\n const z = Fn.add(r, Fn.mul(c, sk)); // r + c * sk\n return [R, z];\n },\n verify(msg: TArg<Uint8Array>, R: P, z: bigint, PK: P): boolean {\n if (opts.adjustPoint) PK = opts.adjustPoint(PK);\n if (opts.adjustPoint) R = opts.adjustPoint(R);\n const c = this.challenge(R, PK, msg);\n const zB = Point.BASE.multiply(z); // z*G\n const cA = PK.multiply(c); // c*PK\n let check = zB.subtract(cA).subtract(R); // zB - cA - R\n // No clearCoffactor on ristretto\n if (check.clearCofactor) check = check.clearCofactor();\n return Point.ZERO.equals(check);\n },\n };\n // === vssVerify\n const validateSecretShare = (identifier: bigint, commitment: P[], signingShare: bigint) => {\n // RFC 9591 Appendix C.2 `vss_verify(share_i, vss_commitment)` is purely algebraic.\n // Public FROST packages still go through Section 3.1 element encoding,\n // which rejects identity points, so a zero share or commitment does not\n // become valid wire data just because VSS matches.\n if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment)))\n throw new Error('invalid secret share');\n };\n const Identifier = {\n fromNumber(n: number): Identifier {\n if (!Number.isSafeInteger(n)) throw new Error('expected safe interger');\n return serializeIdentifier(BigInt(n));\n },\n // Not in spec, but in FROST implementation,\n // seems useful and nice, no need to sync identifiers (would require more interactions)\n derive(s: string): Identifier {\n if (typeof s !== 'string') throw new Error('wrong identifier string: ' + s);\n // Derived identifiers may land anywhere in the scalar field; they are not restricted to\n // sequential `1..max_signers` values.\n return serializeIdentifier(HID(utf8ToBytes(s)));\n },\n };\n // RFC 9591 §4.1: nonce_generate() hashes 32 fresh RNG bytes with SerializeScalar(secret).\n const generateNonce = (secret: bigint, rng: RNG = randomBytes) =>\n H3(concatBytes(rng(32), Fn.toBytes(secret)));\n\n const getGroupCommitment = (\n GPK: P,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>\n ) => {\n const CL = commitmentList.map((i) => [\n i.identifier,\n parseIdentifier(i.identifier),\n parsePoint(i.hiding),\n parsePoint(i.binding),\n ]) as [Identifier, bigint, P, P][];\n // RFC 9591 Sections 4.3/4.4/4.5 and 5.2/5.3 treat commitment_list as sorted by identifier.\n CL.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0));\n // Encode commitment list\n const Cbytes = [];\n for (const [_, id, hC, bC] of CL)\n Cbytes.push(Fn.toBytes(id), serializePoint(hC), serializePoint(bC));\n const encodedCommitmentHash = H5(concatBytes(...Cbytes));\n const rhoPrefix = concatBytes(serializePoint(GPK), H4(msg), encodedCommitmentHash);\n // Compute binding factors\n const bindingFactors: Record<Identifier, bigint> = {};\n for (const [i, id] of CL) {\n bindingFactors[i] = H1(concatBytes(rhoPrefix, Fn.toBytes(id)));\n }\n const points: P[] = [];\n const scalars: bigint[] = [];\n for (const [i, _, hC, bC] of CL) {\n if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC)) throw new Error('infinity commitment');\n points.push(hC, bC);\n scalars.push(Fn.ONE, bindingFactors[i]);\n }\n const groupCommitment = msm(points, scalars); // GC += hC + bC*bindingFactor\n const identifiers = CL.map((i) => i[1]);\n return { identifiers, groupCommitment, bindingFactors };\n };\n const prepareShare = (\n PK: TArg<Uint8Array>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>,\n identifier: Identifier\n ) => {\n // RFC 9591 Sections 4.4/4.5/4.6 feed directly into the Section 5.2 signer computation.\n const GPK = adjustPoint(parsePoint(PK));\n const id = parseIdentifier(identifier);\n const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment(\n GPK,\n commitmentList,\n msg\n );\n const bindingFactor = bindingFactors[identifier];\n const lambda = deriveInterpolatingValue(identifiers, id);\n const challenge = Basic.challenge(groupCommitment, GPK, msg);\n return { lambda, challenge, bindingFactor, groupCommitment };\n };\n Object.freeze(Identifier);\n const frost = {\n Identifier,\n // DKG is Distributed Key Generation, not Trusted Dealer Key Generation.\n DKG: Object.freeze({\n // NOTE: we allow to pass secret scalar from user side,\n // this way it can be derived, instead of random generation\n round1: (\n id: Identifier,\n signers: Signers,\n secret?: TArg<SecretKey>,\n rng: RNG = randomBytes\n ) => {\n validateSigners(signers);\n const idNum = parseIdentifier(id);\n const { coefficients, commitment } = generateSecretPolynomial(\n signers,\n secret,\n undefined,\n rng\n );\n const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng);\n const commitmentBytes = commitment.map(serializePoint) as TRet<Commitment[]>;\n const round1Public: DKG_Round1 = {\n identifier: serializeIdentifier(idNum),\n commitment: commitmentBytes,\n proofOfKnowledge,\n };\n // store secret information for signing\n const round1Secret: DKG_Secret = {\n identifier: idNum,\n coefficients,\n commitment: commitment.map(serializePoint) as TRet<Point[]>,\n // Copy threshold metadata instead of retaining the caller-owned object by reference.\n signers: { min: signers.min, max: signers.max },\n step: 1,\n };\n return { public: round1Public, secret: round1Secret };\n },\n round2: (\n secret: TArg<DKG_Secret>,\n others: TArg<DKG_Round1[]>\n ): TRet<Record<string, DKG_Round2>> => {\n if (others.length !== secret.signers.max - 1)\n throw new Error('wrong number of round1 packages');\n if (!secret.coefficients || secret.step === 3)\n throw new Error('round3 package used in round2');\n const res: Record<Identifier, DKG_Round2> = {};\n for (const p of others) {\n if (p.commitment.length !== secret.signers.min)\n throw new Error('wrong number of commitments');\n const id = parseIdentifier(p.identifier);\n if (id === secret.identifier) throw new Error('duplicate id=' + serializeIdentifier(id));\n\n ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge);\n for (const c of p.commitment) parsePoint(c);\n if (res[p.identifier]) throw new Error('Duplicate id=' + id);\n const signingShare = Fn.toBytes(polynomialEvaluate(id, secret.coefficients));\n res[p.identifier] = {\n identifier: serializeIdentifier(secret.identifier),\n signingShare: signingShare as TRet<Bytes>,\n };\n }\n secret.step = 2;\n return res as TRet<Record<string, DKG_Round2>>;\n },\n round3: (\n secret: TArg<DKG_Secret>,\n round1: TArg<DKG_Round1[]>,\n round2: TArg<DKG_Round2[]>\n ): TRet<Key> => {\n // DKG is outside RFC 9591's signing flow; callers are expected to reuse the same\n // remote round1 packages already accepted in round2, like frost-rs documents.\n if (round1.length !== secret.signers.max - 1)\n throw new Error('wrong length of round1 packages');\n if (!secret.coefficients || secret.step !== 2)\n throw new Error('round2 package used in round3');\n if (round2.length !== round1.length) throw new Error('wrong length of round2 packages');\n const merged: Record<Identifier, TArg<DKG_Round1> & { signingShare?: TArg<Bytes> }> = {};\n for (const r1 of round1) {\n if (!r1.identifier || !r1.commitment) throw new Error('wrong round1 share');\n merged[r1.identifier] = { ...r1 };\n }\n for (const r2 of round2) {\n if (!r2.identifier || !r2.signingShare) throw new Error('wrong round2 share');\n if (!merged[r2.identifier])\n throw new Error('round1 share for ' + r2.identifier + ' is missing');\n merged[r2.identifier].signingShare = r2.signingShare;\n }\n if (Object.keys(merged).length !== round1.length)\n throw new Error('mismatch identifiers between rounds');\n let signingShare = Fn.ZERO;\n if (secret.commitment.length !== secret.signers.min)\n throw new Error('wrong commitments length');\n const localCommitment = secret.commitment.map(parsePoint);\n const localShare = polynomialEvaluate(secret.identifier, secret.coefficients);\n validateSecretShare(secret.identifier, localCommitment, localShare);\n const localCommitmentBytes = localCommitment.map(serializePoint);\n const commitments: Record<Identifier, TArg<Commitment[]>> = {\n [serializeIdentifier(secret.identifier)]: localCommitmentBytes,\n };\n for (const k in merged) {\n const v = merged[k];\n if (!v.signingShare || !v.commitment) throw new Error('mismatch identifiers');\n const id = parseIdentifier(k); // from\n const signingSharePart = Fn.fromBytes(v.signingShare);\n const commitment = v.commitment.map(parsePoint);\n validateSecretShare(secret.identifier, commitment, signingSharePart);\n signingShare = Fn.add(signingShare, signingSharePart);\n const idSer = serializeIdentifier(id);\n if (commitments[idSer]) throw new Error('duplicated id=' + idSer);\n commitments[idSer] = v.commitment;\n }\n signingShare = Fn.add(signingShare, localShare);\n const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO);\n for (const k in commitments) {\n const v = commitments[k];\n if (v.length !== secret.signers.min) throw new Error('wrong commitments length');\n for (let i = 0; i < v.length; i++)\n mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i]));\n }\n const mergedCommitmentBytes = mergedCommitment.map(serializePoint) as TRet<Commitment[]>;\n const verifyingShares: Record<Identifier, Uint8Array> = {};\n for (const k in commitments)\n verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment));\n // This is enough to sign stuff\n let res: TRet<Key> = {\n public: {\n signers: { min: secret.signers.min, max: secret.signers.max },\n commitments: mergedCommitmentBytes,\n verifyingShares: Object.fromEntries(\n Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()])\n ),\n },\n secret: {\n identifier: serializeIdentifier(secret.identifier),\n signingShare: Fn.toBytes(signingShare) as TRet<Bytes>,\n },\n };\n if (opts.adjustDKG) res = opts.adjustDKG(res);\n for (let i = 0; i < secret.coefficients.length; i++)\n secret.coefficients[i] -= secret.coefficients[i];\n delete secret.coefficients;\n secret.step = 3;\n return res;\n },\n clean(secret: TArg<DKG_Secret>) {\n // Instead of replacing secret bigint with another (zero?), we subtract it from itself\n // in the hope that JIT will modify it inplace, instead of creating new value.\n // This is unverified and may not work, but it is best we can do in regard of bigints.\n secret.identifier -= secret.identifier;\n if (secret.coefficients) {\n for (let i = 0; i < secret.coefficients.length; i++)\n secret.coefficients[i] -= secret.coefficients[i];\n }\n // for (const c of secret.commitment) c.fill(0);\n secret.step = 3;\n },\n }),\n // Trusted dealer setup\n // Generates keys for all participants\n trustedDealer(\n signers: Signers,\n identifiers?: Identifier[],\n secret?: TArg<SecretKey>,\n rng: RNG = randomBytes\n ): TRet<DealerShares> {\n // if no identifiers provided, we generated default identifiers\n validateSigners(signers);\n if (identifiers === undefined) {\n identifiers = [];\n for (let i = 1; i <= signers.max; i++) identifiers.push(Identifier.fromNumber(i));\n } else {\n if (!Array.isArray(identifiers) || identifiers.length !== signers.max)\n throw new Error('identifiers should be array of ' + signers.max);\n }\n const identifierNums: Record<Identifier, bigint> = {};\n for (const id of identifiers) {\n const idNum = parseIdentifier(id);\n if (id in identifierNums) throw new Error('duplicated id=' + id);\n identifierNums[id] = idNum;\n }\n const sp = generateSecretPolynomial(signers, secret, undefined, rng);\n const commitmentBytes = sp.commitment.map(serializePoint);\n const secretShares: Record<Identifier, FrostSecret> = {};\n const verifyingShares: Record<Identifier, Uint8Array> = {};\n for (const id of identifiers) {\n const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients);\n verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare));\n secretShares[id] = {\n identifier: id,\n signingShare: Fn.toBytes(signingShare) as TRet<Bytes>,\n };\n }\n return {\n public: {\n signers: { min: signers.min, max: signers.max },\n commitments: commitmentBytes,\n verifyingShares,\n },\n secretShares,\n } as TRet<DealerShares>;\n },\n // Validate secret (from trusted dealer or DKG)\n validateSecret(secret: TArg<FrostSecret>, pub: TArg<FrostPublic>) {\n const id = parseIdentifier(secret.identifier);\n const commitment = pub.commitments.map(parsePoint);\n const signingShare = Fn.fromBytes(secret.signingShare);\n validateSecretShare(id, commitment, signingShare);\n },\n // Actual signing\n // Round 1: each participant commit to nonces\n // Nonces kept private, commitments sent to coordinator (or every other participant)\n // NOTE: we don't need the message at this point, which lets a coordinator\n // keep multiple nonce commitments per participant in advance and skip\n // round1 for signing.\n // But then each participant needs to remember generated shares\n commit(secret: TArg<FrostSecret>, rng: RNG = randomBytes): TRet<GenNonce> {\n const secretScalar = Fn.fromBytes(secret.signingShare);\n const hiding = generateNonce(secretScalar, rng);\n const binding = generateNonce(secretScalar, rng);\n const nonces = { hiding: Fn.toBytes(hiding), binding: Fn.toBytes(binding) };\n return { nonces, commitments: nonceCommitments(secret.identifier, nonces) } as TRet<GenNonce>;\n },\n // Round2: sign. Each participant creates a signature share from the secret\n // and the selected nonce commitments.\n signShare(\n secret: TArg<FrostSecret>,\n pub: TArg<FrostPublic>,\n nonces: TArg<Nonces>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>\n ): TRet<Uint8Array> {\n validateCommitmentsNum(pub.signers, commitmentList.length);\n const hidingNonce0 = Fn.fromBytes(nonces.hiding);\n const bindingNonce0 = Fn.fromBytes(nonces.binding);\n if (Fn.is0(hidingNonce0) || Fn.is0(bindingNonce0))\n throw new Error('signing nonces already used');\n // Reject a coordinator-assigned commitment pair that does not match the signer's own nonce\n // pair. This must happen before suite-specific nonce adjustment; secp256k1-tr may negate the\n // actual signing nonces later, but the coordinator still assigns the original commitments.\n const expectedCommitment = {\n identifier: secret.identifier,\n hiding: serializePoint(Point.BASE.multiply(hidingNonce0)),\n binding: serializePoint(Point.BASE.multiply(bindingNonce0)),\n };\n const commitment = commitmentList.find((i) => i.identifier === secret.identifier);\n if (!commitment) throw new Error('missing signer commitment');\n if (\n bytesToHex(commitment.hiding) !== bytesToHex(expectedCommitment.hiding) ||\n bytesToHex(commitment.binding) !== bytesToHex(expectedCommitment.binding)\n )\n throw new Error('incorrect signer commitment');\n if (opts.adjustSecret) secret = opts.adjustSecret(secret, pub);\n if (opts.adjustPublic) pub = opts.adjustPublic(pub);\n const SK = Fn.fromBytes(secret.signingShare);\n const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(\n pub.commitments[0],\n commitmentList,\n msg,\n secret.identifier\n );\n const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces;\n const hidingNonce = opts.adjustNonces ? Fn.fromBytes(N.hiding) : hidingNonce0;\n const bindingNonce = opts.adjustNonces ? Fn.fromBytes(N.binding) : bindingNonce0;\n const t = Fn.mul(Fn.mul(lambda, SK), challenge); // challenge * lambda * SK\n const t2 = Fn.mul(bindingNonce, bindingFactor); // bindingNonce * bindingFactor\n const r = Fn.toBytes(Fn.add(Fn.add(hidingNonce, t2), t)); // t + t2 + hidingNonce\n // RFC 9591 round-one commitments are one-time-use, and round two must use the nonce\n // corresponding to the published commitment. This API returns mutable local nonce bytes,\n // so consume them after a successful signShare() call: later all-zero reuse fails closed.\n nonces.hiding.fill(0);\n nonces.binding.fill(0);\n return r as TRet<Uint8Array>;\n },\n // Each participant (or coordinator) can verify signatures from other participants\n verifyShare(\n pub: TArg<FrostPublic>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>,\n identifier: Identifier,\n sigShare: TArg<Uint8Array>\n ) {\n if (opts.adjustPublic) pub = opts.adjustPublic(pub);\n const comm = commitmentList.find((i) => i.identifier === identifier);\n if (!comm) throw new Error('cannot find identifier commitment');\n const PK = parsePoint(pub.verifyingShares[identifier]);\n const hidingNonceCommitment = parsePoint(comm.hiding);\n const bindingNonceCommitment = parsePoint(comm.binding);\n const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(\n pub.commitments[0],\n commitmentList,\n msg,\n identifier\n );\n // hC + bC * bF\n let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor));\n if (opts.adjustGroupCommitmentShare)\n commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare);\n const l = Point.BASE.multiply(Fn.fromBytes(sigShare)); // sigShare*G\n // commShare + PK * (challenge * lambda)\n const r = commShare.add(PK.multiply(Fn.mul(challenge, lambda)));\n return l.equals(r);\n },\n // Aggregate multiple signature shares into groupSignature\n aggregate(\n pub: TArg<FrostPublic>,\n commitmentList: TArg<NonceCommitments[]>,\n msg: TArg<Uint8Array>,\n sigShares: TArg<Record<Identifier, Uint8Array>>\n ): TRet<Uint8Array> {\n if (opts.adjustPublic) pub = opts.adjustPublic(pub);\n try {\n validateCommitmentsNum(pub.signers, commitmentList.length);\n } catch {\n throw new AggErr('aggregation failed', []);\n }\n const ids = commitmentList.map((i) => i.identifier);\n if (ids.length !== Object.keys(sigShares).length) throw new AggErr('aggregation failed', []);\n for (const id of ids) {\n if (!(id in sigShares) || !(id in pub.verifyingShares))\n throw new AggErr('aggregation failed', []);\n }\n const GPK = parsePoint(pub.commitments[0]);\n const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg);\n let z = Fn.ZERO;\n // RFC 9591 Section 5.3 aggregates by summing the validated signature shares.\n for (const id of ids) z = Fn.add(z, Fn.fromBytes(sigShares[id])); // z += zi\n if (!Basic.verify(msg, groupCommitment, z, GPK)) {\n const cheaters = [];\n for (const id of ids) {\n if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id])) cheaters.push(id);\n }\n throw new AggErr('aggregation failed', cheaters);\n }\n return Signature.encode(groupCommitment, z);\n },\n // Basic sign/verify using single key\n sign(msg: TArg<Uint8Array>, secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n let sk = Fn.fromBytes(secretKey);\n // Taproot single-key signing needs the same scalar normalization as threshold keys.\n if (opts.adjustScalar) sk = opts.adjustScalar(sk);\n const [R, z] = Basic.sign(msg, sk);\n return Signature.encode(R, z);\n },\n verify(sig: TArg<Signature>, msg: TArg<Uint8Array>, publicKey: TArg<Uint8Array>) {\n const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey);\n const { R, z } = Signature.decode(sig);\n return Basic.verify(msg, R, z, PK);\n },\n // Combine multiple secret shares to restore secret\n combineSecret(shares: TArg<FrostSecret[]>, signers: Signers): TRet<Uint8Array> {\n validateSigners(signers);\n if (!Array.isArray(shares) || shares.length < signers.min)\n throw new Error('wrong secret shares array');\n const points = [];\n const seen: Record<Identifier, boolean> = {};\n // Interpolate over the full provided share set and reject duplicate identifiers.\n for (const s of shares) {\n const idNum = parseIdentifier(s.identifier);\n const id = serializeIdentifier(idNum);\n if (seen[id]) throw new Error('duplicated id=' + id);\n seen[id] = true;\n points.push([idNum, Fn.fromBytes(s.signingShare)]);\n }\n const xCoords = points.map(([x]) => x);\n let res = Fn.ZERO;\n for (const [x, y] of points)\n res = Fn.add(res, Fn.mul(y, deriveInterpolatingValue(xCoords, x)));\n return Fn.toBytes(res) as TRet<Uint8Array>;\n },\n // Utils\n utils: Object.freeze({\n Fn, // NOTE: we re-export it here because it may be different from Point.Fn (ed448 is fun!)\n // Test RNG overrides still go through noble's non-zero scalar derivation; this is not a raw\n // \"bytes become scalar\" escape hatch.\n randomScalar: (rng: RNG = randomBytes) =>\n Fn.toBytes(genPointScalarPair(rng).scalar) as TRet<Uint8Array>,\n generateSecretPolynomial: (\n signers: Signers,\n secret?: TArg<Uint8Array>,\n coeffs?: bigint[],\n rng?: RNG\n ) => {\n const res = generateSecretPolynomial(signers, secret, coeffs, rng);\n return { ...res, commitment: res.commitment.map(serializePoint) as TRet<Point[]> };\n },\n }),\n };\n return Object.freeze(frost) as TRet<FROST>;\n}\n"],"mappings":";;;AAwHM,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;AAE9B;AAcM,SAAU,QAAQ,GAAW,QAAgB,IAAE;AACnD,MAAI,OAAO,MAAM,UAAU;AACzB,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,UAAU,GAAG,MAAM,wBAAwB,OAAO,CAAC,EAAE;EACjE;AACA,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI,GAAG;AACrC,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,WAAW,GAAG,MAAM,8BAA8B,CAAC,EAAE;EACjE;AACF;AAgBM,SAAU,OACd,OACA,QACA,QAAgB,IAAE;AAElB,QAAM,QAAQ,QAAQ,KAAK;AAC3B,QAAM,MAAM,OAAO;AACnB,QAAM,WAAW,WAAW;AAC5B,MAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;AAC1C,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,QAAQ,WAAW,cAAc,MAAM,KAAK;AAClD,UAAM,MAAM,QAAQ,UAAU,GAAG,KAAK,QAAQ,OAAO,KAAK;AAC1D,UAAM,UAAU,SAAS,wBAAwB,QAAQ,WAAW;AACpE,QAAI,CAAC;AAAO,YAAM,IAAI,UAAU,OAAO;AACvC,UAAM,IAAI,WAAW,OAAO;EAC9B;AACA,SAAO;AACT;AAkCM,SAAU,MAAM,GAAc;AAClC,MAAI,OAAO,MAAM,cAAc,OAAO,EAAE,WAAW;AACjD,UAAM,IAAI,UAA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AAG,EAAC,IAAK,UAAU,OAAO,GAAG;AACrC,aAAO,MAAM,OAAO,KAAK,GAAG,GAAG,EAAE;IACnC;;IAEA,cAAc,QAA6B,SAAgB;AACzD,sBAAgB,OAAO;AACvB,UAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS,QAAQ;AACpD,cAAM,IAAI,MAAM,2BAA2B;AAC7C,YAAM,SAAS,CAAA;AACf,YAAM,OAAoC,CAAA;AAE1C,iBAAW,KAAK,QAAQ;AACtB,cAAM,QAAQ,gBAAgB,EAAE,UAAU;AAC1C,cAAM,KAAK,oBAAoB,KAAK;AACpC,YAAI,KAAK,EAAE;AAAG,gBAAM,IAAI,MAAM,mBAAmB,EAAE;AACnD,aAAK,EAAE,IAAI;AACX,eAAO,KAAK,CAAC,OAAO,GAAG,UAAU,EAAE,YAAY,CAAC,CAAC;MACnD;AACA,YAAM,UAAU,OAAO,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC;AACrC,UAAI,MAAM,GAAG;AACb,iBAAW,CAAC,GAAG,CAAC,KAAK;AACnB,cAAM,GAAG,IAAI,KAAK,GAAG,IAAI,GAAG,yBAAyB,SAAS,CAAC,CAAC,CAAC;AACnE,aAAO,GAAG,QAAQ,GAAG;IACvB;;IAEA,OAAO,OAAO,OAAO;MACnB;;;;MAGA,cAAc,CAAC,MAAWD,iBACxB,GAAG,QAAQ,mBAAmB,GAAG,EAAE,MAAM;MAC3C,0BAA0B,CACxB,SACA,QACA,QACA,QACE;AACF,cAAM,MAAM,yBAAyB,SAAS,QAAQ,QAAQ,GAAG;AACjE,eAAO,EAAE,GAAG,KAAK,YAAY,IAAI,WAAW,IAAI,cAAc,EAAkB;MAClF;KACD;;AAEH,SAAO,OAAO,OAAO,KAAK;AAC5B;","names":["isLE","abytes","anumber","bytesToHex","concatBytes","hexToBytes","isBytes","randomBytes","abytes","concatBytes","_0n","_1n","_0n","_1n","_1n","anumber","_0n","_1n","abytes","isLE","_1n","isLE","abytes","_0n","_1n","wbits","isLE","_0n","isBytes","abytes","concatBytes","createHasher","isBytes","roots","opts","concatBytes","randomBytes","bytesToHex","hexToBytes"]}