@toon-protocol/client-mcp 0.20.2 → 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.
- package/dist/{chunk-LN2OF264.js → chunk-6GXZ4KRO.js} +257 -1552
- package/dist/chunk-6GXZ4KRO.js.map +1 -0
- package/dist/{chunk-ZKSFO7M3.js → chunk-F3XAIOGQ.js} +2 -2
- package/dist/{chunk-IAOKAQLA.js → chunk-FDUYHYB2.js} +2 -2
- package/dist/{chunk-IAOKAQLA.js.map → chunk-FDUYHYB2.js.map} +1 -1
- package/dist/chunk-IYPIOSEF.js +3856 -0
- package/dist/chunk-IYPIOSEF.js.map +1 -0
- package/dist/{chunk-UPIAVE44.js → chunk-JFDVE4IA.js} +544 -4115
- package/dist/chunk-JFDVE4IA.js.map +1 -0
- package/dist/{chunk-WS3GVRQJ.js → chunk-TGIKIMXO.js} +9 -7
- package/dist/{chunk-WS3GVRQJ.js.map → chunk-TGIKIMXO.js.map} +1 -1
- package/dist/chunk-V7D5HJBT.js +1363 -0
- package/dist/chunk-V7D5HJBT.js.map +1 -0
- package/dist/daemon.js +6 -4
- package/dist/daemon.js.map +1 -1
- package/dist/{ed25519-VBPL32VX.js → ed25519-U6LNJH4K.js} +3 -2
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +6 -4
- package/dist/mcp.js.map +1 -1
- package/dist/mina-channel-deploy-CO2LMPPB-H2N5FX4G.js +12 -0
- package/dist/mina-channel-deploy-CO2LMPPB-H2N5FX4G.js.map +1 -0
- package/dist/{node-WPA2UDEH-RCLJ66AU.js → node-WPA2UDEH-HZP3B4FH.js} +3 -3
- package/dist/{node-WPA2UDEH-RCLJ66AU.js.map → node-WPA2UDEH-HZP3B4FH.js.map} +1 -1
- package/package.json +5 -5
- package/dist/chunk-LN2OF264.js.map +0 -1
- package/dist/chunk-UPIAVE44.js.map +0 -1
- /package/dist/{chunk-ZKSFO7M3.js.map → chunk-F3XAIOGQ.js.map} +0 -0
- /package/dist/{ed25519-VBPL32VX.js.map → ed25519-U6LNJH4K.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
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/edwards.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/hash-to-curve.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/frost.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/montgomery.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/abstract/oprf.ts","../../../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/src/ed25519.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 * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n aInRange,\n asafenumber,\n bytesToHex,\n bytesToNumberLE,\n concatBytes,\n copyBytes,\n hexToBytes,\n isBytes,\n notImplemented,\n validateObject,\n randomBytes as wcRandomBytes,\n type FHash,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport { type IField } from './modular.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);\n\n/** Extended Edwards point with X/Y/Z/T coordinates. */\nexport interface EdwardsPoint extends CurvePoint<bigint, EdwardsPoint> {\n /** extended X coordinate. Different from affine x. */\n readonly X: bigint;\n /** extended Y coordinate. Different from affine y. */\n readonly Y: bigint;\n /** extended Z coordinate */\n readonly Z: bigint;\n /** extended T coordinate */\n readonly T: bigint;\n}\n/** Constructor and decoding helpers for extended Edwards points. */\nexport interface EdwardsPointCons extends CurvePointCons<EdwardsPoint> {\n /** Create a point from extended X/Y/Z/T coordinates without validation. */\n new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint;\n /**\n * Return the curve parameters used by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): EdwardsOpts;\n /**\n * Decode a point from bytes, optionally using ZIP-215 rules.\n * @param bytes - Encoded point bytes.\n * @param zip215 - Whether to accept ZIP-215 encodings.\n * @returns Decoded Edwards point.\n */\n fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint;\n /**\n * Decode a point from hex, optionally using ZIP-215 rules.\n * @param hex - Encoded point hex.\n * @param zip215 - Whether to accept ZIP-215 encodings.\n * @returns Decoded Edwards point.\n */\n fromHex(hex: string, zip215?: boolean): EdwardsPoint;\n}\n\n/**\n * Twisted Edwards curve options.\n *\n * * a: formula param\n * * d: formula param\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor. h*n is group order; n is subgroup order\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type EdwardsOpts = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Edwards curve parameter `a`. */\n a: bigint;\n /** Edwards curve parameter `d`. */\n d: bigint;\n /** Generator x coordinate. */\n Gx: bigint;\n /** Generator y coordinate. */\n Gy: bigint;\n}>;\n\n/**\n * Extra curve options for Twisted Edwards.\n *\n * * Fp: redefined Field over curve.p\n * * Fn: redefined Field over curve.n\n * * uvRatio: helper function for decompression, calculating √(u/v)\n */\nexport type EdwardsExtraOpts = Partial<{\n /** Optional base-field override. */\n Fp: IField<bigint>;\n /** Optional scalar-field override. */\n Fn: IField<bigint>;\n /** Whether field encodings are little-endian. */\n FpFnLE: boolean;\n /** Square-root ratio helper used during point decompression. */\n uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint };\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) options.\n *\n * * hash: hash function used to hash secret keys and messages\n * * adjustScalarBytes: clears bits to get valid field element\n * * domain: Used for hashing\n * * mapToCurve: for hash-to-curve standard\n * * prehash: RFC 8032 pre-hashing of messages to sign() / verify()\n * * randomBytes: function generating random bytes, used for randomSecretKey\n */\nexport type EdDSAOpts = Partial<{\n /** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */\n adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Domain-separation helper for contexts and prehash mode. */\n domain: (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => TRet<Uint8Array>;\n /** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */\n mapToCurve: (scalar: bigint[]) => AffinePoint<bigint>;\n /** Optional prehash function used before signing or verifying messages. */\n prehash: FHash;\n /** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */\n zip215: boolean;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n}>;\n\n/**\n * EdDSA (Edwards Digital Signature algorithm) helper namespace.\n * Allows creating and verifying signatures, and deriving public keys.\n */\nexport interface EdDSA {\n /**\n * Generate a secret/public key pair.\n * @param seed - Optional seed material.\n * @returns Secret/public key pair.\n */\n keygen: (seed?: TArg<Uint8Array>) => { secretKey: TRet<Uint8Array>; publicKey: TRet<Uint8Array> };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Sign a message with an EdDSA secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param options - Optional signature tweaks:\n * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n options?: TArg<{ context?: Uint8Array }>\n ) => TRet<Uint8Array>;\n /**\n * Verify a signature against a message and public key.\n * @param sig - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param options - Optional verification tweaks:\n * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448.\n * - `zip215` (optional): Whether to accept ZIP-215 encodings.\n * @returns Whether the signature is valid.\n */\n verify: (\n sig: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n options?: TArg<{ context?: Uint8Array; zip215?: boolean }>\n ) => boolean;\n /** Point constructor used by this signature scheme. */\n Point: EdwardsPointCons;\n /** Helper utilities for key validation and Montgomery conversion. */\n utils: {\n /**\n * Generate a valid random secret key.\n * Optional seed bytes are only length-checked and returned unchanged.\n */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Check whether a secret key has the expected encoding. */\n isValidSecretKey: (secretKey: TArg<Uint8Array>) => boolean;\n /** Check whether a public key decodes to a valid point. */\n isValidPublicKey: (publicKey: TArg<Uint8Array>, zip215?: boolean) => boolean;\n\n /**\n * Converts ed public key to x public key.\n *\n * There is NO `fromMontgomery`:\n * - There are 2 valid ed25519 points for every x25519, with flipped coordinate\n * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally*\n * accepts inputs on the quadratic twist, which can't be moved to ed25519\n *\n * @example\n * Converts ed public key to x public key.\n *\n * ```js\n * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey());\n * const someonesPub = ed25519.utils.toMontgomery(someonesPub);\n * const aPriv = x25519.utils.randomSecretKey();\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomery: (publicKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Converts ed secret key to x secret key.\n * @example\n * Converts ed secret key to x secret key.\n *\n * ```js\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey());\n * const aPriv_ed = ed25519.utils.randomSecretKey();\n * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed);\n * const shared = x25519.getSharedSecret(aPriv, someonesPub)\n * ```\n */\n toMontgomerySecret: (secretKey: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Return the expanded private key components used by RFC8032 signing. */\n getExtendedPublicKey: (key: TArg<Uint8Array>) => {\n head: TRet<Uint8Array>;\n prefix: TRet<Uint8Array>;\n scalar: bigint;\n point: EdwardsPoint;\n pointBytes: TRet<Uint8Array>;\n };\n };\n /** Byte lengths for keys and signatures exposed by this scheme. */\n lengths: CurveLengths;\n}\n\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp: TArg<IField<bigint>>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=8\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(\n params: TArg<EdwardsOpts>,\n extraOpts: TArg<EdwardsExtraOpts> = {}\n): EdwardsPointCons {\n const opts = extraOpts as EdwardsExtraOpts;\n const validated = createCurveFields('edwards', params as EdwardsOpts, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE as EdwardsOpts;\n const { h: cofactor } = CURVE;\n validateObject(opts, {}, { uvRatio: 'function' });\n\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n: bigint) => Fp.create(n); // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n opts.uvRatio === undefined\n ? (u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title: string, n: bigint, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n\n function aedpoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('EdwardsPoint expected');\n }\n\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements EdwardsPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: bigint;\n readonly Y: bigint;\n readonly Z: bigint;\n readonly T: bigint;\n\n constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n\n static CURVE(): EdwardsOpts {\n return CURVE;\n }\n\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes: Uint8Array, zip215 = false): Point {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid) throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n\n static fromHex(hex: string, zip215 = false): Point {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n precompute(windowSize: number = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_2n); // random number\n return this;\n }\n\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity(): void {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar: bigint): Point {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar)) throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n) return Point.ZERO;\n if (this.is0() || scalar === _1n) return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Clears cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.clearCofactor().is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x, y };\n }\n\n clearCofactor(): Point {\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n toBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (Fn.BITS >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport abstract class PrimeEdwardsPoint<T extends PrimeEdwardsPoint<T>>\n implements CurvePoint<bigint, T>\n{\n static BASE: PrimeEdwardsPoint<any>;\n static ZERO: PrimeEdwardsPoint<any>;\n static Fp: IField<bigint>;\n static Fn: IField<bigint>;\n\n protected readonly ep: EdwardsPoint;\n\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep: EdwardsPoint) {\n this.ep = ep;\n }\n\n // Abstract methods that must be implemented by subclasses\n abstract toBytes(): Uint8Array;\n abstract equals(other: T): boolean;\n\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes: Uint8Array): any {\n notImplemented();\n }\n\n static fromHex(_hex: string): any {\n notImplemented();\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n // Common implementations\n clearCofactor(): T {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this as any;\n }\n\n assertValidity(): void {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ?: bigint): AffinePoint<bigint> {\n return this.ep.toAffine(invertedZ);\n }\n\n toHex(): string {\n return bytesToHex(this.toBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n isTorsionFree(): boolean {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n\n isSmallOrder(): boolean {\n return false;\n }\n\n add(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n\n subtract(other: T): T {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): T {\n return this.init(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): T {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): T {\n return this.init(this.ep.double());\n }\n\n negate(): T {\n return this.init(this.ep.negate());\n }\n\n precompute(windowSize?: number, isLazy?: boolean): T {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this as unknown as T;\n }\n\n // Helper methods\n abstract is0(): boolean;\n protected abstract assertSame(other: T): void;\n protected abstract init(ep: EdwardsPoint): T;\n}\n\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(\n Point: EdwardsPointCons,\n cHash: TArg<FHash>,\n eddsaOpts: TArg<EdDSAOpts> = {}\n): EdDSA {\n if (typeof cHash !== 'function') throw new Error('\"hash\" function param is required');\n const hash = cHash as FHash;\n const opts = eddsaOpts as EdDSAOpts;\n validateObject(\n opts,\n {},\n {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n }\n );\n\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = (hash as FHash & { outputLen?: number }).outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const adjustScalarBytes =\n opts.adjustScalarBytes === undefined\n ? (bytes: TArg<Uint8Array>) => bytes as TRet<Uint8Array>\n : opts.adjustScalarBytes;\n const domain =\n opts.domain === undefined\n ? (data: TArg<Uint8Array>, ctx: TArg<Uint8Array>, phflag: boolean) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data as TRet<Uint8Array>;\n }\n : opts.domain; // NOOP\n\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash: TArg<Uint8Array>): bigint {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key: TArg<Uint8Array>) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len) as TRet<Uint8Array>; // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey: TArg<Uint8Array>) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes() as TRet<Uint8Array>;\n return { head, prefix, scalar, point, pointBytes };\n }\n\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(\n context: TArg<Uint8Array> = Uint8Array.of(),\n ...msgs: TArg<Uint8Array[]>\n ) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(\n msg: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n options: TArg<{ context?: Uint8Array }> = {}\n ): TRet<Uint8Array> {\n msg = abytes(msg, undefined, 'message');\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result') as TRet<Uint8Array>;\n }\n\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts: TArg<{ context?: Uint8Array; zip215?: boolean }> = {\n zip215: opts.zip215,\n };\n\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(\n sig: TArg<Uint8Array>,\n msg: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n options = verifyOpts\n ): boolean {\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined) abool(zip215, 'zip215');\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder()) return false;\n\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed') as TRet<Uint8Array>;\n }\n\n function isValidSecretKey(key: TArg<Uint8Array>): boolean {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n\n function isValidPublicKey(key: TArg<Uint8Array>, zip215?: boolean): boolean {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n } catch (error) {\n return false;\n }\n }\n\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey: TArg<Uint8Array>): TRet<Uint8Array> {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u) as TRet<Uint8Array>;\n },\n toMontgomerySecret(secretKey: TArg<Uint8Array>): TRet<Uint8Array> {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = hash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size) as TRet<Uint8Array>;\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n }) satisfies Signer;\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 * 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 * 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","/**\n * Montgomery curve methods. It's not really whole montgomery curve,\n * just bunch of very specific methods for X25519 / X448 from\n * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748)\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n aInRange,\n bytesToNumberLE,\n copyBytes,\n numberToBytesLE,\n randomBytes,\n validateObject,\n type CryptoKeys,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport { createKeygen, type CurveLengths } from './curve.ts';\nimport { mod } from './modular.ts';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\n\n/** Curve-specific hooks required to build one X25519/X448 helper. */\nexport type MontgomeryOpts = {\n /** Prime field modulus. */\n P: bigint;\n /** RFC 7748 variant name. */\n type: 'x25519' | 'x448';\n /**\n * Clamp or otherwise normalize one scalar byte string before use.\n * @param bytes - Raw secret scalar bytes.\n * @returns Adjusted scalar bytes ready for Montgomery multiplication.\n */\n adjustScalarBytes: (bytes: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Invert one field element with exponentiation by `p - 2`.\n * @param x - Field element to invert.\n * @returns Multiplicative inverse of `x`.\n */\n powPminus2: (x: bigint) => bigint;\n /**\n * Optional randomness source for `keygen()` and `utils.randomSecretKey()`.\n * Receives the requested byte length and returns fresh random bytes.\n */\n randomBytes?: (bytesLength?: number) => TRet<Uint8Array>;\n};\n\n/** Public X25519/X448 ECDH API built on a Montgomery ladder. */\nexport type MontgomeryECDH = {\n /**\n * Multiply one scalar by one Montgomery `u` coordinate.\n * @param scalar - Secret scalar bytes.\n * @param u - Public Montgomery `u` coordinate.\n * @returns Shared point encoded as bytes.\n */\n scalarMult: (scalar: TArg<Uint8Array>, u: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Multiply one scalar by the curve base point.\n * @param scalar - Secret scalar bytes.\n * @returns Public key bytes.\n */\n scalarMultBase: (scalar: TArg<Uint8Array>) => TRet<Uint8Array>;\n /**\n * Derive a shared secret from a local secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * Rejects low-order public inputs instead of returning the all-zero shared secret.\n * @returns Shared secret bytes.\n */\n getSharedSecret: (secretKeyA: TArg<Uint8Array>, publicKeyB: TArg<Uint8Array>) => TRet<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: TArg<Uint8Array>) => TRet<Uint8Array>;\n /** Utility helpers for secret-key generation. */\n utils: {\n /** Generate one random secret key with the curve's expected byte length. */\n randomSecretKey: () => TRet<Uint8Array>;\n };\n /** Encoded Montgomery base point `u`. */\n GuBytes: TRet<Uint8Array>;\n /** Public lengths for keys and seeds. */\n lengths: CurveLengths;\n /**\n * Generate one random secret/public keypair.\n * @param seed - Optional seed bytes to use instead of random generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg<Uint8Array>) => {\n secretKey: TRet<Uint8Array>;\n publicKey: TRet<Uint8Array>;\n };\n};\n\nfunction validateOpts(curve: TArg<MontgomeryOpts>) {\n // Validate constructor config eagerly, but do not call user-provided hooks here:\n // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are\n // enough to fail fast on malformed configs without consuming user state.\n validateObject(\n curve,\n {\n P: 'bigint',\n type: 'string',\n adjustScalarBytes: 'function',\n powPminus2: 'function',\n },\n {\n randomBytes: 'function',\n }\n );\n return Object.freeze({ ...curve } as const);\n}\n\n/**\n * @param curveDef - Montgomery curve definition.\n * @returns ECDH helper namespace.\n * @throws If the curve definition or derived shared point is invalid. {@link Error}\n * @example\n * Perform one X25519 key exchange through the generic Montgomery helper.\n *\n * ```ts\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function montgomery(curveDef: TArg<MontgomeryOpts>): TRet<MontgomeryECDH> {\n const CURVE = validateOpts(curveDef);\n const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE;\n const is25519 = type === 'x25519';\n if (!is25519 && type !== 'x448') throw new Error('invalid type');\n const randomBytes_ = rand === undefined ? randomBytes : rand;\n\n const montgomeryBits = is25519 ? 255 : 448;\n const fieldLen = is25519 ? 32 : 56;\n const Gu = is25519 ? BigInt(9) : BigInt(5);\n // RFC 7748 #5:\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and\n // (156326 - 2) / 4 = 39081 for curve448/X448\n // const a = is25519 ? 486662n : 156326n;\n const a24 = is25519 ? BigInt(121665) : BigInt(39081);\n // RFC: x25519 \"the resulting integer is of the form 2^254 plus\n // eight times a value between 0 and 2^251 - 1 (inclusive)\"\n // x448: \"2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)\"\n const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447);\n const maxAdded = is25519\n ? BigInt(8) * _2n ** BigInt(251) - _1n\n : BigInt(4) * _2n ** BigInt(445) - _1n;\n const maxScalar = minScalar + maxAdded + _1n; // (inclusive)\n const modP = (n: bigint) => mod(n, P);\n const GuBytes = encodeU(Gu);\n function encodeU(u: bigint): TRet<Uint8Array> {\n return numberToBytesLE(modP(u), fieldLen);\n }\n function decodeU(u: TArg<Uint8Array>): bigint {\n const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate'));\n // RFC: When receiving such an array, implementations of X25519\n // (but not X448) MUST mask the most significant bit in the final byte.\n if (is25519) _u[31] &= 127; // 0b0111_1111\n // RFC: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime. The non-canonical\n // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224\n // - 1 through 2^448 - 1 for X448.\n return modP(bytesToNumberLE(_u));\n }\n function decodeScalar(scalar: TArg<Uint8Array>): bigint {\n return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar'))));\n }\n function scalarMult(scalar: TArg<Uint8Array>, u: TArg<Uint8Array>): TRet<Uint8Array> {\n const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar));\n // Some public keys are useless, of low-order. Curve author doesn't think\n // it needs to be validated, but we do it nonetheless.\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('invalid private or public key received');\n return encodeU(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n function scalarMultBase(scalar: TArg<Uint8Array>): TRet<Uint8Array> {\n return scalarMult(scalar, GuBytes);\n }\n const getPublicKey = scalarMultBase;\n const getSharedSecret = scalarMult;\n\n // cswap from RFC7748 \"example code\"\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): { x_2: bigint; x_3: bigint } {\n // dummy = mask(swap) AND (x_2 XOR x_3)\n // Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n // and x_3, computed, e.g., as mask(swap) = 0 - swap.\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy\n x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy\n return { x_2, x_3 };\n }\n\n /**\n * Montgomery x-only multiplication ladder for the selected X25519/X448 curve.\n * @param pointU - decoded Montgomery u coordinate for the selected curve\n * @param scalar - decoded clamped scalar by which the point is multiplied\n * @returns resulting Montgomery u coordinate for the selected curve\n */\n function montgomeryLadder(u: bigint, scalar: bigint): bigint {\n aInRange('u', u, _0n, P);\n aInRange('scalar', scalar, minScalar, maxScalar);\n const k = scalar;\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n ({ x_2, x_3 } = cswap(swap, x_2, x_3));\n ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3));\n const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent\n return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2))\n }\n const lengths = {\n secretKey: fieldLen,\n publicKey: fieldLen,\n seed: fieldLen,\n };\n const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n seed = seed === undefined ? randomBytes_(fieldLen) : seed;\n abytes(seed, lengths.seed, 'seed');\n // Reuse caller-supplied seed bytes verbatim; clamping is deferred until\n // decodeScalar(...) when the secret key is actually used.\n return seed as TRet<Uint8Array>;\n };\n const utils = { randomSecretKey };\n Object.freeze(lengths);\n Object.freeze(utils);\n\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getSharedSecret,\n getPublicKey,\n scalarMult,\n scalarMultBase,\n utils,\n GuBytes: GuBytes.slice() as TRet<Uint8Array>,\n lengths,\n }) satisfies CryptoKeys;\n}\n","/**\n * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups.\n * https://www.rfc-editor.org/rfc/rfc9497\n *\n\nOPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`:\n\n- Server cannot calculate Output by itself: it doesn't know Input\n- Client cannot calculate Output by itself: it doesn't know server secretKey\n- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't\n link Input to some value.\n\n## Issues\n\n- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server\n (solveable by domain separation in POPRF)\n- High-level protocol needs to be constructed on top, because OPRF is low-level\n\n## Use cases\n\n1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE)\n without revealing the password to the server.\n2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their\n private sets without revealing non-intersecting elements.\n3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials\n (e.g., Privacy Pass) using blind OPRF evaluation.\n4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which\n item they accessed.\n5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping\n queries private.\n6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse\n (e.g., CAPTCHA bypass) without compromising user privacy.\n\n## Modes\n\n- OPRF: simple mode, client doesn't need to know server public key\n- VOPRF: verifiable mode. It lets the client verify that the server used the\n secret key corresponding to a known public key\n- POPRF: partially oblivious mode, VOPRF + domain separation\n\nThere is also non-interactive mode (Evaluate), which creates Output\nnon-interactively with knowledge of the secret key.\n\nFlow:\n- (once) Server generates secret and public keys, distributes public keys to clients\n - deterministically: `deriveKeyPair` or just random: `generateKeyPair`\n- Client blinds input: `blind(secretInput)`\n- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client\n- Client creates output using result of evaluation via 'finalize'\n\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n asciiToBytes,\n bytesToNumberBE,\n bytesToNumberLE,\n concatBytes,\n numberToBytesBE,\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 { _DST_scalar, type H2CDSTOpts } from './hash-to-curve.ts';\nimport { getMinHashLength, mapHashToField } from './modular.ts';\n\n// OPRF is designed to be used across network, so we default to serialized values.\n/** Serialized group element passed between OPRF participants. */\nexport type PointBytes = Uint8Array;\n/** Serialized scalar used for blinds and server secret keys. */\nexport type ScalarBytes = Uint8Array;\n/** Arbitrary byte input or output used by the OPRF protocol. */\nexport type Bytes = Uint8Array;\nconst _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar);\n/** Cryptographically secure byte generator used for blinds and proofs. */\nexport type RNG = typeof randomBytes;\n\n/** Curve and hash hooks required to instantiate one OPRF ciphersuite. */\nexport type OPRFOpts<P extends CurvePoint<any, P>> = {\n /** Human-readable suite identifier used for domain separation. */\n name: string;\n /**\n * Prime-order group used by the OPRF construction.\n * Kept generic because the suite returns serialized points.\n */\n Point: CurvePointCons<P>;\n // Fn: IField<bigint>;\n /**\n * Hash function used for transcripts, proofs, and outputs.\n * @param msg - Message bytes to hash.\n * @returns Digest bytes.\n */\n hash(msg: TArg<Bytes>): TRet<Bytes>;\n /**\n * Hash arbitrary bytes into one scalar in the suite order.\n * @param msg - Message bytes to map.\n * @param options - Hash-to-field domain-separation options. See {@link H2CDSTOpts}.\n * Implementations MUST treat `msg` and `options` as read-only.\n * @returns Scalar in the suite order.\n */\n hashToScalar(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts>): bigint;\n /**\n * Hash arbitrary bytes directly onto one curve point.\n * @param msg - Message bytes to map.\n * @param options - Hash-to-curve domain-separation options. See {@link H2CDSTOpts}.\n * Implementations MUST treat `msg` and `options` as read-only.\n * @returns Point on the suite curve.\n */\n hashToGroup(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts>): P;\n};\n\n/** Server keypair for one OPRF suite. */\nexport type OPRFKeys = {\n /** Secret scalar kept by the server. */\n secretKey: TRet<ScalarBytes>;\n /** Public point distributed to clients in verifiable modes. */\n publicKey: TRet<PointBytes>;\n};\n/** Result of the client-side blind step. */\nexport type OPRFBlind = {\n /** Secret blind scalar that the client keeps locally. */\n blind: TRet<ScalarBytes>;\n /** Blinded group element sent to the server. */\n blinded: TRet<PointBytes>;\n};\n/** Server response for one verifiable OPRF evaluation. */\nexport type OPRFBlindEval = {\n /** Evaluated group element returned by the server. */\n evaluated: TRet<PointBytes>;\n /** DLEQ proof binding the evaluation to the server public key. */\n proof: TRet<Bytes>;\n};\n/** Server response for a batch of verifiable OPRF evaluations. */\nexport type OPRFBlindEvalBatch = {\n /** Evaluated group elements returned for each blinded input. */\n evaluated: TRet<PointBytes[]>;\n /** Batch proof covering all evaluated elements. */\n proof: TRet<Bytes>;\n};\n/** One finalized transcript item used by batch verification helpers. */\nexport type OPRFFinalizeItem = {\n /** Original client input. */\n input: Bytes;\n /** Secret blind scalar used for the input. */\n blind: ScalarBytes;\n /** Evaluated point returned by the server. */\n evaluated: PointBytes;\n /** Blinded point originally sent to the server. */\n blinded: PointBytes;\n};\n/** Result of the POPRF client-side blind step with the tweaked server public key. */\nexport type OPRFBlindTweaked = OPRFBlind & { tweakedKey: TRet<PointBytes> };\n\n/**\n * Represents a full OPRF ciphersuite implementation according to RFC 9497.\n * This object bundles the three protocol variants (OPRF, VOPRF, POPRF) for a specific\n * prime-order group and hash function combination.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9497.html\n */\nexport type OPRF = {\n /**\n * The unique identifier for the ciphersuite, e.g., \"ristretto255-SHA512\".\n * This name is used for domain separation to prevent cross-protocol attacks.\n */\n readonly name: string;\n\n /**\n * The base Oblivious Pseudorandom Function (OPRF) mode (mode 0x00).\n * This is a two-party protocol between a client and a server to compute F(k, x)\n * where 'k' is the server's key and 'x' is the client's input.\n *\n * The client learns the output F(k, x) but nothing about 'k'.\n * The server learns nothing about 'x' or F(k, x).\n * This mode is NOT verifiable; the client cannot prove the server used a specific key.\n */\n readonly oprf: {\n /**\n * (Server-side) Generates a new random private/public key pair for the server.\n * @returns A new key pair.\n */\n generateKeyPair(): TRet<OPRFKeys>;\n\n /**\n * (Server-side) Deterministically derives a private/public key pair from a seed.\n * @param seed - A 32-byte cryptographically secure random seed.\n * @param keyInfo - An optional byte string for domain separation.\n * @returns The derived key pair.\n */\n deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;\n\n /**\n * (Client-side) The first step of the protocol. The client blinds its private input.\n * @param input - The client's private input bytes.\n * @param rng - An optional cryptographically secure random number generator.\n * @returns An object containing the `blind` scalar (which the client MUST keep secret)\n * and the `blinded` element (which the client sends to the server).\n */\n blind(input: TArg<Bytes>, rng?: RNG): TRet<OPRFBlind>;\n\n /**\n * (Server-side) The second step. The server evaluates the client's blinded element\n * using its secret key.\n * @param secretKey - The server's private key.\n * @param blinded - The blinded group element received from the client.\n * @returns The evaluated group element, to be sent back to the client.\n */\n blindEvaluate(secretKey: TArg<ScalarBytes>, blinded: TArg<PointBytes>): TRet<PointBytes>;\n\n /**\n * (Client-side) The final step. The client unblinds the server's response to\n * compute the final OPRF output.\n * @param input - The original private input from the `blind` step.\n * @param blind - The secret scalar from the `blind` step.\n * @param evaluated - The evaluated group element received from the server.\n * @returns The final OPRF output, `Hash(len(input)||input||len(unblinded)||unblinded||\"Finalize\")`.\n */\n finalize(\n input: TArg<Bytes>,\n blind: TArg<ScalarBytes>,\n evaluated: TArg<PointBytes>\n ): TRet<Bytes>;\n };\n\n /**\n * The Verifiable Oblivious Pseudorandom Function (VOPRF) mode (mode 0x01).\n * This mode extends the base OPRF by providing a proof that the server used the\n * secret key corresponding to its known public key.\n */\n readonly voprf: {\n /** (Server-side) Generates a key pair for the VOPRF mode. */\n generateKeyPair(): TRet<OPRFKeys>;\n /** (Server-side) Deterministically derives a key pair for the VOPRF mode. */\n deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;\n /** (Client-side) Blinds the client's private input for the VOPRF protocol. */\n blind(input: TArg<Bytes>, rng?: RNG): TRet<OPRFBlind>;\n\n /**\n * (Server-side) Evaluates the client's blinded element and generates a DLEQ proof\n * of correctness.\n * @param secretKey - The server's private key.\n * @param publicKey - The server's public key, used in proof generation.\n * @param blinded - The blinded group element received from the client.\n * @param rng - An optional cryptographically secure random number generator for the proof.\n * @returns The evaluated element and a proof of correct computation.\n */\n blindEvaluate(\n secretKey: TArg<ScalarBytes>,\n publicKey: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n rng?: RNG\n ): TRet<OPRFBlindEval>;\n\n /**\n * (Server-side) An optimized batch version of `blindEvaluate`. It evaluates multiple\n * blinded elements and produces a single, constant-size proof for the entire batch,\n * amortizing the cost of proof generation.\n * @param secretKey - The server's private key.\n * @param publicKey - The server's public key.\n * @param blinded - An array of blinded group elements from one or more clients.\n * @param rng - An optional cryptographically secure random number generator for the proof.\n * @returns An array of evaluated elements and a single proof for the batch.\n */\n blindEvaluateBatch(\n secretKey: TArg<ScalarBytes>,\n publicKey: TArg<PointBytes>,\n blinded: TArg<PointBytes[]>,\n rng?: RNG\n ): TRet<OPRFBlindEvalBatch>;\n\n /**\n * (Client-side) The final step. The client verifies the server's proof, and if valid,\n * unblinds the result to compute the final VOPRF output.\n * @param input - The original private input.\n * @param blind - The secret scalar from the `blind` step.\n * @param evaluated - The evaluated element from the server.\n * @param blinded - The blinded element sent to the server (needed for proof verification).\n * @param publicKey - The server's public key against which the proof is verified.\n * @param proof - The DLEQ proof from the server.\n * @returns The final VOPRF output.\n * @throws If the proof verification fails. {@link Error}\n */\n finalize(\n input: TArg<Bytes>,\n blind: TArg<ScalarBytes>,\n evaluated: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n publicKey: TArg<PointBytes>,\n proof: TArg<Bytes>\n ): TRet<Bytes>;\n\n /**\n * (Client-side) The batch-aware version of `finalize`. It verifies a single batch proof\n * against a list of corresponding inputs and outputs.\n * @param items - An array of objects, each containing the parameters for a single finalization.\n * @param publicKey - The server's public key.\n * @param proof - The single DLEQ proof for the entire batch.\n * @returns An array of final VOPRF outputs, one for each item in the input.\n * @throws If the proof verification fails. {@link Error}\n */\n finalizeBatch(\n items: TArg<OPRFFinalizeItem[]>,\n publicKey: TArg<PointBytes>,\n proof: TArg<Bytes>\n ): TRet<Bytes[]>;\n };\n\n /**\n * A factory for the Partially Oblivious Pseudorandom Function (POPRF) mode (mode 0x02).\n * This mode extends VOPRF to include a public `info` parameter, known to both client and\n * server, which is cryptographically bound to the final output.\n * This is useful for domain separation at the application level.\n * @param info - A public byte string to be mixed into the computation.\n * @returns An object with the POPRF protocol functions.\n */\n readonly poprf: (info: TArg<Bytes>) => {\n /** (Server-side) Generates a key pair for the POPRF mode. */\n generateKeyPair(): TRet<OPRFKeys>;\n /** (Server-side) Deterministically derives a key pair for the POPRF mode. */\n deriveKeyPair(seed: TArg<Bytes>, keyInfo: TArg<Bytes>): TRet<OPRFKeys>;\n\n /**\n * (Client-side) Blinds the client's private input and computes the \"tweaked key\".\n * The tweaked key is a public value derived from the server's public key and the public `info`.\n * @param input - The client's private input.\n * @param publicKey - The server's public key.\n * @param rng - An optional cryptographically secure random number generator.\n * @returns The `blind`, `blinded` element, and the `tweakedKey`\n * the client uses for verification.\n */\n blind(input: TArg<Bytes>, publicKey: TArg<PointBytes>, rng?: RNG): TRet<OPRFBlindTweaked>;\n\n /**\n * (Server-side) Evaluates the blinded element using a key derived from\n * its secret key and the public `info`.\n * It generates a DLEQ proof against the tweaked key.\n * @param secretKey - The server's private key.\n * @param blinded - The blinded element from the client.\n * @param rng - An optional RNG for the proof.\n * @returns The evaluated element and a proof of correct computation.\n */\n blindEvaluate(\n secretKey: TArg<ScalarBytes>,\n blinded: TArg<PointBytes>,\n rng?: RNG\n ): TRet<OPRFBlindEval>;\n\n /**\n * (Server-side) A batch-aware version of `blindEvaluate` for the POPRF mode.\n * @param secretKey - The server's private key.\n * @param blinded - An array of blinded elements.\n * @param rng - An optional RNG for the proof.\n * @returns An array of evaluated elements and a single proof for the batch.\n */\n blindEvaluateBatch(\n secretKey: TArg<ScalarBytes>,\n blinded: TArg<PointBytes[]>,\n rng: RNG\n ): TRet<OPRFBlindEvalBatch>;\n\n /**\n * (Client-side) A batch-aware version of `finalize` for the POPRF mode.\n * It verifies the proof against the tweaked key.\n * @param items - An array containing the parameters for each finalization.\n * @param proof - The single DLEQ proof for the batch.\n * @param tweakedKey - The tweaked key corresponding to the proof.\n * All items must share the same `info` and `publicKey`.\n * @returns An array of final POPRF outputs.\n * @throws If proof verification fails. {@link Error}\n */\n finalizeBatch(\n items: TArg<OPRFFinalizeItem[]>,\n proof: TArg<Bytes>,\n tweakedKey: TArg<PointBytes>\n ): TRet<Bytes[]>;\n\n /**\n * (Client-side) Finalizes the POPRF protocol. It verifies the server's proof against the\n * `tweakedKey` computed in the `blind` step. The final output is bound to the public `info`.\n * @param input - The original private input.\n * @param blind - The secret scalar.\n * @param evaluated - The evaluated element from the server.\n * @param blinded - The blinded element sent to the server.\n * @param proof - The DLEQ proof from the server.\n * @param tweakedKey - The public tweaked key computed by the client during the `blind` step.\n * @returns The final POPRF output.\n * @throws If proof verification fails. {@link Error}\n */\n finalize(\n input: TArg<Bytes>,\n blind: TArg<ScalarBytes>,\n evaluated: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n proof: TArg<Bytes>,\n tweakedKey: TArg<PointBytes>\n ): TRet<Bytes>;\n\n /**\n * A non-interactive evaluation function for an entity that knows all inputs.\n * Computes the final POPRF output directly. Useful for testing or specific applications\n * where the server needs to compute the output for a known input.\n * @param secretKey - The server's private key.\n * @param input - The client's private input.\n * @returns The final POPRF output.\n */\n evaluate(secretKey: TArg<ScalarBytes>, input: TArg<Bytes>): TRet<Bytes>;\n };\n};\n\n// welcome to generic hell\n/**\n * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}.\n * @returns OPRF helper namespace.\n * @example\n * Instantiate an OPRF suite from curve-specific hashing hooks.\n *\n * ```ts\n * import { createOPRF } from '@noble/curves/abstract/oprf.js';\n * import { p256, p256_hasher } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const oprf = createOPRF({\n * name: 'P256-SHA256',\n * Point: p256.Point,\n * hash: sha256,\n * hashToGroup: p256_hasher.hashToCurve,\n * hashToScalar: p256_hasher.hashToScalar,\n * });\n * const keys = oprf.oprf.generateKeyPair();\n * ```\n */\nexport function createOPRF<P extends CurvePoint<any, P>>(opts: OPRFOpts<P>): TRet<OPRF> {\n validateObject(opts, {\n name: 'string',\n hash: 'function',\n hashToScalar: 'function',\n hashToGroup: 'function',\n });\n // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that\n // OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness.\n validatePointCons(opts.Point);\n const { name, Point, hash } = opts;\n const { Fn } = Point;\n\n const hashToGroup = (msg: TArg<Uint8Array>, ctx: TArg<Uint8Array>) =>\n opts.hashToGroup(msg, {\n DST: concatBytes(asciiToBytes('HashToGroup-'), ctx),\n }) as P;\n const hashToScalarPrefixed = (msg: TArg<Uint8Array>, ctx: TArg<Uint8Array>) =>\n opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) });\n const randomScalar = (rng: RNG = randomBytes) => {\n // RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys\n // both rely on keeping this helper in the `1..n-1` range.\n const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE);\n // We cannot use Fn.fromBytes here, because field\n // can have different number of bytes (like ed448)\n return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t);\n };\n\n const msm = (points: P[], scalars: bigint[]) => pippenger(Point, points, scalars);\n\n const getCtx = (mode: number) =>\n concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name));\n const ctxOPRF = getCtx(0x00);\n const ctxVOPRF = getCtx(0x01);\n const ctxPOPRF = getCtx(0x02);\n\n function encode(...args: TArg<(Uint8Array | number | string)[]>): TRet<Bytes> {\n const res = [];\n for (const a of args) {\n if (typeof a === 'number') res.push(numberToBytesBE(a, 2));\n else if (typeof a === 'string') res.push(asciiToBytes(a));\n else {\n abytes(a);\n res.push(numberToBytesBE(a.length, 2), a);\n }\n }\n // No wipe here, since will modify actual bytes\n return concatBytes(...res) as TRet<Bytes>;\n }\n const inputBytes = (title: string, bytes: TArg<Uint8Array>) => {\n abytes(bytes, undefined, title);\n // RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are\n // length-prefixed with two bytes before use throughout the protocol.\n if (bytes.length > 0xffff)\n throw new Error(\n `\"${title}\" expected Uint8Array of length <= 65535, got length=${bytes.length}`\n );\n return bytes;\n };\n const hashInput = (...bytes: TArg<Uint8Array[]>): TRet<Bytes> =>\n hash(encode(...bytes, 'Finalize')) as TRet<Bytes>;\n\n function getTranscripts(B: P, C: P[], D: P[], ctx: TArg<Bytes>) {\n const Bm = B.toBytes();\n const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx)));\n const res: bigint[] = [];\n for (let i = 0; i < C.length; i++) {\n const Ci = C[i].toBytes();\n const Di = D[i].toBytes();\n const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx);\n res.push(di);\n }\n return res;\n }\n\n function computeComposites(B: P, C: P[], D: P[], ctx: TArg<Bytes>) {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n const Z = msm(D, T);\n return { M, Z };\n }\n\n function computeCompositesFast(\n k: bigint,\n B: P,\n C: P[],\n D: P[],\n ctx: TArg<Bytes>\n ): { M: P; Z: P } {\n const T = getTranscripts(B, C, D, ctx);\n const M = msm(C, T);\n // RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(),\n // then uses the server shortcut Z = k * M instead of a second MSM over D.\n const Z = M.multiply(k);\n return { M, Z };\n }\n\n function challengeTranscript(B: P, M: P, Z: P, t2: P, t3: P, ctx: TArg<Bytes>) {\n const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes());\n return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx);\n }\n\n function generateProof(ctx: TArg<Bytes>, k: bigint, B: P, C: P[], D: P[], rng: RNG): TRet<Bytes> {\n const { M, Z } = computeCompositesFast(k, B, C, D, ctx);\n const r = randomScalar(rng);\n const t2 = Point.BASE.multiply(r);\n const t3 = M.multiply(r);\n const c = challengeTranscript(B, M, Z, t2, t3, ctx);\n const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k\n return concatBytes(...[c, s].map((i) => Fn.toBytes(i))) as TRet<Bytes>;\n }\n\n function verifyProof(ctx: TArg<Bytes>, B: P, C: P[], D: P[], proof: TArg<Bytes>) {\n abytes(proof, 2 * Fn.BYTES);\n const { M, Z } = computeComposites(B, C, D, ctx);\n const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) =>\n Fn.fromBytes(f)\n );\n const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B\n const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z\n const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx);\n if (!Fn.eql(c, expectedC)) throw new Error('proof verification failed');\n }\n\n function generateKeyPair(): TRet<OPRFKeys> {\n const skS = randomScalar();\n const pkS = Point.BASE.multiply(skS);\n return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() } as TRet<OPRFKeys>;\n }\n\n function deriveKeyPair(ctx: TArg<Bytes>, seed: TArg<Bytes>, info: TArg<Bytes>): TRet<OPRFKeys> {\n // RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already\n // documents a 32-byte seed instead of generic input keying material.\n abytes(seed, 32, 'seed');\n info = inputBytes('keyInfo', info);\n const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx);\n const msg = concatBytes(seed, encode(info), Uint8Array.of(0));\n for (let counter = 0; counter <= 255; counter++) {\n msg[msg.length - 1] = counter;\n const skS = opts.hashToScalar(msg, { DST: dst });\n if (Fn.is0(skS)) continue; // should not happen\n return {\n secretKey: Fn.toBytes(skS),\n publicKey: Point.BASE.multiply(skS).toBytes(),\n } as TRet<OPRFKeys>;\n }\n throw new Error('Cannot derive key');\n }\n const wirePoint = (label: string, bytes: TArg<Uint8Array>) => {\n const point = Point.fromBytes(bytes);\n // RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire\n // after deserialization, even if the suite decoder itself accepts the identity encoding.\n if (point.equals(Point.ZERO)) throw new Error(label + ' point at infinity');\n return point;\n };\n function blind(\n ctx: TArg<Bytes>,\n input: TArg<Uint8Array>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlind> {\n input = inputBytes('input', input);\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity');\n const blinded = inputPoint.multiply(blind);\n return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() } as TRet<OPRFBlind>;\n }\n function evaluate(\n ctx: TArg<Bytes>,\n secretKey: TArg<ScalarBytes>,\n input: TArg<Bytes>\n ): TRet<Bytes> {\n input = inputBytes('input', input);\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctx);\n if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity');\n const unblinded = inputPoint.multiply(skS).toBytes();\n return hashInput(input, unblinded);\n }\n const oprf = Object.freeze({\n generateKeyPair,\n deriveKeyPair: (seed: TArg<Bytes>, keyInfo: TArg<Bytes>) =>\n deriveKeyPair(ctxOPRF, seed, keyInfo),\n blind: (input: TArg<Bytes>, rng: RNG = randomBytes) => blind(ctxOPRF, input, rng),\n blindEvaluate(secretKey: TArg<ScalarBytes>, blindedPoint: TArg<PointBytes>): TRet<PointBytes> {\n const skS = Fn.fromBytes(secretKey);\n const elm = wirePoint('blinded', blindedPoint);\n return elm.multiply(skS).toBytes() as TRet<PointBytes>;\n },\n finalize(\n input: TArg<Bytes>,\n blindBytes: TArg<ScalarBytes>,\n evaluatedBytes: TArg<PointBytes>\n ): TRet<Bytes> {\n input = inputBytes('input', input);\n const blind = Fn.fromBytes(blindBytes);\n const evalPoint = wirePoint('evaluated', evaluatedBytes);\n const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes();\n return hashInput(input, unblinded);\n },\n evaluate: (secretKey: TArg<ScalarBytes>, input: TArg<Bytes>) =>\n evaluate(ctxOPRF, secretKey, input),\n });\n\n const voprf = Object.freeze({\n generateKeyPair,\n deriveKeyPair: (seed: TArg<Bytes>, keyInfo: TArg<Bytes>) =>\n deriveKeyPair(ctxVOPRF, seed, keyInfo),\n blind: (input: TArg<Bytes>, rng: RNG = randomBytes) => blind(ctxVOPRF, input, rng),\n blindEvaluateBatch(\n secretKey: TArg<ScalarBytes>,\n publicKey: TArg<PointBytes>,\n blinded: TArg<PointBytes[]>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlindEvalBatch> {\n if (!Array.isArray(blinded)) throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const pkS = wirePoint('public key', publicKey);\n const blindedPoints = blinded.map((i) => wirePoint('blinded', i));\n const evaluated = blindedPoints.map((i) => i.multiply(skS));\n const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng);\n return { evaluated: evaluated.map((i) => i.toBytes()), proof } as TRet<OPRFBlindEvalBatch>;\n },\n blindEvaluate(\n secretKey: TArg<ScalarBytes>,\n publicKey: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlindEval> {\n const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof } as TRet<OPRFBlindEval>;\n },\n finalizeBatch(\n items: TArg<OPRFFinalizeItem[]>,\n publicKey: TArg<PointBytes>,\n proof: TArg<Bytes>\n ): TRet<Bytes[]> {\n if (!Array.isArray(items)) throw new Error('expected array');\n const pkS = wirePoint('public key', publicKey);\n const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded));\n const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));\n verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof);\n return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated)) as TRet<Bytes[]>;\n },\n finalize(\n input: TArg<Bytes>,\n blind: TArg<ScalarBytes>,\n evaluated: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n publicKey: TArg<PointBytes>,\n proof: TArg<Bytes>\n ): TRet<Bytes> {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0];\n },\n evaluate: (secretKey: TArg<ScalarBytes>, input: TArg<Bytes>) =>\n evaluate(ctxVOPRF, secretKey, input),\n });\n // NOTE: info is domain separation\n const poprf = (info: TArg<Bytes>) => {\n info = inputBytes('info', info);\n const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF);\n const T = Point.BASE.multiply(m);\n return Object.freeze({\n generateKeyPair,\n deriveKeyPair: (seed: TArg<Bytes>, keyInfo: TArg<Bytes>) =>\n deriveKeyPair(ctxPOPRF, seed, keyInfo),\n blind(\n input: TArg<Bytes>,\n publicKey: TArg<PointBytes>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlindTweaked> {\n input = inputBytes('input', input);\n const pkS = wirePoint('public key', publicKey);\n const tweakedKey = T.add(pkS);\n if (tweakedKey.equals(Point.ZERO)) throw new Error('tweakedKey point at infinity');\n const blind = randomScalar(rng);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity');\n const blindedPoint = inputPoint.multiply(blind);\n return {\n blind: Fn.toBytes(blind),\n blinded: blindedPoint.toBytes(),\n tweakedKey: tweakedKey.toBytes(),\n } as TRet<OPRFBlindTweaked>;\n },\n blindEvaluateBatch(\n secretKey: TArg<ScalarBytes>,\n blinded: TArg<PointBytes[]>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlindEvalBatch> {\n if (!Array.isArray(blinded)) throw new Error('expected array');\n const skS = Fn.fromBytes(secretKey);\n const t = Fn.add(skS, m);\n // \"Hence, this error can be a signal for the server to replace its\n // private key\". We throw inside; this should be impossible.\n const invT = Fn.inv(t);\n const blindedPoints = blinded.map((i) => wirePoint('blinded', i));\n const evalPoints = blindedPoints.map((i) => i.multiply(invT));\n const tweakedKey = Point.BASE.multiply(t);\n const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng);\n return { evaluated: evalPoints.map((i) => i.toBytes()), proof } as TRet<OPRFBlindEvalBatch>;\n },\n blindEvaluate(\n secretKey: TArg<ScalarBytes>,\n blinded: TArg<PointBytes>,\n rng: RNG = randomBytes\n ): TRet<OPRFBlindEval> {\n const res = this.blindEvaluateBatch(secretKey, [blinded], rng);\n return { evaluated: res.evaluated[0], proof: res.proof } as TRet<OPRFBlindEval>;\n },\n finalizeBatch(\n items: TArg<OPRFFinalizeItem[]>,\n proof: TArg<Bytes>,\n tweakedKey: TArg<PointBytes>\n ): TRet<Bytes[]> {\n if (!Array.isArray(items)) throw new Error('expected array');\n const inputs = items.map((i) => inputBytes('input', i.input));\n const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated));\n verifyProof(\n ctxPOPRF,\n wirePoint('tweakedKey', tweakedKey),\n evalPoints,\n items.map((i) => wirePoint('blinded', i.blinded)),\n proof\n );\n return items.map((i, j) => {\n const blind = Fn.fromBytes(i.blind);\n const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes();\n return hashInput(inputs[j], info, point);\n }) as TRet<Bytes[]>;\n },\n finalize(\n input: TArg<Bytes>,\n blind: TArg<ScalarBytes>,\n evaluated: TArg<PointBytes>,\n blinded: TArg<PointBytes>,\n proof: TArg<Bytes>,\n tweakedKey: TArg<PointBytes>\n ): TRet<Bytes> {\n return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0];\n },\n evaluate(secretKey: TArg<ScalarBytes>, input: TArg<Bytes>): TRet<Bytes> {\n input = inputBytes('input', input);\n const skS = Fn.fromBytes(secretKey);\n const inputPoint = hashToGroup(input, ctxPOPRF);\n if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity');\n const t = Fn.add(skS, m);\n const invT = Fn.inv(t);\n const unblinded = inputPoint.multiply(invT).toBytes();\n return hashInput(input, info, unblinded);\n },\n });\n };\n const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) };\n return Object.freeze(res) as TRet<OPRF>;\n}\n","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport { type AffinePoint } from './abstract/curve.ts';\nimport {\n eddsa,\n edwards,\n PrimeEdwardsPoint,\n type EdDSA,\n type EdDSAOpts,\n type EdwardsOpts,\n type EdwardsPoint,\n type EdwardsPointCons,\n} from './abstract/edwards.ts';\nimport { createFROST, type FROST } from './abstract/frost.ts';\nimport {\n _DST_scalar,\n createHasher,\n expand_message_xmd,\n type H2CDSTOpts,\n type H2CHasher,\n type H2CHasherBase,\n} from './abstract/hash-to-curve.ts';\nimport {\n FpInvertBatch,\n FpSqrtEven,\n isNegativeLE,\n mod,\n pow2,\n type IField,\n} from './abstract/modular.ts';\nimport { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts';\nimport { createOPRF, type OPRF } from './abstract/oprf.ts';\nimport { asciiToBytes, bytesToNumberLE, equalBytes, type TArg, type TRet } from './utils.ts';\n\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'\n);\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes as TRet<Uint8Array>;\n}\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(\n data: TArg<Uint8Array>,\n ctx: TArg<Uint8Array>,\n phflag: boolean\n): TRet<Uint8Array> {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n asciiToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n ) as TRet<Uint8Array>;\n}\n\nfunction ed(opts: TArg<EdDSAOpts>) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(\n ed25519_Point,\n sha512,\n Object.assign({ adjustScalarBytes, zip215: true }, opts as EdDSAOpts)\n );\n}\n\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519: EdDSA = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree()) throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n }))();\n\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519: TRet<MontgomeryECDH> = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x: bigint): bigint => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u: bigint): {\n xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint\n} {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher: H2CHasher<EdwardsPointCons> = /* @__PURE__ */ (() =>\n createHasher(\n ed25519_Point,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\n\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = /* @__PURE__ */ BigInt(\n '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'\n);\n// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes: TArg<Uint8Array>) =>\n Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0: bigint): EdwardsPoint {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO: _RistrettoPoint =\n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp: IField<bigint> =\n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn: IField<bigint> =\n /* @__PURE__ */ (() => Fn)();\n\n constructor(ep: EdwardsPoint) {\n super(ep);\n }\n\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap: AffinePoint<bigint>): _RistrettoPoint {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n\n protected assertSame(other: _RistrettoPoint): void {\n if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected');\n }\n\n protected init(ep: EdwardsPoint): _RistrettoPoint {\n return new _RistrettoPoint(ep);\n }\n\n static fromBytes(bytes: TArg<Uint8Array>): _RistrettoPoint {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: string): _RistrettoPoint {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes(): TRet<Uint8Array> {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n: bigint) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D: bigint; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return Fp.toBytes(s) as TRet<Uint8Array>; // 11\n }\n\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other: _RistrettoPoint): boolean {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n: bigint) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n is0(): boolean {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\nObject.freeze(_RistrettoPoint.BASE);\nObject.freeze(_RistrettoPoint.ZERO);\nObject.freeze(_RistrettoPoint.prototype);\nObject.freeze(_RistrettoPoint);\n\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255: {\n Point: typeof _RistrettoPoint;\n} = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint });\n\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * §4.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher: H2CHasherBase<typeof _RistrettoPoint> = Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): _RistrettoPoint {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve!(xmd);\n },\n hashToScalar(msg: TArg<Uint8Array>, options: TArg<H2CDSTOpts> = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes: TArg<Uint8Array>): _RistrettoPoint {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf: TRet<OPRF> = /* @__PURE__ */ (() =>\n createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n }))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST: TRet<FROST> = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n }))();\n\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP: readonly string[] = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\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,M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E,KAAK,YAAW,GAAE;AAClF,UAAM,MAAM,mBAAmB,KAAK,QAAQ,KAAK,IAAI,MAAM;AAC3D,WAAO,GAAG,OAAO,gBAAgB,GAAG,CAAC;EACvC;;;;;;;;;;EAUA,cAAc,OAAuB;AAEnC,WAAO,OAAO,EAAE;AAChB,UAAM,KAAK,mBAAmB,MAAM,SAAS,GAAG,EAAE,CAAC;AACnD,UAAM,KAAK,0BAA0B,EAAE;AACvC,UAAM,KAAK,mBAAmB,MAAM,SAAS,IAAI,EAAE,CAAC;AACpD,UAAM,KAAK,0BAA0B,EAAE;AACvC,WAAO,IAAI,gBAAgB,GAAG,IAAI,EAAE,CAAC;EACvC;CACD;AAeM,IAAM,oBAAiD,uBAC5D,WAAW;EACT,MAAM;EACN,OAAO;EACP,MAAM;EACN,aAAa,oBAAoB;EACjC,cAAc,oBAAoB;CACnC,GAAE;AAaE,IAAM,qBAAmD,uBAC9D,YAAY;EACV,MAAM;EACN,OAAO;EACP,eAAe,CAAC,MAAK;AAEnB,MAAE,eAAc;EAClB;EACA,MAAM;CACP,GAAE;AAgBE,IAAM,2BAA8D,uBAAO,OAAO;EACvF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;","names":["isLE","abytes","anumber","bytesToHex","concatBytes","hexToBytes","isBytes","randomBytes","abytes","concatBytes","_0n","_1n","_0n","_1n","Fp","Fp","_1n","anumber","_0n","_1n","abytes","isLE","Fp","_1n","isLE","abytes","_0n","_1n","wbits","isLE","_0n","Fp","Fn","_0n","_1n","_2n","_8n","Fp","Fn","uvRatio","abytes","hexToBytes","p","bytesToHex","randomBytes","adjustScalarBytes","hash","concatBytes","isBytes","roots","isBytes","abytes","concatBytes","createHasher","isBytes","Fn","opts","concatBytes","randomBytes","bytesToHex","hexToBytes","_0n","_1n","_2n","adjustScalarBytes","randomBytes","abytes","Fn","concatBytes","randomBytes","res","abytes","blind","_0n","_1n","_2n","_3n","_5n","_8n","createHasher","mod"]}
|