@obolnetwork/obol-sdk 2.12.2 → 2.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/browser/src/index.js +72 -13
  2. package/dist/browser/src/index.js.map +1 -1
  3. package/dist/cjs/src/index.js +73 -13
  4. package/dist/cjs/src/index.js.map +1 -1
  5. package/dist/cjs/src/verification/clusterLockValidationWorker.js +39 -8
  6. package/dist/cjs/src/verification/clusterLockValidationWorker.js.map +1 -1
  7. package/dist/cjs/src/verification/parallelPool.js +27 -7
  8. package/dist/cjs/src/verification/parallelPool.js.map +1 -1
  9. package/dist/esm/src/{chunk-YSXFCSVK.js → chunk-BJWBUH75.js} +39 -8
  10. package/dist/esm/src/chunk-BJWBUH75.js.map +1 -0
  11. package/dist/esm/src/{chunk-T74RX3N2.js → chunk-L2GZF5CQ.js} +8 -4
  12. package/dist/esm/src/chunk-L2GZF5CQ.js.map +1 -0
  13. package/dist/esm/src/index.js +33 -6
  14. package/dist/esm/src/index.js.map +1 -1
  15. package/dist/esm/src/verification/clusterLockValidationWorker.js +9 -3
  16. package/dist/esm/src/verification/clusterLockValidationWorker.js.map +1 -1
  17. package/dist/esm/src/verification/parallelPool.js +1 -1
  18. package/dist/types/src/errors.d.ts +17 -7
  19. package/dist/types/src/index.d.ts +1 -1
  20. package/dist/types/src/services.d.ts +6 -3
  21. package/dist/types/src/verification/parallelPool.d.ts +4 -0
  22. package/dist/types/src/verification/validationConcurrency.d.ts +11 -0
  23. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  24. package/package.json +2 -2
  25. package/dist/esm/src/chunk-T74RX3N2.js.map +0 -1
  26. package/dist/esm/src/chunk-YSXFCSVK.js.map +0 -1
  27. package/dist/types/test/client/ajv.spec.d.ts +0 -1
  28. package/dist/types/test/client/baseUrl.spec.d.ts +0 -1
  29. package/dist/types/test/client/methods.spec.d.ts +0 -18
  30. package/dist/types/test/eoa/eoa.spec.d.ts +0 -1
  31. package/dist/types/test/exit/ethUtils.spec.d.ts +0 -1
  32. package/dist/types/test/exit/exit.spec.d.ts +0 -1
  33. package/dist/types/test/exit/verificationHelpers.spec.d.ts +0 -1
  34. package/dist/types/test/fixtures.d.ts +0 -359
  35. package/dist/types/test/incentives/incentives.spec.d.ts +0 -1
  36. package/dist/types/test/splits/splits.spec.d.ts +0 -1
  37. package/dist/types/test/verification/parallelPool.spec.d.ts +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/verification/parallelPool.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../../../../node_modules/@noble/curves/src/utils.ts","../../../../node_modules/@noble/curves/src/abstract/modular.ts","../../../../node_modules/@noble/curves/src/abstract/curve.ts","../../../../node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../../node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../../node_modules/@noble/curves/src/abstract/bls.ts","../../../../node_modules/@noble/curves/src/abstract/tower.ts","../../../../node_modules/@noble/curves/src/bls12-381.ts","../../../../src/blsUtils.ts","../../../../src/errors.ts"],"sourcesContent":["// Parallel BLS verification via Node worker_threads.\n//\n// IMPORTANT: only the CJS build actually runs in parallel. ESM Node and\n// browser bundles transparently fall back to sync. See the matrix in\n// PARALLEL_VALIDATION_PLAN.md. The main consumer flow (charon DKG ->\n// obol-api NestJS handler -> SDK CJS) is CJS, so it gets the speedup.\n//\n// Strategy:\n// - Look up the worker file via __dirname (CJS only). If undefined or the\n// file isn't where we expect (ESM, browser, source-mode tsx/jest), return\n// undefined and fall back to sync.\n// - Below MIN_PARALLEL_* thresholds, sync wins (worker spin-up dominates).\n// - Spawn one worker per chunk, await all, collapse to a single boolean.\n\nimport { fromHexString } from '@chainsafe/ssz';\nimport {\n blsAggregatePublicKeys,\n blsAggregateSignatures,\n blsRecoverDistributedPubkeyFromShares,\n blsVerifyAggregate,\n blsVerifyExtraShares,\n blsVerifyMultiple,\n blsVerifyWithAggregatedPubkey,\n} from '../blsUtils.js';\n// Type-only imports — erased at compile time, so they don't pull node:*\n// modules into the browser bundle.\nimport type * as WTNs from 'node:worker_threads';\nimport type * as OsNs from 'node:os';\nimport type * as PathNs from 'node:path';\nimport type * as FsNs from 'node:fs';\nimport { ClusterLockValidationTimeoutError } from '../errors.js';\nimport type { BlsSignatureCheck, ClusterLock, SafeRpcUrl } from '../types.js';\nimport type { AggregatePubkeysInput, WorkerInput } from './lockWorker.js';\n\nconst MIN_PARALLEL_VALIDATORS = 50;\nconst MIN_PARALLEL_BATCH_PAIRS = 100;\nconst MAX_WORKERS = 8;\nconst MIN_VALIDATORS_PER_WORKER = 25;\nconst MIN_PAIRS_PER_WORKER = 50;\nconst MIN_PARALLEL_AGGREGATE_KEYS = 400;\nconst MIN_KEYS_PER_WORKER_AGG = 100;\n// Hard ceiling so a stuck worker can't leak past obol-api's HTTP timeout.\n// Biggest legitimate batch (~1000 pairs) finishes in ~3s on the bench; 60s\n// is conservative enough to never false-trip on real input.\nconst MIN_VALIDATORS_FOR_VALIDATION_WORKER = 50;\nconst VALIDATION_WORKER_TIMEOUT_MS = 120_000;\nconst WORKER_TIMEOUT_MS = 60_000;\n// Cap simultaneous workers (memory). Scales up for large jobs on multi-core hosts.\nconst MAX_CONCURRENT_WORKERS_CAP = 8;\n\nfunction maxConcurrentWorkers(numWorkers: number): number {\n return Math.min(numWorkers, MAX_CONCURRENT_WORKERS_CAP);\n}\n\ntype WorkerThreads = typeof WTNs;\ntype NodeOs = typeof OsNs;\n\nlet workerThreadsCache: WorkerThreads | null | undefined;\nlet osCache: NodeOs | null | undefined;\n// Tri-state per worker file: undefined = uncached, null = unavailable, string = path.\nconst workerPathByFile = new Map<string, string | null | undefined>();\n\nfunction loadWorkerThreads(): WorkerThreads | null {\n if (workerThreadsCache !== undefined) return workerThreadsCache;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n workerThreadsCache = require('node:worker_threads') as WorkerThreads;\n } catch {\n workerThreadsCache = null;\n }\n return workerThreadsCache;\n}\n\nfunction loadOs(): NodeOs | null {\n if (osCache !== undefined) return osCache;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n osCache = require('node:os') as NodeOs;\n } catch {\n osCache = null;\n }\n return osCache;\n}\n\nfunction getWorkerPath(filename: string): string | null {\n const cached = workerPathByFile.get(filename);\n if (cached !== undefined) return cached;\n if (typeof __dirname === 'undefined') {\n workerPathByFile.set(filename, null);\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const path = require('node:path') as typeof PathNs;\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const fs = require('node:fs') as typeof FsNs;\n // Bundled index.js: __dirname is dist/cjs/src; workers live in verification/.\n // Standalone parallelPool.js entry: __dirname is already verification/.\n const candidates = [\n path.join(__dirname, filename),\n path.join(__dirname, 'verification', filename),\n ];\n try {\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n workerPathByFile.set(filename, candidate);\n return candidate;\n }\n }\n } catch {\n // fall through\n }\n workerPathByFile.set(filename, null);\n return null;\n}\n\nasync function mapWithConcurrency<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let next = 0;\n const runners = Array.from(\n { length: Math.min(concurrency, items.length) },\n async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i], i);\n }\n },\n );\n await Promise.all(runners);\n return results;\n}\n\nfunction chunkArrays<T>(arr: T[], n: number): T[][] {\n const size = Math.ceil(arr.length / n);\n const out: T[][] = [];\n for (let i = 0; i < arr.length; i += size) {\n out.push(arr.slice(i, i + size));\n }\n return out;\n}\n\nfunction verifySharesSync(\n shares: string[][],\n distributedKeys: string[],\n threshold: number,\n): boolean {\n for (let i = 0; i < shares.length; i++) {\n const sharesBytes = shares[i].map(s => fromHexString(s));\n const dkBytes = fromHexString(distributedKeys[i]);\n const recovered = blsRecoverDistributedPubkeyFromShares(\n sharesBytes,\n threshold,\n );\n if (!recovered) return false;\n if (recovered.length !== dkBytes.length) return false;\n for (let j = 0; j < recovered.length; j++) {\n if (recovered[j] !== dkBytes[j]) return false;\n }\n if (!blsVerifyExtraShares(sharesBytes, threshold, dkBytes)) {\n return false;\n }\n }\n return true;\n}\n\nasync function runWorkerAggregatePubkeys(\n wt: WorkerThreads,\n workerFile: string,\n data: AggregatePubkeysInput,\n): Promise<Uint8Array | null> {\n return await new Promise(resolve => {\n let settled = false;\n const worker = new wt.Worker(workerFile, { workerData: data });\n const finish = (result: Uint8Array | null): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n const timer = setTimeout(() => {\n finish(null);\n }, WORKER_TIMEOUT_MS);\n worker.once('message', (msg: unknown) => {\n finish(msg instanceof Uint8Array ? msg : null);\n });\n worker.once('error', () => {\n finish(null);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(null);\n });\n });\n}\n\nasync function runWorker(\n wt: WorkerThreads,\n workerFile: string,\n data: WorkerInput,\n): Promise<boolean> {\n return await new Promise(resolve => {\n let settled = false;\n const worker = new wt.Worker(workerFile, { workerData: data });\n const finish = (result: boolean): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n const timer = setTimeout(() => {\n finish(false);\n }, WORKER_TIMEOUT_MS);\n worker.once('message', (msg: unknown) => {\n finish(msg === true);\n });\n worker.once('error', () => {\n finish(false);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(false);\n });\n });\n}\n\nfunction poolSize(\n itemCount: number,\n minPerWorker: number,\n): {\n numWorkers: number;\n wt: WorkerThreads | null;\n workerFile: string | null;\n} {\n const wt = loadWorkerThreads();\n const os = loadOs();\n const workerFile = getWorkerPath('lockWorker.js');\n const numCpus = os ? Math.max(1, os.cpus().length) : 1;\n const numWorkers = Math.min(\n MAX_WORKERS,\n Math.max(1, Math.floor(itemCount / minPerWorker)),\n numCpus,\n );\n return { numWorkers, wt, workerFile };\n}\n\nasync function runWorkerChunks(\n wt: WorkerThreads,\n workerFile: string,\n chunks: WorkerInput[],\n): Promise<boolean> {\n const results = await mapWithConcurrency(\n chunks,\n maxConcurrentWorkers(chunks.length),\n async data => await runWorker(wt, workerFile, data),\n );\n return results.every(Boolean);\n}\n\nexport async function verifySharesBinding(\n shares: string[][],\n distributedKeys: string[],\n threshold: number,\n): Promise<boolean> {\n if (shares.length !== distributedKeys.length) return false;\n if (shares.length === 0) return true;\n\n const { numWorkers, wt, workerFile } = poolSize(\n shares.length,\n MIN_VALIDATORS_PER_WORKER,\n );\n\n // Inline the guard so TS narrows wt/workerFile for the parallel path below\n // (avoids non-null assertions).\n if (\n wt === null ||\n workerFile === null ||\n shares.length < MIN_PARALLEL_VALIDATORS ||\n numWorkers < 2\n ) {\n return verifySharesSync(shares, distributedKeys, threshold);\n }\n\n const shareChunks = chunkArrays(shares, numWorkers);\n const keyChunks = chunkArrays(distributedKeys, numWorkers);\n\n return await runWorkerChunks(\n wt,\n workerFile,\n shareChunks.map((chunk, i) => ({\n mode: 'shareBinding',\n shares: chunk,\n distributedKeys: keyChunks[i],\n threshold,\n })),\n );\n}\n\n/** Verify deposit + builder BLS signatures collected from `depositBlsCheck` / `builderBlsCheck`. */\nexport async function verifyBlsChecksParallel(\n checks: BlsSignatureCheck[],\n): Promise<boolean> {\n if (checks.length === 0) return true;\n return await verifyBatchParallel(\n checks.map(c => c.pubkey),\n checks.map(c => c.message),\n checks.map(c => c.signature),\n );\n}\n\n// Verify a batch of (pubkey, message, individual signature) triples.\n// Sync path aggregates all sigs and runs blsVerifyMultiple once (matches the\n// previous behavior). Parallel path splits into chunks; each chunk's sigs are\n// aggregated and verified independently — same total pairing count, K× wall\n// time speedup.\nexport async function verifyBatchParallel(\n pubkeys: Uint8Array[],\n messages: Uint8Array[],\n signatures: Uint8Array[],\n): Promise<boolean> {\n if (\n pubkeys.length !== messages.length ||\n pubkeys.length !== signatures.length\n ) {\n return false;\n }\n if (pubkeys.length === 0) return true;\n\n const { numWorkers, wt, workerFile } = poolSize(\n pubkeys.length,\n MIN_PAIRS_PER_WORKER,\n );\n\n if (\n wt === null ||\n workerFile === null ||\n pubkeys.length < MIN_PARALLEL_BATCH_PAIRS ||\n numWorkers < 2\n ) {\n return blsVerifyMultiple(\n pubkeys,\n messages,\n blsAggregateSignatures(signatures),\n );\n }\n\n const pkChunks = chunkArrays(pubkeys, numWorkers);\n const msgChunks = chunkArrays(messages, numWorkers);\n const sigChunks = chunkArrays(signatures, numWorkers);\n\n return await runWorkerChunks(\n wt,\n workerFile,\n pkChunks.map((pks, i) => ({\n mode: 'verifyBatch',\n pubkeys: pks,\n messages: msgChunks[i],\n signatures: sigChunks[i],\n })),\n );\n}\n\n// Lock signature_aggregate: aggregate many operator shares (validators × operators)\n// then verify one BLS signature over lock_hash. Parallel path aggregates pubkey\n// chunks in workers, combines partial aggregates on the main thread, then verifies.\nexport async function verifyAggregateParallel(\n pubkeys: Uint8Array[],\n message: Uint8Array,\n signature: Uint8Array,\n): Promise<boolean> {\n if (pubkeys.length === 0) return false;\n\n const { numWorkers, wt, workerFile } = poolSize(\n pubkeys.length,\n MIN_KEYS_PER_WORKER_AGG,\n );\n\n if (\n wt === null ||\n workerFile === null ||\n pubkeys.length < MIN_PARALLEL_AGGREGATE_KEYS ||\n numWorkers < 2\n ) {\n return blsVerifyAggregate(pubkeys, message, signature);\n }\n\n const pkChunks = chunkArrays(pubkeys, numWorkers);\n const partials = await mapWithConcurrency(\n pkChunks,\n maxConcurrentWorkers(pkChunks.length),\n async chunk =>\n await runWorkerAggregatePubkeys(wt, workerFile, {\n mode: 'aggregatePubkeys',\n pubkeys: chunk,\n }),\n );\n if (partials.some(p => p === null)) return false;\n\n const aggregated = blsAggregatePublicKeys(partials as Uint8Array[]);\n return blsVerifyWithAggregatedPubkey(aggregated, message, signature);\n}\n\n/**\n * Large locks: run full validation off the main thread (obol-api stays responsive).\n * Returns null when workers are unavailable — caller should use sync validation.\n */\nexport async function validateClusterLockInWorker(\n lock: ClusterLock,\n safeRpcUrl?: SafeRpcUrl,\n): Promise<boolean | null> {\n const n = lock.distributed_validators?.length ?? 0;\n if (n < MIN_VALIDATORS_FOR_VALIDATION_WORKER) return null;\n\n const wt = loadWorkerThreads();\n const workerFile = getWorkerPath('clusterLockValidationWorker.js');\n if (wt === null || workerFile === null) return null;\n\n return await new Promise((resolve, reject) => {\n let settled = false;\n const worker = new wt.Worker(workerFile, {\n workerData: { lock, safeRpcUrl },\n });\n // Timeout rejects (ClusterLockValidationTimeoutError) instead of resolving\n // false: callers must distinguish **504** gateway timeout from **400** invalid\n // crypto. Do not resolve null here — full sync fallback would block Node again.\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n void worker.terminate();\n reject(\n new ClusterLockValidationTimeoutError(VALIDATION_WORKER_TIMEOUT_MS),\n );\n }, VALIDATION_WORKER_TIMEOUT_MS);\n const finish = (result: boolean | null): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n worker.once('message', (msg: unknown) => {\n finish(msg === true);\n });\n worker.once('error', () => {\n finish(null);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(null);\n });\n });\n}\n","/**\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 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = <T extends TArg<Uint8Array>>(value: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> =>\n concatBytes_(...arrays) as TRet<Uint8Array>;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet<Uint8Array> => hexToBytes_(hex) as TRet<Uint8Array>;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet<Uint8Array> =>\n randomBytes_(bytesLength) as TRet<Uint8Array>;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg<Uint8Array>): TRet<Uint8Array>;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg<Uint8Array>, message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber<T extends number | bigint>(n: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet<Uint8Array>;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet<Uint8Array> {\n return numberToBytesBE(n, len).reverse() as TRet<Uint8Array>;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet<Uint8Array> {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet<Uint8Array>;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet<Uint8Array> {\n if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet<Uint8Array>;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: TArg<Uint8Array>) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg<HmacFn>\n): TRet<(seed: Uint8Array, predicate: Pred<T>) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet<Uint8Array> => new Uint8Array(len) as TRet<Uint8Array>;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs: TArg<Uint8Array[]>) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg<Uint8Array> = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: TArg<Uint8Array>, pred: TArg<Pred<T>>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred<T>)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred<T>) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: TArg<IField<T>>, root: T, n: T): void {\n const F = Fp as IField<T>;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (<T>(Fp: TArg<IField<T>>, n: T): T => {\n const F = Fp as IField<T>;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n }) as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: TArg<IField<T>>, n: T): T {\n const F = Fp as IField<T>;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n } as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField<T> {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet<IField<T>>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T {\n const F = Fp as IField<T>;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero = false): T[] {\n const F = Fp as IField<T>;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField<T>;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1 {\n const F = Fp as IField<T>;\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean {\n const l = FpLegendre(Fp as IField<T>, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap<object, ReturnType<typeof FpSqrt>>();\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet<Readonly<FpField>> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n key: TArg<Uint8Array>,\n fieldOrder: bigint,\n isLE = false\n): TRet<Uint8Array> {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint<T> = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint<F>;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void {\n const pc = Point as unknown as CurvePointCons<any>;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper<T> = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams<T> = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: TArg<IField<T>>, isLE?: boolean): TRet<IField<T>> {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet<IField<T>>;\n } else {\n return Field(order, { isLE }) as unknown as TRet<IField<T>>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn<T> = {\n /** Base field used for curve coordinates. */\n Fp: IField<T>;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField<bigint>;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: TArg<Partial<FpFn<T>>> = {},\n FpFnLE?: boolean\n): TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn } as TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: TArg<Signer['getPublicKey']>\n): TRet<KeygenFn> {\n return function keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed) as TRet<Uint8Array>;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet<Uint8Array> };\n };\n}\n","/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash, TArg, TRet } from '../utils.ts';\nimport {\n abytes,\n asafenumber,\n asciiToBytes,\n bytesToNumberBE,\n copyBytes,\n concatBytes,\n isBytes,\n validateObject,\n} from '../utils.ts';\nimport type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\n/** ASCII domain-separation tag or raw bytes. */\nexport type AsciiOrBytes = string | Uint8Array;\ntype H2CDefaults = {\n DST: AsciiOrBytes;\n expand: 'xmd' | 'xof';\n hash: CHash;\n p: bigint;\n m: number;\n k: number;\n encodeDST?: AsciiOrBytes;\n};\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n /** Domain separation tag. */\n DST: AsciiOrBytes;\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n /** Base-field characteristic. */\n p: bigint;\n /** Extension degree (`1` for prime fields). */\n m: number;\n /** Target security level in bits. */\n k: number;\n};\n/** Hash-only subset of RFC 9380 options used by per-call overrides. */\nexport type H2CHashOpts = {\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n};\n/**\n * Map one hash-to-field output tuple onto affine curve coordinates.\n * Implementations receive the validated scalar tuple by reference for performance and MUST treat it\n * as read-only. Callers that need scratch space should copy before mutating.\n * @param scalar - Field-element tuple produced by `hash_to_field`.\n * @returns Affine point before subgroup clearing.\n */\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\n/** Per-call override for the domain-separation tag. */\nexport type H2CDSTOpts = {\n /** Domain-separation tag override. */\n DST: AsciiOrBytes;\n};\n/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */\nexport type H2CHasherBase<PC extends PC_ANY> = {\n /**\n * Hash arbitrary bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after hash-to-curve.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /**\n * Hash arbitrary bytes to one scalar.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Scalar reduced into the target field.\n */\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;\n /**\n * Derive one curve point from non-uniform bytes without the random-oracle\n * guarantees of `hashToCurve`.\n * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve\n * path instead of the random-oracle construction.\n */\n deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Point constructor for the target curve. */\n Point: PC;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {\n /**\n * Encode non-uniform bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after encode-to-curve.\n */\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Deterministic map from `hash_to_field` tuples into affine coordinates. */\n mapToCurve: MapToCurve<PC_F<PC>>;\n /** Default RFC 9380 options captured by this hasher bundle. */\n defaults: H2CDefaults;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value: number, length: number): TRet<Uint8Array> {\n asafenumber(value);\n asafenumber(length);\n // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length);\n if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res) as TRet<Uint8Array>;\n}\n\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a: TArg<Uint8Array>, b: TArg<Uint8Array>): TRet<Uint8Array> {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr as TRet<Uint8Array>;\n}\n\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST: TArg<AsciiOrBytes>): TRet<Uint8Array> {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n // RFC 9380 §3.1 requirement 2: tags \"MUST have nonzero length\".\n if (dst.length === 0) throw new Error('DST must be non-empty');\n return dst as TRet<Uint8Array>;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n // by reaching `I2OSP(256, 1)`.\n for (let i = 1; i < ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n * new TextEncoder().encode('hello noble'),\n * 'DST',\n * 32,\n * 128,\n * shake256\n * );\n * ```\n */\nexport function expand_message_xof(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n k: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // RFC 9380 §5.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n * DST: 'DST',\n * p: 17n,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(\n msg: TArg<Uint8Array>,\n count: number,\n options: TArg<H2COpts>\n): bigint[][] {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires\n // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n if (count < 1) throw new Error('hash_to_field: expected count >= 1');\n if (m < 1) throw new Error('hash_to_field: expected m >= 1');\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\ntype XY<T> = (x: T, y: T) => { x: T; y: T };\ntype XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must\n // return the identity on E.\n // Shipped Weierstrass consumers encode that affine identity as all-zero\n // coordinates, so `passZero=true` intentionally collapses zero\n // denominators to `{ x: 0, y: 0 }`.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-' as const;\n\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n * the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n * DST: 'P256_XMD:SHA-256_SSWU_RO_',\n * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n * p: p256.Point.Fp.ORDER,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher<PC extends PC_ANY>(\n Point: PC,\n mapToCurve: MapToCurve<PC_F<PC>>,\n defaults: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>\n): H2CHasher<PC> {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n const snapshot = (src: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>): TRet<H2CDefaults> =>\n Object.freeze({\n ...src,\n DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n ...(src.encodeDST === undefined\n ? {}\n : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n }) as TRet<H2CDefaults>;\n // Keep one private defaults snapshot for actual hashing and expose fresh\n // detached snapshots via the public getter.\n // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n // the singleton hasher for every other consumer in the same process.\n const safeDefaults = snapshot(defaults);\n function map(num: bigint[]): PC_P<PC> {\n return Point.fromAffine(mapToCurve(num)) as PC_P<PC>;\n }\n function clear(initial: PC_P<PC>): PC_P<PC> {\n const P = initial.clearCofactor();\n // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n if (P.equals(Point.ZERO)) return Point.ZERO as PC_P<PC>;\n P.assertValidity();\n return P as PC_P<PC>;\n }\n\n return Object.freeze({\n get defaults() {\n return snapshot(safeDefaults);\n },\n Point,\n\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const opts = Object.assign({}, safeDefaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1) as PC_P<PC>);\n },\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n const opts = Object.assign({}, safeDefaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars: bigint | bigint[]): PC_P<PC> {\n // Curves with m=1 accept only single scalar\n if (safeDefaults.m === 1) {\n if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n });\n}\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abignumber,\n abool,\n abytes,\n aInRange,\n asafenumber,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type HmacFn,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n FpIsSquare,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n /** Cube root of unity used by the GLV endomorphism. */\n beta: bigint;\n /** Reduced lattice basis used for scalar splitting. */\n basises?: EndoBasis;\n /**\n * Optional custom scalar-splitting helper.\n * Receives one scalar and returns two half-sized scalar components.\n */\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n /** Whether the first split scalar should be negated. */\n k1neg: boolean;\n /** Absolute value of the first split scalar. */\n k1: bigint;\n /** Whether the second split scalar should be negated. */\n k2neg: boolean;\n /** Absolute value of the second split scalar. */\n k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n /** Whether to hash the message before signature recovery. */\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n /** Whether to hash the message before verification. */\n prehash?: boolean;\n /** Whether to reject high-S signatures. */\n lowS?: boolean;\n /** Signature encoding to accept. */\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n * security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n /** Whether to hash the message before signing. */\n prehash?: boolean;\n /** Whether to normalize signatures into the low-S half-order. */\n lowS?: boolean;\n /** Signature encoding to produce. */\n format?: ECDSASignatureFormat;\n /** Optional hedging input for deterministic k generation. */\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): D {\n validateObject(opts);\n const optsn = {} as D;\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def) as (keyof D)[]) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /**\n * Encode the point into compressed or uncompressed SEC1 bytes.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point bytes.\n */\n toBytes(isCompressed?: boolean): TRet<Uint8Array>;\n /**\n * Encode the point into compressed or uncompressed SEC1 hex.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point hex.\n */\n toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n /**\n * Return the curve parameters captured by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\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, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Weierstrass curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts<T> = Partial<{\n /** Optional base-field override. */\n Fp: IField<T>;\n /** Optional scalar-field override. */\n Fn: IField<bigint>;\n /** Whether the point constructor accepts infinity points. */\n allowInfinityPoint: boolean;\n /** Optional GLV endomorphism data. */\n endo: EndomorphismOpts;\n /** Optional torsion-check override. */\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n /** Optional cofactor-clearing override. */\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n /** Optional custom point decoder. */\n fromBytes: (bytes: TArg<Uint8Array>) => AffinePoint<T>;\n /** Optional custom point encoder. */\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => TRet<Uint8Array>;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n * low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n * `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n /** Default low-S policy for this ECDSA instance. */\n lowS: boolean;\n /** HMAC implementation used by RFC6979 DRBG. */\n hmac: HmacFn;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n /** Hash-to-integer conversion override. */\n bits2int: (bytes: TArg<Uint8Array>) => bigint;\n /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n bits2int_modN: (bytes: TArg<Uint8Array>) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\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 * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>, isCompressed?: boolean) => TRet<Uint8Array>;\n /**\n * Compute the shared secret point from a secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded shared point.\n */\n getSharedSecret: (\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed?: boolean\n ) => TRet<Uint8Array>;\n /** Point constructor used by this ECDH instance. */\n Point: WeierstrassPointCons<bigint>;\n /** Validation and random-key helpers. */\n utils: {\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>, isCompressed?: boolean) => boolean;\n /** Generate a valid random secret key. */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n };\n /** Byte lengths for keys and signatures exposed by this curve. */\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n /**\n * Sign a message with the given secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<ECDSASignOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify a signature against a message and public key.\n * @param signature - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n * @returns Whether the signature is valid.\n */\n verify: (\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<ECDSAVerifyOpts>\n ) => boolean;\n /**\n * Recover the public key encoded into a recoverable signature.\n * @param signature - Recoverable signature bytes.\n * @param message - Message bytes.\n * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n * @returns Encoded recovered public key.\n */\n recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts?: TArg<ECDSARecoverOpts>\n ): TRet<Uint8Array>;\n /** Signature constructor and parser helpers. */\n Signature: ECDSASignatureCons;\n}\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n // asn.1 DER encoding utils\n /**\n * DER-specific error constructor.\n * @param m - Error message.\n * @returns DER-specific error instance.\n */\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n /** Low-level tag-length-value helpers used by DER encoders. */\n _tlv: {\n /**\n * Encode one TLV record.\n * @param tag - ASN.1 tag byte.\n * @param data - Hex-encoded value payload.\n * @returns Encoded TLV string.\n */\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n /**\n * Decode one TLV record and return the value plus leftover bytes.\n * @param tag - Expected ASN.1 tag byte.\n * @param data - Remaining DER bytes.\n * @returns Parsed value plus leftover bytes.\n */\n decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }>;\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n /** Positive-integer DER helpers used by ECDSA signature encoding. */\n _int: {\n /**\n * Encode one positive bigint as a DER INTEGER.\n * @param num - Positive integer to encode.\n * @returns Encoded DER INTEGER.\n */\n encode(num: bigint): string;\n /**\n * Decode one DER INTEGER into a bigint.\n * @param data - DER INTEGER bytes.\n * @returns Decoded bigint.\n */\n decode(data: TArg<Uint8Array>): bigint;\n };\n /**\n * Parse a DER signature into `{ r, s }`.\n * @param bytes - DER signature bytes.\n * @returns Parsed signature components.\n */\n toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint };\n /**\n * Encode `{ r, s }` as a DER signature.\n * @param sig - Signature components.\n * @returns DER-encoded signature hex.\n */\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof data);\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }> {\n const { Err: E } = DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n abignumber(num);\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: TArg<Uint8Array>): bigint {\n const { Err: E } = DER;\n if (data.length < 1) throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\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), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp as IField<T>;\n const Fn = validated.Fn as IField<bigint>;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp as TArg<IField<T>>, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): TRet<Uint8Array> {\n // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet<Uint8Array>;\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx) as TRet<Uint8Array>;\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet<Uint8Array>;\n }\n }\n function pointFromBytes(bytes: TArg<Uint8Array>) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown): asserts other is Point {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: TArg<Uint8Array>): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: WeierstrassPoint<T>): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: WeierstrassPoint<T>): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: WeierstrassPoint<T>) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-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)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n if (cofactor === _1n) return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n\n toBytes(isCompressed = true): TRet<Uint8Array> {\n abool(isCompressed, 'isCompressed');\n // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\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 (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/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n /** Signature component `r`. */\n readonly r: bigint;\n /** Signature component `s`. */\n readonly s: bigint;\n /** Optional recovery bit for recoverable signatures. */\n readonly recovery?: number;\n /**\n * Return a copy of the signature with a recovery bit attached.\n * @param recovery - Recovery bit to attach.\n * @returns Signature with an attached recovery bit.\n */\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n /**\n * Check whether the signature uses the high-S half-order.\n * @returns Whether the signature uses the high-S half-order.\n */\n hasHighS(): boolean;\n /**\n * Recover the public key from the hashed message and recovery bit.\n * @param messageHash - Hashed message bytes.\n * @returns Recovered public-key point.\n */\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint>;\n /**\n * Encode the signature into bytes.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature bytes.\n */\n toBytes(format?: string): TRet<Uint8Array>;\n /**\n * Encode the signature into hex.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature hex.\n */\n toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n /** Create a signature from `r`, `s`, and an optional recovery bit. */\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n /**\n * Decode a signature from bytes.\n * @param bytes - Encoded signature bytes.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromBytes(bytes: TArg<Uint8Array>, format?: ECDSASignatureFormat): ECDSASignature;\n /**\n * Decode a signature from hex.\n * @param hex - Encoded signature hex.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet<Uint8Array> {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet<Uint8Array>;\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: TArg<IField<T>>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp as IField<T>) as IField<T>;\n // Generic implementation\n const q = F.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: TArg<IField<T>>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n const F = validateField(Fp as IField<T>) as IField<T>;\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 §6.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField<T>` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths<T>(Fp: TArg<IField<T>>, Fn: TArg<IField<bigint>>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet<Uint8Array> }> = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n\n function isValidSecretKey(secretKey: TArg<Uint8Array>) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: TArg<Uint8Array>, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet<Uint8Array>;\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: TArg<Uint8Array>, isCompressed = true): TRet<Uint8Array> {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: TArg<Uint8Array>): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n if (!isBytes(item)) return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec) return undefined;\n return isPub;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed = true\n ): TRet<Uint8Array> {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: TArg<CHash>,\n ecdsaOpts: TArg<ECDSAOpts> = {}\n): ECDSA {\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash as CHash;\n ahash(hash_);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac =\n ecdsaOpts.hmac === undefined\n ? (key: TArg<Uint8Array>, msg: TArg<Uint8Array>) => nobleHmac(hash_, key, msg)\n : (ecdsaOpts.hmac as HmacFn);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertRecoverableCurve(): void {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: TArg<Uint8Array>, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: TArg<Uint8Array>,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint> {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet<Uint8Array> {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet<Uint8Array>;\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet<Uint8Array>;\n }\n return concatBytes(rb, sb) as TRet<Uint8Array>;\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int === undefined\n ? function bits2int_def(bytes: TArg<Uint8Array>): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : (ecdsaOpts.bits2int as (bytes: TArg<Uint8Array>) => bigint);\n const bits2int_modN: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes: TArg<Uint8Array>): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : (ecdsaOpts.bits2int_modN as (bytes: TArg<Uint8Array>) => bigint);\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): TRet<Uint8Array> {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num) as TRet<Uint8Array>;\n }\n\n function validateMsgAndHash(message: TArg<Uint8Array>, prehash: boolean): TRet<Uint8Array> {\n abytes(message, undefined, 'message');\n return (\n prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n ) as TRet<Uint8Array>;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts>\n ) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs: TArg<Uint8Array>[] = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs) as TRet<Uint8Array>; // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: TArg<Uint8Array>): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts> = {}\n ): TRet<Uint8Array> {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<Signature>(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts: TArg<ECDSAVerifyOpts> = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts: TArg<ECDSARecoverOpts> = {}\n ): TRet<Uint8Array> {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n }) satisfies Signer;\n}\n","/**\n * BLS != BLS.\n * The file implements BLS (Boneh-Lynn-Shacham) signatures.\n * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)\n * families of pairing-friendly curves.\n * Consists of two curves: G1 and G2:\n * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.\n * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1\n * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in\n * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.\n * Pairing is used to aggregate and verify signatures.\n * There are two modes of operation:\n * - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs).\n * - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs).\n * @module\n **/\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, notImplemented, randomBytes, type TArg, type TRet } from '../utils.ts';\nimport { type CurveLengths } from './curve.ts';\nimport {\n createHasher,\n type H2CDSTOpts,\n type H2CHasher,\n type H2COpts,\n type MapToCurve,\n} from './hash-to-curve.ts';\nimport { getMinHashLength, mapHashToField, type IField } from './modular.ts';\nimport type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6Bls } from './tower.ts';\nimport { type WeierstrassPoint, type WeierstrassPointCons } from './weierstrass.ts';\n\ntype Fp = bigint; // Can be different field?\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n\n/**\n * Twist convention used by the pairing formulas for a concrete curve family.\n * BLS12-381 uses a multiplicative twist, while BN254 uses a divisive one.\n */\nexport type BlsTwistType = 'multiplicative' | 'divisive';\n\n/**\n * Codec exposed as `curve.shortSignatures.Signature`.\n * Use it to parse or serialize G1 signatures in short-signature mode.\n * In this mode, public keys live in G2.\n */\nexport type BlsShortSignatureCoder<Fp> = {\n /**\n * Parse a compressed signature from raw bytes.\n * @param bytes - Compressed signature bytes.\n * @returns Parsed signature point.\n */\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;\n /**\n * Parse a compressed signature from a hex string.\n * @param hex - Compressed signature hex string.\n * @returns Parsed signature point.\n */\n fromHex(hex: string): WeierstrassPoint<Fp>;\n /**\n * Encode a signature point into compressed bytes.\n * @param point - Signature point.\n * @returns Compressed signature bytes.\n */\n toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;\n /**\n * Encode a signature point into a hex string.\n * @param point - Signature point.\n * @returns Compressed signature hex.\n */\n toHex(point: WeierstrassPoint<Fp>): string;\n};\n\n/**\n * Codec exposed as `curve.longSignatures.Signature`.\n * Use it to parse or serialize G2 signatures in long-signature mode.\n * In this mode, public keys live in G1.\n */\nexport type BlsLongSignatureCoder<Fp> = {\n /**\n * Parse a compressed signature from raw bytes.\n * @param bytes - Compressed signature bytes.\n * @returns Parsed signature point.\n */\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;\n /**\n * Parse a compressed signature from a hex string.\n * @param hex - Compressed signature hex string.\n * @returns Parsed signature point.\n */\n fromHex(hex: string): WeierstrassPoint<Fp>;\n /**\n * Encode a signature point into compressed bytes.\n * @param point - Signature point.\n * @returns Compressed signature bytes.\n */\n toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;\n /**\n * Encode a signature point into a hex string.\n * @param point - Signature point.\n * @returns Compressed signature hex.\n */\n toHex(point: WeierstrassPoint<Fp>): string;\n};\n\n/** Tower fields needed by pairing code, hash-to-curve, and subgroup arithmetic. */\nexport type BlsFields = {\n /** Base field of G1 coordinates. */\n Fp: IField<Fp>;\n /** Scalar field used for secret scalars and subgroup order arithmetic. */\n Fr: IField<bigint>;\n /** Quadratic extension field used by G2. */\n Fp2: Fp2Bls;\n /** Sextic extension field used inside pairing arithmetic. */\n Fp6: Fp6Bls;\n /** Degree-12 extension field that contains the GT target group. */\n Fp12: Fp12Bls;\n};\n\n/**\n * Callback used by pairing post-processing hooks to add one more G2 point to the Miller-loop state.\n * @param Rx - Current projective X coordinate.\n * @param Ry - Current projective Y coordinate.\n * @param Rz - Current projective Z coordinate.\n * @param Qx - G2 affine x coordinate.\n * @param Qy - G2 affine y coordinate.\n * @returns Updated projective accumulator coordinates.\n */\nexport type BlsPostPrecomputePointAddFn = (\n Rx: Fp2,\n Ry: Fp2,\n Rz: Fp2,\n Qx: Fp2,\n Qy: Fp2\n) => { Rx: Fp2; Ry: Fp2; Rz: Fp2 };\n/**\n * Hook for curve-specific pairing cleanup after the Miller loop precomputes are built.\n * @param Rx - Current projective X coordinate.\n * @param Ry - Current projective Y coordinate.\n * @param Rz - Current projective Z coordinate.\n * @param Qx - G2 affine x coordinate.\n * @param Qy - G2 affine y coordinate.\n * @param pointAdd - Callback used to fold one more point into the accumulator.\n */\nexport type BlsPostPrecomputeFn = (\n Rx: Fp2,\n Ry: Fp2,\n Rz: Fp2,\n Qx: Fp2,\n Qy: Fp2,\n pointAdd: BlsPostPrecomputePointAddFn\n) => void;\n/** Low-level pairing helpers shared by BLS curve bundles. */\nexport type BlsPairing = {\n /** Byte lengths for keys and signatures exposed by this pairing family. */\n lengths: CurveLengths;\n /** Scalar field used by the pairing and signing helpers. */\n Fr: IField<bigint>;\n /** Target field used for the GT result of pairings. */\n Fp12: Fp12Bls;\n /**\n * Build Miller-loop precomputes for one G2 point.\n * @param p - G2 point to precompute.\n * @returns Pairing precompute table.\n */\n calcPairingPrecomputes: (p: WeierstrassPoint<Fp2>) => Precompute;\n /**\n * Evaluate a batch of Miller loops from precomputed line coefficients.\n * @param pairs - Precomputed Miller-loop inputs.\n * @returns Accumulated GT value before or after final exponentiation.\n */\n millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12;\n /**\n * Pair one G1 point with one G2 point.\n * @param P - G1 point.\n * @param Q - G2 point.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result.\n * @throws If either point is the point at infinity. {@link Error}\n */\n pairing: (P: WeierstrassPoint<Fp>, Q: WeierstrassPoint<Fp2>, withFinalExponent?: boolean) => Fp12;\n /**\n * Pair many G1/G2 pairs in one batch.\n * @param pairs - Point pairs to accumulate.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result. Empty input returns the multiplicative identity in GT.\n */\n pairingBatch: (\n pairs: { g1: WeierstrassPoint<Fp>; g2: WeierstrassPoint<Fp2> }[],\n withFinalExponent?: boolean\n ) => Fp12;\n /**\n * Generate a random secret key for this pairing family.\n * @param seed - Optional seed material.\n * @returns Secret key bytes.\n */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/**\n * Parameters that define the Miller-loop shape and twist handling\n * for a concrete pairing family.\n */\nexport type BlsPairingParams = {\n // MSB is always ignored and used as marker for length, otherwise leading zeros will be lost.\n // Can be different from `X` (seed) param.\n /** Signed loop parameter used by the Miller loop. */\n ateLoopSize: bigint;\n /** Whether the signed Miller-loop parameter is negative. */\n xNegative: boolean;\n /**\n * Twist convention used by the pairing formulas.\n * BLS12-381 is multiplicative; BN254 is divisive.\n */\n twistType: BlsTwistType;\n /**\n * Optional RNG override used by helper constructors.\n * Receives the requested byte length and returns random bytes.\n */\n randomBytes?: (len?: number) => TRet<Uint8Array>;\n /**\n * Optional hook for curve-specific untwisting after precomputation.\n * Used by BN254 after the Miller loop.\n */\n postPrecompute?: BlsPostPrecomputeFn;\n};\n/** Hash-to-curve settings shared by the G1 and G2 hashers inside a BLS curve bundle. */\nexport type BlsHasherParams = {\n /**\n * Optional map-to-curve override for G1.\n * Receives the hash-to-field tuple and returns one affine G1 point.\n */\n mapToG1?: MapToCurve<Fp>;\n /**\n * Optional map-to-curve override for G2.\n * Receives the hash-to-field tuple and returns one affine G2 point.\n */\n mapToG2?: MapToCurve<Fp2>;\n /** Shared baseline hash-to-curve options. */\n hasherOpts: H2COpts;\n /** G1-specific hash-to-curve options merged on top of `hasherOpts`. */\n hasherOptsG1: H2COpts;\n /** G2-specific hash-to-curve options merged on top of `hasherOpts`. */\n hasherOptsG2: H2COpts;\n};\ntype PrecomputeSingle = [Fp2, Fp2, Fp2][];\ntype Precompute = PrecomputeSingle[];\n\n/**\n * BLS consists of two curves: G1 and G2:\n * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.\n * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1\n */\nexport interface BlsCurvePair {\n /** Byte lengths for keys and signatures exposed by this curve family. */\n lengths: CurveLengths;\n /**\n * Shared Miller-loop batch evaluator.\n * @param pairs - Precomputed Miller-loop inputs.\n * @returns Accumulated GT value.\n */\n millerLoopBatch: BlsPairing['millerLoopBatch'];\n /**\n * Pair one G1 point with one G2 point.\n * @param P - G1 point.\n * @param Q - G2 point.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result.\n * @throws If either point is the point at infinity. {@link Error}\n */\n pairing: BlsPairing['pairing'];\n /**\n * Pair many G1/G2 pairs in one batch.\n * @param pairs - Point pairs to accumulate.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result. Empty input returns the multiplicative identity in GT.\n */\n pairingBatch: BlsPairing['pairingBatch'];\n /** G1 point constructor for the base field subgroup. */\n G1: { Point: WeierstrassPointCons<Fp> };\n /** G2 point constructor for the twist subgroup. */\n G2: { Point: WeierstrassPointCons<Fp2> };\n /** Tower fields exposed by the pairing implementation. */\n fields: {\n Fp: IField<Fp>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n Fr: IField<bigint>;\n };\n /** Utility helpers shared by hashers and signers. */\n utils: {\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n calcPairingPrecomputes: BlsPairing['calcPairingPrecomputes'];\n };\n /** Public pairing parameters exposed for introspection. */\n params: {\n ateLoopSize: bigint;\n twistType: BlsTwistType;\n };\n}\n\n/** BLS curve bundle extended with hash-to-curve helpers for G1 and G2. */\nexport interface BlsCurvePairWithHashers extends BlsCurvePair {\n /** G1 hasher bundle with RFC 9380 helpers. */\n G1: H2CHasher<WeierstrassPointCons<Fp>>;\n /** G2 hasher bundle with RFC 9380 helpers. */\n G2: H2CHasher<WeierstrassPointCons<Fp2>>;\n}\n\n/** BLS curve bundle extended with both hashers and signature helpers. */\nexport interface BlsCurvePairWithSignatures extends BlsCurvePairWithHashers {\n /** Long-signature mode: G1 public keys and G2 signatures. */\n longSignatures: BlsSigs<bigint, Fp2>;\n /** Short-signature mode: G2 public keys and G1 signatures. */\n shortSignatures: BlsSigs<Fp2, bigint>;\n}\n\ntype BLSInput = TArg<Uint8Array>;\n/** BLS signer helpers for one signature mode. */\nexport interface BlsSigs<P, S> {\n /** Byte lengths for secret keys, public keys, and signatures. */\n lengths: CurveLengths;\n /**\n * Generate a secret/public key pair for this signature mode.\n * @param seed - Optional seed material.\n * @returns Secret and public key pair.\n */\n keygen(seed?: TArg<Uint8Array>): {\n secretKey: TRet<Uint8Array>;\n publicKey: WeierstrassPoint<P>;\n };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public-key point.\n */\n getPublicKey(secretKey: TArg<Uint8Array>): WeierstrassPoint<P>;\n /**\n * Sign a message already hashed onto the signature subgroup.\n * @param hashedMessage - Message mapped to the signature subgroup.\n * @param secretKey - Secret key bytes.\n * @returns Signature point.\n */\n sign(hashedMessage: WeierstrassPoint<S>, secretKey: TArg<Uint8Array>): WeierstrassPoint<S>;\n /**\n * Verify one signature against one public key and hashed message.\n * @param signature - Signature point or encoded signature.\n * @param message - Hashed message point.\n * @param publicKey - Public-key point or encoded key.\n * @returns Whether the signature is valid.\n */\n verify(\n signature: WeierstrassPoint<S> | BLSInput,\n message: WeierstrassPoint<S>,\n publicKey: WeierstrassPoint<P> | BLSInput\n ): boolean;\n /**\n * Verify one aggregated signature against many `(message, publicKey)` pairs.\n * @param signature - Aggregated signature.\n * @param items - Message/public-key pairs.\n * @returns Whether the aggregated signature is valid. Same-message aggregate verification still\n * requires proof of possession or another rogue-key defense from the caller.\n */\n verifyBatch: (\n signature: WeierstrassPoint<S> | BLSInput,\n items: { message: WeierstrassPoint<S>; publicKey: WeierstrassPoint<P> | BLSInput }[]\n ) => boolean;\n /**\n * Add many public keys into one aggregate point.\n * @param publicKeys - Public keys to aggregate.\n * @returns Aggregated public-key point. This is raw point addition and does not add proof of\n * possession or rogue-key protection on its own.\n */\n aggregatePublicKeys(publicKeys: (WeierstrassPoint<P> | BLSInput)[]): WeierstrassPoint<P>;\n /**\n * Add many signatures into one aggregate point.\n * @param signatures - Signatures to aggregate.\n * @returns Aggregated signature point. This is raw point addition and does not change the proof\n * of possession requirements of the aggregate-verification scheme.\n */\n aggregateSignatures(signatures: (WeierstrassPoint<S> | BLSInput)[]): WeierstrassPoint<S>;\n /**\n * Hash an arbitrary message onto the signature subgroup.\n * @param message - Message bytes.\n * @param DST - Optional domain separation tag.\n * @returns Curve point on the signature subgroup.\n */\n hash(message: TArg<Uint8Array>, DST?: TArg<string | Uint8Array>): WeierstrassPoint<S>;\n /** Signature codec for this mode. */\n Signature: BlsLongSignatureCoder<S>;\n}\n\n// Signed non-adjacent decomposition of the spec-defined Miller-loop parameter.\n// BN254 benefits most because `6x+2` has multiple adjacent `11` runs, but BLS12-381's\n// stored `|x|` still starts with `11`, so the Miller loop must also handle one `-1` digit there.\nfunction NAfDecomposition(a: bigint) {\n const res = [];\n // a>1 because of marker bit\n for (; a > _1n; a >>= _1n) {\n if ((a & _1n) === _0n) res.unshift(0);\n else if ((a & _3n) === _3n) {\n res.unshift(-1);\n a += _1n;\n } else res.unshift(1);\n }\n return res;\n}\nfunction aNonEmpty(arr: any[]) {\n // Aggregate helpers use this to reject empty variable-length inputs consistently.\n // Without the guard, each caller would fall through into a different empty-input / identity\n // case and hide missing inputs behind outputs that still look structurally valid.\n if (!Array.isArray(arr) || arr.length === 0) throw new Error('expected non-empty array');\n}\n\n// This should be enough for bn254, no need to export full stuff?\nfunction createBlsPairing(\n fields: TArg<BlsFields>,\n G1: WeierstrassPointCons<Fp>,\n G2: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>\n): BlsPairing {\n const { Fr, Fp2, Fp12 } = fields;\n const { twistType, ateLoopSize, xNegative, postPrecompute } = params;\n type G1 = typeof G1.BASE;\n type G2 = typeof G2.BASE;\n // Applies sparse multiplication as line function\n let lineFunction: (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => Fp12;\n if (twistType === 'multiplicative') {\n lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) =>\n Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));\n } else if (twistType === 'divisive') {\n // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of\n // precompute calculations.\n lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) =>\n Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);\n } else throw new Error('bls: unknown twist type');\n\n const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));\n function pointDouble(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2) {\n const t0 = Fp2.sqr(Ry); // Ry²\n const t1 = Fp2.sqr(Rz); // Rz²\n const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B\n const t3 = Fp2.mul(t2, _3n); // 3 * T2\n const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0\n const c0 = Fp2.sub(t2, t0); // T2 - T0 (i)\n const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx²\n const c2 = Fp2.neg(t4); // -T4 (-h)\n\n ell.push([c0, c1, c2]);\n\n Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2\n // ((T0 + T3) / 2)² - 3 * T2²\n Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n));\n Rz = Fp2.mul(t0, t4); // T0 * T4\n return { Rx, Ry, Rz };\n }\n function pointAdd(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) {\n // Addition\n const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz\n const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz\n const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy\n const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry\n const c2 = t1; // == Rx - Qx * Rz\n\n ell.push([c0, c1, c2]);\n\n const t2 = Fp2.sqr(t1); // T1²\n const t3 = Fp2.mul(t2, t1); // T2 * T1\n const t4 = Fp2.mul(t2, Rx); // T2 * Rx\n // T3 - 2 * T4 + T0² * Rz\n const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz));\n Rx = Fp2.mul(t1, t5); // T1 * T5\n Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry\n Rz = Fp2.mul(Rz, t3); // Rz * T3\n return { Rx, Ry, Rz };\n }\n\n // Pre-compute coefficients for sparse multiplication\n // Point addition and point double calculations is reused for coefficients\n // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine\n // add + double in windowed precomputes here, otherwise it would be single op (since X is static)\n const ATE_NAF = NAfDecomposition(ateLoopSize);\n\n const calcPairingPrecomputes = (point: G2) => {\n const p = point;\n const { x, y } = p.toAffine();\n // prettier-ignore\n const Qx = x, Qy = y, negQy = Fp2.neg(y);\n // prettier-ignore\n let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;\n const ell: Precompute = [];\n for (const bit of ATE_NAF) {\n const cur: PrecomputeSingle = [];\n ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));\n if (bit) ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));\n ell.push(cur);\n }\n if (postPrecompute) {\n const last = ell[ell.length - 1];\n postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));\n }\n return ell;\n };\n\n // Main pairing logic is here. Computes product of miller loops + final exponentiate\n // Applies calculated precomputes\n type MillerInput = [Precompute, Fp, Fp][];\n function millerLoopBatch(pairs: MillerInput, withFinalExponent: boolean = false) {\n let f12 = Fp12.ONE;\n if (pairs.length) {\n const ellLen = pairs[0][0].length;\n for (let i = 0; i < ellLen; i++) {\n f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings\n // NOTE: we apply multiple pairings in parallel here\n for (const [ell, Px, Py] of pairs) {\n for (const [c0, c1, c2] of ell[i]) f12 = lineFunction(c0, c1, c2, f12, Px, Py);\n }\n }\n }\n if (xNegative) f12 = Fp12.conjugate(f12);\n return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;\n }\n type PairingInput = { g1: G1; g2: G2 };\n // Calculates product of multiple pairings\n // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))`\n function pairingBatch(pairs: PairingInput[], withFinalExponent: boolean = true) {\n const res: MillerInput = [];\n for (const { g1, g2 } of pairs) {\n // Mathematically, a zero pairing term contributes GT.ONE. We still reject it here because\n // this API mainly backs BLS verification, where ZERO inputs usually mean broken hash /\n // wiring. Silently skipping them would turn those failures into a neutral pairing product.\n // Callers that want the algebraic neutral-element behavior can filter ZERO terms first.\n if (g1.is0() || g2.is0()) throw new Error('pairing is not available for ZERO point');\n // This uses toAffine inside\n g1.assertValidity();\n g2.assertValidity();\n const Qa = g1.toAffine();\n res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);\n }\n return millerLoopBatch(res, withFinalExponent);\n }\n // Calculates bilinear pairing\n function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 {\n return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);\n }\n const lengths = {\n seed: getMinHashLength(Fr.ORDER),\n };\n const rand = params.randomBytes === undefined ? randomBytes : params.randomBytes;\n // Seeded calls deterministically reduce exactly `lengths.seed` bytes into `1..Fr.ORDER-1`;\n // omitting `seed` just fills that input buffer from the configured RNG first.\n const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n seed = seed === undefined ? rand(lengths.seed) : seed;\n abytes(seed, lengths.seed, 'seed');\n return mapHashToField(seed, Fr.ORDER) as TRet<Uint8Array>;\n };\n Object.freeze(lengths);\n return {\n lengths,\n Fr,\n Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12!\n millerLoopBatch,\n pairing,\n pairingBatch,\n calcPairingPrecomputes,\n randomSecretKey,\n };\n}\n\nfunction createBlsSig<P, S>(\n blsPairing: BlsPairing,\n PubPoint: WeierstrassPointCons<P>,\n SigPoint: WeierstrassPointCons<S>,\n isSigG1: boolean,\n hashToSigCurve: (msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>) => WeierstrassPoint<S>,\n SignatureCoder?: BlsLongSignatureCoder<S>\n): BlsSigs<P, S> {\n const { Fr, Fp12, pairingBatch, randomSecretKey, lengths } = blsPairing;\n if (!SignatureCoder) {\n SignatureCoder = {\n fromBytes: notImplemented,\n fromHex: notImplemented,\n toBytes: notImplemented,\n toHex: notImplemented,\n };\n }\n type PubPoint = WeierstrassPoint<P>;\n type SigPoint = WeierstrassPoint<S>;\n function normPub(point: PubPoint | BLSInput): PubPoint {\n return point instanceof PubPoint ? (point as PubPoint) : PubPoint.fromBytes(point);\n }\n function normSig(point: SigPoint | BLSInput): SigPoint {\n return point instanceof SigPoint ? (point as SigPoint) : SigPoint.fromBytes(point);\n }\n // Sign/verify here take points already hashed onto the signature subgroup.\n // Raw bytes and points from the other subgroup must fail this constructor-brand\n // check before later validity checks run.\n function amsg(m: unknown): SigPoint {\n if (!(m instanceof SigPoint))\n throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`);\n return m as SigPoint;\n }\n\n type G1 = WeierstrassPoint<Fp>;\n type G2 = WeierstrassPoint<Fp2>;\n type PairingInput = { g1: G1; g2: G2 };\n // What matters here is what point pairing API accepts as G1 or G2, not actual size or names\n const pair: (a: PubPoint, b: SigPoint) => PairingInput = !isSigG1\n ? (a: PubPoint, b: SigPoint) => ({ g1: a, g2: b }) as PairingInput\n : (a: PubPoint, b: SigPoint) => ({ g1: b, g2: a }) as PairingInput;\n return Object.freeze({\n lengths: Object.freeze({ ...lengths, secretKey: Fr.BYTES }),\n keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed);\n const publicKey = this.getPublicKey(secretKey);\n return { secretKey, publicKey };\n },\n // P = pk x G\n getPublicKey(secretKey: TArg<Uint8Array>): PubPoint {\n let sec;\n try {\n sec = PubPoint.Fn.fromBytes(secretKey);\n } catch (error) {\n // @ts-ignore\n throw new Error('invalid private key: ' + typeof secretKey, { cause: error });\n }\n return PubPoint.BASE.multiply(sec);\n },\n // S = pk x H(m)\n sign(message: SigPoint, secretKey: TArg<Uint8Array>, unusedArg?: any): SigPoint {\n if (unusedArg != null) throw new Error('sign() expects 2 arguments');\n const sec = PubPoint.Fn.fromBytes(secretKey);\n amsg(message).assertValidity();\n return message.multiply(sec);\n },\n // Checks if pairing of public key & hash is equal to pairing of generator & signature.\n // e(P, H(m)) == e(G, S)\n // e(S, G) == e(H(m), P)\n verify(\n signature: SigPoint | BLSInput,\n message: SigPoint,\n publicKey: PubPoint | BLSInput,\n unusedArg?: any\n ): boolean {\n if (unusedArg != null) throw new Error('verify() expects 3 arguments');\n signature = normSig(signature);\n publicKey = normPub(publicKey);\n const P = publicKey.negate();\n const G = PubPoint.BASE;\n const Hm = amsg(message);\n const S = signature;\n // This code was changed in 1.9.x:\n // Before it was G.negate() in G2, now it's always pubKey.negate\n // e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair).\n // We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1\n try {\n const exp = pairingBatch([pair(P, Hm), pair(G, S)]);\n return Fp12.eql(exp, Fp12.ONE);\n } catch {\n return false;\n }\n },\n // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407\n // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))\n // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?\n verifyBatch(\n signature: SigPoint | BLSInput,\n items: { message: SigPoint; publicKey: PubPoint | BLSInput }[]\n ): boolean {\n aNonEmpty(items);\n const sig = normSig(signature);\n const nMessages = items.map((i) => i.message);\n const nPublicKeys = items.map((i) => normPub(i.publicKey));\n // NOTE: this works only for exact same object\n const messagePubKeyMap = new Map<SigPoint, PubPoint[]>();\n for (let i = 0; i < nPublicKeys.length; i++) {\n const pub = nPublicKeys[i];\n const msg = nMessages[i];\n let keys = messagePubKeyMap.get(msg);\n if (keys === undefined) {\n keys = [];\n messagePubKeyMap.set(msg, keys);\n }\n keys.push(pub);\n }\n const paired = [];\n const G = PubPoint.BASE;\n try {\n for (const [msg, keys] of messagePubKeyMap) {\n const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg));\n paired.push(pair(groupPublicKey, msg));\n }\n paired.push(pair(G.negate(), sig));\n return Fp12.eql(pairingBatch(paired), Fp12.ONE);\n } catch {\n return false;\n }\n },\n // Adds a bunch of public key points together.\n // pk1 + pk2 + pk3 = pkA\n aggregatePublicKeys(publicKeys: (PubPoint | BLSInput)[]): PubPoint {\n aNonEmpty(publicKeys);\n publicKeys = publicKeys.map((pub) => normPub(pub));\n const agg = (publicKeys as PubPoint[]).reduce((sum, p) => sum.add(p), PubPoint.ZERO);\n agg.assertValidity();\n return agg;\n },\n\n // Adds a bunch of signature points together.\n // pk1 + pk2 + pk3 = pkA\n aggregateSignatures(signatures: (SigPoint | BLSInput)[]): SigPoint {\n aNonEmpty(signatures);\n signatures = signatures.map((sig) => normSig(sig));\n const agg = (signatures as SigPoint[]).reduce((sum, s) => sum.add(s), SigPoint.ZERO);\n agg.assertValidity();\n return agg;\n },\n\n hash(messageBytes: TArg<Uint8Array>, DST?: TArg<string | Uint8Array>): SigPoint {\n abytes(messageBytes);\n const opts = DST ? { DST } : undefined;\n return hashToSigCurve(messageBytes, opts);\n },\n Signature: Object.freeze({ ...SignatureCoder }),\n }) /*satisfies Signer */;\n}\n\ntype BlsSignatureCoders = Partial<{\n LongSignature: BlsLongSignatureCoder<Fp2>;\n ShortSignature: BlsShortSignatureCoder<Fp>;\n}>;\n\n// NOTE: separate function instead of function override, so we don't depend on hasher in bn254.\n/**\n * @param fields - Tower field implementations.\n * @param G1_Point - G1 point constructor.\n * @param G2_Point - G2 point constructor.\n * @param params - Pairing parameters. See {@link BlsPairingParams}.\n * @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while\n * empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the\n * low-level pairing API fail-closed for BLS-style callers, where identity points usually signal\n * broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly\n * precomputes the G1 base-point table as a performance side effect.\n * @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error}\n * @example\n * ```ts\n * import { blsBasic } from '@noble/curves/abstract/bls.js';\n * import { bn254 } from '@noble/curves/bn254.js';\n * // Pair a G1 point with a G2 point without the higher-level signer helpers.\n * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE);\n * ```\n */\nexport function blsBasic(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>\n): BlsCurvePair {\n // Fields are specific for curve, so for now we'll need to pass them with opts\n const { Fp, Fr, Fp2, Fp6, Fp12 } = fields;\n // Point on G1 curve: (x, y)\n // const G1_Point = weierstrass(CURVE.G1, { Fn: Fr });\n const G1 = { Point: G1_Point };\n // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)\n const G2 = { Point: G2_Point };\n\n const pairingRes = createBlsPairing(fields, G1_Point, G2_Point, params);\n const {\n millerLoopBatch,\n pairing,\n pairingBatch,\n calcPairingPrecomputes,\n randomSecretKey,\n lengths,\n } = pairingRes;\n\n G1.Point.BASE.precompute(4);\n Object.freeze(G1);\n Object.freeze(G2);\n return Object.freeze({\n lengths: Object.freeze(lengths),\n millerLoopBatch,\n pairing,\n pairingBatch,\n G1,\n G2,\n fields: Object.freeze({ Fr, Fp, Fp2, Fp6, Fp12 }),\n params: Object.freeze({\n ateLoopSize: params.ateLoopSize,\n twistType: params.twistType,\n }),\n utils: Object.freeze({\n randomSecretKey,\n calcPairingPrecomputes,\n }),\n });\n}\n\n// We can export this too, but seems there is not much reasons for now? If user wants hasher, they can just create hasher.\nfunction blsHashers(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>,\n hasherParams: TArg<BlsHasherParams>\n): BlsCurvePairWithHashers {\n const base = blsBasic(fields, G1_Point, G2_Point, params);\n // Missing map hooks intentionally fail closed via notImplemented on first hash use.\n const G1Hasher = createHasher(\n G1_Point,\n hasherParams.mapToG1 === undefined ? notImplemented : hasherParams.mapToG1,\n {\n ...hasherParams.hasherOpts,\n ...hasherParams.hasherOptsG1,\n }\n );\n const G2Hasher = createHasher(\n G2_Point,\n hasherParams.mapToG2 === undefined ? notImplemented : hasherParams.mapToG2,\n {\n ...hasherParams.hasherOpts,\n ...hasherParams.hasherOptsG2,\n }\n );\n return Object.freeze({ ...base, G1: G1Hasher, G2: G2Hasher });\n}\n\n// G1_Point: ProjConstructor<bigint>, G2_Point: ProjConstructor<Fp2>,\n// Rename to blsSignatures?\n/**\n * @param fields - Tower field implementations.\n * @param G1_Point - G1 point constructor.\n * @param G2_Point - G2 point constructor.\n * @param params - Pairing parameters. See {@link BlsPairingParams}.\n * @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}.\n * @param signatureCoders - Signature codecs.\n * @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs,\n * and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate\n * verification still requires proof of possession or another rogue-key defense from the caller.\n * @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error}\n * @example\n * ```ts\n * import { bls } from '@noble/curves/abstract/bls.js';\n * import { bls12_381 } from '@noble/curves/bls12-381.js';\n * const sigs = bls12_381.longSignatures;\n * // Use the full BLS helper set when you need hashing, keygen, signing, and verification.\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = sigs.hash(new TextEncoder().encode('hello noble'));\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function bls(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>,\n hasherParams: TArg<BlsHasherParams>,\n signatureCoders: BlsSignatureCoders\n): BlsCurvePairWithSignatures {\n const base = blsHashers(fields, G1_Point, G2_Point, params, hasherParams);\n const pairingRes: BlsPairing = {\n ...base,\n Fr: base.fields.Fr,\n Fp12: base.fields.Fp12,\n calcPairingPrecomputes: base.utils.calcPairingPrecomputes,\n randomSecretKey: base.utils.randomSecretKey,\n };\n const longSignatures = createBlsSig(\n pairingRes,\n G1_Point,\n G2_Point,\n false,\n base.G2.hashToCurve,\n signatureCoders?.LongSignature\n );\n const shortSignatures = createBlsSig(\n pairingRes,\n G2_Point,\n G1_Point,\n true,\n base.G1.hashToCurve,\n signatureCoders?.ShortSignature\n );\n return Object.freeze({ ...base, longSignatures, shortSignatures });\n}\n","/**\n * Towered extension fields.\n * Rather than implementing a massive 12th-degree extension directly, it is more efficient\n * to build it up from smaller extensions: a tower of extensions.\n *\n * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension,\n * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp.\n *\n * For more info: \"Pairings for beginners\" by Costello, section 7.3.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n aInRange,\n asafenumber,\n bitGet,\n bitLen,\n concatBytes,\n notImplemented,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport * as mod from './modular.ts';\nimport type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass.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), _3n = /* @__PURE__ */ BigInt(3), _6n = /* @__PURE__ */ BigInt(6), _12n = /* @__PURE__ */ BigInt(12);\n\n// Fp₂ over complex plane\n/** Pair of bigints used for quadratic-extension tuples. */\nexport type BigintTuple = [bigint, bigint];\n/** Prime-field element. */\nexport type Fp = bigint;\n// Finite extension field over irreducible polynominal.\n// Fp(u) / (u² - β) where β = -1\n/** Quadratic-extension field element `c0 + c1 * u`. */\nexport type Fp2 = {\n /** Real component. */\n c0: bigint;\n /** Imaginary component. */\n c1: bigint;\n};\n/** Six bigints used for sextic-extension tuples. */\nexport type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];\n/** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */\nexport type Fp6 = {\n /** Constant coefficient. */\n c0: Fp2;\n /** Linear coefficient. */\n c1: Fp2;\n /** Quadratic coefficient. */\n c2: Fp2;\n};\n/**\n * Degree-12 extension field element `c0 + c1 * w`.\n * Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v.\n */\nexport type Fp12 = {\n /** Constant coefficient. */\n c0: Fp6;\n /** Linear coefficient. */\n c1: Fp6;\n};\n// prettier-ignore\n/** Twelve bigints used for degree-12 extension tuples. */\nexport type BigintTwelve = [\n bigint, bigint, bigint, bigint, bigint, bigint,\n bigint, bigint, bigint, bigint, bigint, bigint\n];\n\nconst isObj = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object';\n\n/** BLS-friendly helpers on top of the quadratic extension field. */\nexport type Fp2Bls = mod.IField<Fp2> & {\n /** Underlying prime field. */\n Fp: mod.IField<Fp>;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp2, power: number): Fp2;\n /** Build one field element from a raw bigint tuple. */\n fromBigTuple(num: BigintTuple): Fp2;\n /** Multiply by the curve `b` constant. */\n mulByB: (num: Fp2) => Fp2;\n /** Multiply by the quadratic non-residue. */\n mulByNonresidue: (num: Fp2) => Fp2;\n /** Split one quadratic element into real and imaginary components. */\n reim: (num: Fp2) => { re: Fp; im: Fp };\n /** Specialized helper used by sextic squaring formulas. */\n Fp4Square: (a: Fp2, b: Fp2) => { first: Fp2; second: Fp2 };\n /** Quadratic non-residue used by the extension. */\n NONRESIDUE: Fp2;\n};\n\n/** BLS-friendly helpers on top of the sextic extension field. */\nexport type Fp6Bls = mod.IField<Fp6> & {\n /** Underlying quadratic extension field. */\n Fp2: Fp2Bls;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp6, power: number): Fp6;\n /** Build one field element from a raw six-bigint tuple. */\n fromBigSix: (tuple: BigintSix) => Fp6;\n /** Multiply by a sparse `(0, b1, 0)` sextic element. */\n mul1(num: Fp6, b1: Fp2): Fp6;\n /** Multiply by a sparse `(b0, b1, 0)` sextic element. */\n mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6;\n /** Multiply by one quadratic-extension element. */\n mulByFp2(lhs: Fp6, rhs: Fp2): Fp6;\n /** Multiply by the sextic non-residue. */\n mulByNonresidue: (num: Fp6) => Fp6;\n};\n\n/** BLS-friendly helpers on top of the degree-12 extension field. */\nexport type Fp12Bls = mod.IField<Fp12> & {\n /** Underlying sextic extension field. */\n Fp6: Fp6Bls;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp12, power: number): Fp12;\n /** Build one field element from a raw twelve-bigint tuple. */\n fromBigTwelve: (t: BigintTwelve) => Fp12;\n /** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */\n mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;\n /** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */\n mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;\n /** Multiply by one quadratic-extension element. */\n mulByFp2(lhs: Fp12, rhs: Fp2): Fp12;\n /** Conjugate one degree-12 element. */\n conjugate(num: Fp12): Fp12;\n /** Apply the final exponentiation from pairing arithmetic. */\n finalExponentiate(num: Fp12): Fp12;\n /** Apply one cyclotomic square. */\n _cyclotomicSquare(num: Fp12): Fp12;\n /** Apply one cyclotomic exponentiation. */\n _cyclotomicExp(num: Fp12, n: bigint): Fp12;\n};\n\nfunction calcFrobeniusCoefficients<T>(\n Fp: TArg<mod.IField<T>>,\n nonResidue: T,\n modulus: bigint,\n degree: number,\n num: number = 1,\n divisor?: number\n): T[][] {\n asafenumber(num, 'num');\n const F = Fp as mod.IField<T>;\n // Generic callers can hit empty / fractional row counts through `__TEST`; fail closed instead of\n // silently returning `[]` or deriving extra Frobenius rows from a truncated loop bound.\n if (num <= 0)\n throw new Error('calcFrobeniusCoefficients: expected positive row count, got ' + num);\n const _divisor = BigInt(divisor === undefined ? degree : divisor);\n const towerModulus: any = modulus ** BigInt(degree);\n const res: T[][] = [];\n // Derive tower-basis multipliers for the `p^k` Frobenius action. The\n // divisions below are expected to be exact for the chosen tower parameters.\n for (let i = 0; i < num; i++) {\n const a = BigInt(i + 1);\n const powers: T[] = [];\n for (let j = 0, qPower = _1n; j < degree; j++) {\n const numer = a * qPower - a;\n // Shipped towers divide cleanly here, but generic callers can pick bad\n // params. Bigint division would floor and derive the wrong Frobenius table.\n if (numer % _divisor) throw new Error('calcFrobeniusCoefficients: inexact tower exponent');\n const power = (numer / _divisor) % towerModulus;\n powers.push(F.pow(nonResidue, power));\n qPower *= modulus;\n }\n res.push(powers);\n }\n return res;\n}\n\nexport const __TEST: { calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients } =\n /* @__PURE__ */ Object.freeze({\n calcFrobeniusCoefficients,\n });\n\n// This works same at least for bls12-381, bn254 and bls12-377\n/**\n * @param Fp - Base field implementation.\n * @param Fp2 - Quadratic extension field.\n * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants.\n * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`.\n * @returns Frobenius endomorphism helpers.\n * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error}\n * @example\n * Build Frobenius endomorphism helpers for a BLS extension tower.\n *\n * ```ts\n * import { psiFrobenius } from '@noble/curves/abstract/tower.js';\n * import { bls12_381 } from '@noble/curves/bls12-381.js';\n * const Fp = bls12_381.fields.Fp;\n * const Fp2 = bls12_381.fields.Fp2;\n * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE));\n * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE);\n * ```\n */\nexport function psiFrobenius(\n Fp: TArg<mod.IField<Fp>>,\n Fp2: TArg<Fp2Bls>,\n base: TArg<Fp2>\n): {\n psi: (x: Fp2, y: Fp2) => [Fp2, Fp2];\n psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2];\n G2psi: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;\n G2psi2: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;\n PSI_X: Fp2;\n PSI_Y: Fp2;\n PSI2_X: Fp2;\n PSI2_Y: Fp2;\n} {\n // GLV endomorphism Ψ(P)\n const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3)\n const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2)\n function psi(x: Fp2, y: Fp2): [Fp2, Fp2] {\n // This x10 faster than previous version in bls12-381\n const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);\n const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);\n return [x2, y2];\n }\n // Ψ²(P) endomorphism (psi2(x) = psi(psi(x)))\n const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3)\n // Current towers rely on this landing on `-1`, which lets psi2 map `y` with\n // one negation instead of carrying a separate Frobenius multiplier.\n const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/2)\n if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) throw new Error('psiFrobenius: PSI2_Y!==-1');\n function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] {\n return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];\n }\n // Map points\n const mapAffine =\n <T>(fn: (x: T, y: T) => [T, T]) =>\n (c: WeierstrassPointCons<T>, P: WeierstrassPoint<T>) => {\n const affine = P.toAffine();\n const p = fn(affine.x, affine.y);\n return c.fromAffine({ x: p[0], y: p[1] });\n };\n const G2psi = mapAffine(psi);\n const G2psi2 = mapAffine(psi2);\n return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y };\n}\n\n/** Construction options for the BLS-style degree-12 tower. */\nexport type Tower12Opts = {\n /** Prime-field order. */\n ORDER: bigint;\n /** Bit length of the BLS parameter `x`. */\n X_LEN: number;\n /** Prime-field non-residue used by the quadratic extension. */\n NONRESIDUE?: Fp;\n /** Quadratic-extension non-residue used by the sextic tower. */\n FP2_NONRESIDUE: BigintTuple;\n /**\n * Optional custom quadratic square-root helper.\n * Receives one quadratic-extension element and returns one square root.\n */\n Fp2sqrt?: (num: Fp2) => Fp2;\n /**\n * Multiply one quadratic element by the curve `b` constant.\n * @param num - Quadratic-extension element to scale.\n * @returns Product by the curve `b` constant.\n */\n Fp2mulByB: (num: Fp2) => Fp2;\n /**\n * Final exponentiation used by pairing arithmetic.\n * @param num - Degree-12 field element to exponentiate.\n * @returns Pairing result after final exponentiation.\n */\n Fp12finalExponentiate: (num: Fp12) => Fp12;\n};\n\nclass _Field2 implements mod.IField<Fp2> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp2;\n readonly ONE: Fp2;\n readonly Fp: mod.IField<bigint>;\n\n readonly NONRESIDUE: Fp2;\n readonly mulByB: Tower12Opts['Fp2mulByB'];\n readonly Fp_NONRESIDUE: bigint;\n readonly Fp_div2: bigint;\n readonly FROBENIUS_COEFFICIENTS: readonly Fp[];\n\n constructor(\n Fp: mod.IField<bigint>,\n opts: Partial<{\n NONRESIDUE: bigint;\n FP2_NONRESIDUE: BigintTuple;\n Fp2mulByB: Tower12Opts['Fp2mulByB'];\n }> = {}\n ) {\n const { NONRESIDUE = BigInt(-1), FP2_NONRESIDUE, Fp2mulByB } = opts;\n const ORDER = Fp.ORDER;\n const FP2_ORDER = ORDER * ORDER;\n this.Fp = Fp;\n this.ORDER = FP2_ORDER;\n this.BITS = bitLen(FP2_ORDER);\n this.BYTES = Math.ceil(bitLen(FP2_ORDER) / 8);\n this.isLE = Fp.isLE;\n this.ZERO = this.create({ c0: Fp.ZERO, c1: Fp.ZERO });\n this.ONE = this.create({ c0: Fp.ONE, c1: Fp.ZERO });\n\n // These knobs only swap constants for the shipped quadratic tower shape:\n // arithmetic below assumes `u^2 = -1`, and bytes are handled as two adjacent\n // `Fp` limbs (`fromBytes` / `toBytes` expect the shipped `2 * Fp.BYTES` layout).\n this.Fp_NONRESIDUE = Fp.create(NONRESIDUE);\n this.Fp_div2 = Fp.div(Fp.ONE, _2n); // 1/2\n this.NONRESIDUE = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] });\n // const Fp2Nonresidue = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] });\n this.FROBENIUS_COEFFICIENTS = Object.freeze(\n calcFrobeniusCoefficients(Fp, this.Fp_NONRESIDUE, Fp.ORDER, 2)[0]\n );\n this.mulByB = (num) => {\n // This config hook is trusted to return a canonical Fp2 value already.\n // Copy+freeze it to keep the tower immutability invariant without mutating caller objects.\n const { c0, c1 } = Fp2mulByB!(num);\n return Object.freeze({ c0, c1 });\n };\n Object.freeze(this);\n }\n fromBigTuple(tuple: BigintTuple) {\n if (!Array.isArray(tuple) || tuple.length !== 2) throw new Error('invalid Fp2.fromBigTuple');\n const [c0, c1] = tuple;\n if (typeof c0 !== 'bigint' || typeof c1 !== 'bigint')\n throw new Error('invalid Fp2.fromBigTuple');\n return this.create({ c0, c1 });\n }\n create(num: Fp2) {\n const { Fp } = this;\n const c0 = Fp.create(num.c0);\n const c1 = Fp.create(num.c1);\n // Bigint field elements are immutable values, and higher-level code relies on\n // that invariant. Copy+freeze tower values too without mutating caller-owned objects.\n return Object.freeze({ c0, c1 });\n }\n isValid(num: Fp2) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1 } = num;\n const { Fp } = this;\n // Match base-field `isValid(...)`: malformed coordinate types are errors, not a `false`\n // predicate result.\n return Fp.isValid(c0) && Fp.isValid(c1);\n }\n is0(num: Fp2) {\n if (!isObj(num)) return false;\n const { c0, c1 } = num;\n const { Fp } = this;\n return Fp.is0(c0) && Fp.is0(c1);\n }\n isValidNot0(num: Fp2) {\n return !this.is0(num) && this.isValid(num);\n }\n eql({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) {\n const { Fp } = this;\n return Fp.eql(c0, r0) && Fp.eql(c1, r1);\n }\n neg({ c0, c1 }: Fp2) {\n const { Fp } = this;\n return Object.freeze({ c0: Fp.neg(c0), c1: Fp.neg(c1) });\n }\n pow(num: Fp2, power: bigint): Fp2 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp2[]): Fp2[] {\n return mod.FpInvertBatch(this, nums);\n }\n // Normalized\n add(f1: Fp2, f2: Fp2): Fp2 {\n const { Fp } = this;\n const { c0, c1 } = f1;\n const { c0: r0, c1: r1 } = f2;\n return Object.freeze({\n c0: Fp.add(c0, r0),\n c1: Fp.add(c1, r1),\n });\n }\n sub({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) {\n const { Fp } = this;\n return Object.freeze({\n c0: Fp.sub(c0, r0),\n c1: Fp.sub(c1, r1),\n });\n }\n mul({ c0, c1 }: Fp2, rhs: Fp2) {\n const { Fp } = this;\n if (typeof rhs === 'bigint') return Object.freeze({ c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) });\n // (a+bi)(c+di) = (ac−bd) + (ad+bc)i\n const { c0: r0, c1: r1 } = rhs;\n let t1 = Fp.mul(c0, r0); // c0 * o0\n let t2 = Fp.mul(c1, r1); // c1 * o1\n // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i\n const o0 = Fp.sub(t1, t2);\n const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));\n return Object.freeze({ c0: o0, c1: o1 });\n }\n sqr({ c0, c1 }: Fp2) {\n const { Fp } = this;\n const a = Fp.add(c0, c1);\n const b = Fp.sub(c0, c1);\n const c = Fp.add(c0, c0);\n return Object.freeze({ c0: Fp.mul(a, b), c1: Fp.mul(c, c1) });\n }\n // NonNormalized stuff\n addN(a: Fp2, b: Fp2): Fp2 {\n return this.add(a, b);\n }\n subN(a: Fp2, b: Fp2): Fp2 {\n return this.sub(a, b);\n }\n mulN(a: Fp2, b: Fp2): Fp2 {\n return this.mul(a, b);\n }\n sqrN(a: Fp2): Fp2 {\n return this.sqr(a);\n }\n // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?\n div(lhs: Fp2, rhs: Fp2): Fp2 {\n const { Fp } = this;\n // @ts-ignore\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n inv({ c0: a, c1: b }: Fp2): Fp2 {\n // We wish to find the multiplicative inverse of a nonzero\n // element a + bu in Fp2. We leverage an identity\n //\n // (a + bu)(a - bu) = a² + b²\n //\n // which holds because u² = -1. This can be rewritten as\n //\n // (a + bu)(a - bu)/(a² + b²) = 1\n //\n // because a² + b² = 0 has no nonzero solutions for (a, b).\n // This gives that (a - bu)/(a² + b²) is the inverse\n // of (a + bu). Importantly, this can be computing using\n // only a single inversion in Fp.\n const { Fp } = this;\n const factor = Fp.inv(Fp.create(a * a + b * b));\n return Object.freeze({ c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) });\n }\n sqrt(num: Fp2) {\n // This is generic for all quadratic extensions (Fp2)\n const { Fp } = this;\n const Fp2 = this;\n const { c0, c1 } = num;\n if (Fp.is0(c1)) {\n // if c0 is quadratic residue\n if (mod.FpLegendre(Fp, c0) === 1) return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO });\n else return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, this.Fp_NONRESIDUE)) });\n }\n const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), this.Fp_NONRESIDUE)));\n let d = Fp.mul(Fp.add(a, c0), this.Fp_div2);\n const legendre = mod.FpLegendre(Fp, d);\n // -1, Quadratic non residue\n if (legendre === -1) d = Fp.sub(d, a);\n const a0 = Fp.sqrt(d);\n const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, this.Fp_div2), a0) });\n if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) throw new Error('Cannot find square root');\n // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num\n const x1 = candidateSqrt;\n const x2 = Fp2.neg(x1);\n const { re: re1, im: im1 } = Fp2.reim(x1);\n const { re: re2, im: im2 } = Fp2.reim(x2);\n if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1;\n return x2;\n }\n // Same as sgn0_m_eq_2 in RFC 9380\n isOdd(x: Fp2) {\n const { re: x0, im: x1 } = this.reim(x);\n const sign_0 = x0 % _2n;\n const zero_0 = x0 === _0n;\n const sign_1 = x1 % _2n;\n return BigInt(sign_0 || (zero_0 && sign_1)) == _1n;\n }\n // Bytes util\n fromBytes(b: Uint8Array): Fp2 {\n const { Fp } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n return this.create({\n c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)),\n c1: Fp.fromBytes(b.subarray(Fp.BYTES)),\n });\n }\n toBytes({ c0, c1 }: Fp2): Uint8Array {\n return concatBytes(this.Fp.toBytes(c0), this.Fp.toBytes(c1));\n }\n cmov({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2, c: boolean) {\n const { Fp } = this;\n return this.create({\n c0: Fp.cmov(c0, r0, c),\n c1: Fp.cmov(c1, r1, c),\n });\n }\n reim({ c0, c1 }: Fp2) {\n return { re: c0, im: c1 };\n }\n Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } {\n const Fp2 = this;\n const a2 = Fp2.sqr(a);\n const b2 = Fp2.sqr(b);\n return {\n first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a²\n second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b²\n };\n }\n // multiply by u + 1\n mulByNonresidue({ c0, c1 }: Fp2) {\n return this.mul({ c0, c1 }, this.NONRESIDUE);\n }\n frobeniusMap({ c0, c1 }: Fp2, power: number): Fp2 {\n return Object.freeze({\n c0,\n c1: this.Fp.mul(c1, this.FROBENIUS_COEFFICIENTS[power % 2]),\n });\n }\n}\n\nclass _Field6 implements Fp6Bls {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp6;\n readonly ONE: Fp6;\n readonly Fp2: Fp2Bls;\n\n constructor(Fp2: Fp2Bls) {\n this.Fp2 = Fp2;\n // `IField.ORDER` is the field cardinality `q`; for sextic extensions that is `p^6`.\n // Generic helpers like Frobenius-style `x^q = x` checks rely on the literal field size here.\n this.ORDER = Fp2.Fp.ORDER ** _6n;\n this.BITS = 3 * Fp2.BITS;\n this.BYTES = 3 * Fp2.BYTES;\n this.isLE = Fp2.isLE;\n this.ZERO = this.create({ c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO });\n this.ONE = this.create({ c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO });\n Object.freeze(this);\n }\n // Most callers never touch Frobenius maps, so keep the sextic tables lazy:\n // eagerly deriving them dominates `bls12-381.js` / `bn254.js` import time.\n get FROBENIUS_COEFFICIENTS_1(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_6.get(this);\n if (frob) return frob[0];\n const { Fp2 } = this;\n const { Fp } = Fp2;\n const rows = calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 6, 2, 3);\n const cache = [Object.freeze(rows[0]), Object.freeze(rows[1])] as const;\n _FROBENIUS_COEFFICIENTS_6.set(this, cache);\n return cache[0];\n }\n get FROBENIUS_COEFFICIENTS_2(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_6.get(this);\n if (frob) return frob[1];\n void this.FROBENIUS_COEFFICIENTS_1;\n return _FROBENIUS_COEFFICIENTS_6.get(this)![1];\n }\n add({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.add(c0, r0),\n c1: Fp2.add(c1, r1),\n c2: Fp2.add(c2, r2),\n });\n }\n sub({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.sub(c0, r0),\n c1: Fp2.sub(c1, r1),\n c2: Fp2.sub(c2, r2),\n });\n }\n mul({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) {\n const { Fp2 } = this;\n if (typeof rhs === 'bigint') {\n return Object.freeze({\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n });\n }\n const { c0: r0, c1: r1, c2: r2 } = rhs;\n const t0 = Fp2.mul(c0, r0); // c0 * o0\n const t1 = Fp2.mul(c1, r1); // c1 * o1\n const t2 = Fp2.mul(c2, r2); // c2 * o2\n return Object.freeze({\n // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)\n c0: Fp2.add(\n t0,\n Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))\n ),\n // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)\n c1: Fp2.add(\n Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)),\n Fp2.mulByNonresidue(t2)\n ),\n // T1 + (c0 + c2) * (r0 + r2) - T0 + T2\n c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)),\n });\n }\n sqr({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n let t0 = Fp2.sqr(c0); // c0²\n let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1\n let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2\n let t4 = Fp2.sqr(c2); // c2²\n return Object.freeze({\n c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0\n c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1\n // T1 + (c0 - c1 + c2)² + T3 - T0 - T4\n c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4),\n });\n }\n addN(a: Fp6, b: Fp6): Fp6 {\n return this.add(a, b);\n }\n subN(a: Fp6, b: Fp6): Fp6 {\n return this.sub(a, b);\n }\n mulN(a: Fp6, b: Fp6): Fp6 {\n return this.mul(a, b);\n }\n sqrN(a: Fp6): Fp6 {\n return this.sqr(a);\n }\n\n create(num: Fp6) {\n const { Fp2 } = this;\n const c0 = Fp2.create(num.c0);\n const c1 = Fp2.create(num.c1);\n const c2 = Fp2.create(num.c2);\n return Object.freeze({ c0, c1, c2 });\n }\n\n isValid(num: Fp6) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1, c2 } = num;\n const { Fp2 } = this;\n return Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2);\n }\n is0(num: Fp6) {\n if (!isObj(num)) return false;\n const { c0, c1, c2 } = num;\n const { Fp2 } = this;\n return Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2);\n }\n isValidNot0(num: Fp6) {\n return !this.is0(num) && this.isValid(num);\n }\n neg({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) });\n }\n eql({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2);\n }\n sqrt(_: Fp6) {\n // Sextic extensions can use generic odd-field Tonelli-Shanks, but the helper must work\n // over `IField<T>` with a quadratic non-residue from Fp6 itself. The current\n // `mod.tonelliShanks(P)` precomputation only searches integer residues in the base field.\n return notImplemented();\n }\n // Do we need division by bigint at all? Should be done via order:\n div(lhs: Fp6, rhs: Fp6) {\n const { Fp2 } = this;\n const { Fp } = Fp2;\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n pow(num: Fp6, power: Fp): Fp6 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp6[]): Fp6[] {\n return mod.FpInvertBatch(this, nums);\n }\n\n inv({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1)\n let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1\n let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2\n // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)\n let t4 = Fp2.inv(\n Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))\n );\n return Object.freeze({ c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) });\n }\n // Bytes utils\n fromBytes(b: Uint8Array): Fp6 {\n const { Fp2 } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n const B2 = Fp2.BYTES;\n return this.create({\n c0: Fp2.fromBytes(b.subarray(0, B2)),\n c1: Fp2.fromBytes(b.subarray(B2, B2 * 2)),\n c2: Fp2.fromBytes(b.subarray(2 * B2)),\n });\n }\n toBytes({ c0, c1, c2 }: Fp6): Uint8Array {\n const { Fp2 } = this;\n return concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2));\n }\n cmov({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c: boolean) {\n const { Fp2 } = this;\n return this.create({\n c0: Fp2.cmov(c0, r0, c),\n c1: Fp2.cmov(c1, r1, c),\n c2: Fp2.cmov(c2, r2, c),\n });\n }\n fromBigSix(tuple: BigintSix): Fp6 {\n const { Fp2 } = this;\n if (!Array.isArray(tuple) || tuple.length !== 6) throw new Error('invalid Fp6.fromBigSix');\n for (let i = 0; i < 6; i++)\n if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp6.fromBigSix');\n const t = tuple;\n return this.create({\n c0: Fp2.fromBigTuple(t.slice(0, 2) as BigintTuple),\n c1: Fp2.fromBigTuple(t.slice(2, 4) as BigintTuple),\n c2: Fp2.fromBigTuple(t.slice(4, 6) as BigintTuple),\n });\n }\n frobeniusMap({ c0, c1, c2 }: Fp6, power: number) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.frobeniusMap(c0, power),\n c1: Fp2.mul(Fp2.frobeniusMap(c1, power), this.FROBENIUS_COEFFICIENTS_1[power % 6]),\n c2: Fp2.mul(Fp2.frobeniusMap(c2, power), this.FROBENIUS_COEFFICIENTS_2[power % 6]),\n });\n }\n mulByFp2({ c0, c1, c2 }: Fp6, rhs: Fp2): Fp6 {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n });\n }\n mulByNonresidue({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 });\n }\n // Sparse multiplication\n mul1({ c0, c1, c2 }: Fp6, b1: Fp2): Fp6 {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),\n c1: Fp2.mul(c0, b1),\n c2: Fp2.mul(c1, b1),\n });\n }\n // Sparse multiplication\n mul01({ c0, c1, c2 }: Fp6, b0: Fp2, b1: Fp2): Fp6 {\n const { Fp2 } = this;\n let t0 = Fp2.mul(c0, b0); // c0 * b0\n let t1 = Fp2.mul(c1, b1); // c1 * b1\n return Object.freeze({\n // ((c1 + c2) * b1 - T1) * (u + 1) + T0\n c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),\n // (b0 + b1) * (c0 + c1) - T0 - T1\n c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),\n // (c0 + c2) * b0 - T0 + T1\n c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1),\n });\n }\n}\n\n// Keep lazy tower caches off-object: field instances stay frozen, and debugger output\n// stays readable without JS private slots while second/subsequent lookups still hit cache.\nconst _FROBENIUS_COEFFICIENTS_6 = new WeakMap<_Field6, readonly [readonly Fp2[], readonly Fp2[]]>();\n\nclass _Field12 implements Fp12Bls {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp12;\n readonly ONE: Fp12;\n\n readonly Fp6: Fp6Bls;\n readonly X_LEN: number;\n readonly finalExponentiate: Tower12Opts['Fp12finalExponentiate'];\n\n constructor(Fp6: Fp6Bls, opts: Tower12Opts) {\n const { X_LEN, Fp12finalExponentiate } = opts;\n const { Fp2 } = Fp6;\n const { Fp } = Fp2;\n this.Fp6 = Fp6;\n\n // `IField.ORDER` is the field cardinality `q`; for degree-12 extensions that is `p^12`.\n // Keeping `p^2` here breaks generic field identities like `x^q = x` on Fp12.\n this.ORDER = Fp.ORDER ** _12n;\n this.BITS = 2 * Fp6.BITS;\n this.BYTES = 2 * Fp6.BYTES;\n this.isLE = Fp6.isLE;\n // Returned tower values are frozen, so larger constants can safely reuse\n // already-frozen child coefficients instead of cloning them.\n this.ZERO = this.create({ c0: Fp6.ZERO, c1: Fp6.ZERO });\n this.ONE = this.create({ c0: Fp6.ONE, c1: Fp6.ZERO });\n this.X_LEN = X_LEN;\n this.finalExponentiate = (num) => {\n const copy2 = ({ c0, c1 }: Fp2): Fp2 => Object.freeze({ c0, c1 });\n const copy6 = ({ c0, c1, c2 }: Fp6): Fp6 =>\n Object.freeze({ c0: copy2(c0), c1: copy2(c1), c2: copy2(c2) });\n // This config hook is trusted to return a canonical Fp12 value already.\n // Copy+freeze it to keep the tower immutability invariant without mutating caller objects.\n const res = Fp12finalExponentiate(num);\n return Object.freeze({ c0: copy6(res.c0), c1: copy6(res.c1) });\n };\n Object.freeze(this);\n }\n // Keep the degree-12 Frobenius row lazy too; after the first lookup the cached\n // array is reused exactly like the old eager table.\n get FROBENIUS_COEFFICIENTS(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_12.get(this);\n if (frob) return frob;\n const { Fp2 } = this.Fp6;\n const { Fp } = Fp2;\n const cache = Object.freeze(\n calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 12, 1, 6)[0]\n );\n _FROBENIUS_COEFFICIENTS_12.set(this, cache);\n return cache;\n }\n create(num: Fp12) {\n const { Fp6 } = this;\n const c0 = Fp6.create(num.c0);\n const c1 = Fp6.create(num.c1);\n return Object.freeze({ c0, c1 });\n }\n isValid(num: Fp12) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1 } = num;\n const { Fp6 } = this;\n return Fp6.isValid(c0) && Fp6.isValid(c1);\n }\n is0(num: Fp12) {\n if (!isObj(num)) return false;\n const { c0, c1 } = num;\n const { Fp6 } = this;\n return Fp6.is0(c0) && Fp6.is0(c1);\n }\n isValidNot0(num: Fp12) {\n return !this.is0(num) && this.isValid(num);\n }\n neg({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) });\n }\n eql({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Fp6.eql(c0, r0) && Fp6.eql(c1, r1);\n }\n sqrt(_: Fp12): Fp12 {\n // Fp12 is quadratic over Fp6, so a dedicated quadratic-extension sqrt is possible here\n // once Fp6.sqrt() exists. Without that lower-level sqrt, only a field-generic\n // Tonelli-Shanks path over Fp12 itself would work.\n return notImplemented();\n }\n inv({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v)\n // ((C0 * T) * T) + (-C1 * T) * w\n return Object.freeze({ c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) });\n }\n div(lhs: Fp12, rhs: Fp12) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { Fp } = Fp2;\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n pow(num: Fp12, power: bigint): Fp12 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp12[]): Fp12[] {\n return mod.FpInvertBatch(this, nums);\n }\n\n // Normalized\n add({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.add(c0, r0),\n c1: Fp6.add(c1, r1),\n });\n }\n sub({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.sub(c0, r0),\n c1: Fp6.sub(c1, r1),\n });\n }\n mul({ c0, c1 }: Fp12, rhs: Fp12 | bigint) {\n const { Fp6 } = this;\n if (typeof rhs === 'bigint')\n return Object.freeze({ c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) });\n let { c0: r0, c1: r1 } = rhs;\n let t1 = Fp6.mul(c0, r0); // c0 * r0\n let t2 = Fp6.mul(c1, r1); // c1 * r1\n return Object.freeze({\n c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v\n // (c0 + c1) * (r0 + r1) - (T1 + T2)\n c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)),\n });\n }\n sqr({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n let ab = Fp6.mul(c0, c1); // c0 * c1\n return Object.freeze({\n // (c1 * v + c0) * (c0 + c1) - AB - AB * v\n c0: Fp6.sub(\n Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab),\n Fp6.mulByNonresidue(ab)\n ),\n c1: Fp6.add(ab, ab),\n }); // AB + AB\n }\n // NonNormalized stuff\n addN(a: Fp12, b: Fp12): Fp12 {\n return this.add(a, b);\n }\n subN(a: Fp12, b: Fp12): Fp12 {\n return this.sub(a, b);\n }\n mulN(a: Fp12, b: Fp12): Fp12 {\n return this.mul(a, b);\n }\n sqrN(a: Fp12): Fp12 {\n return this.sqr(a);\n }\n\n // Bytes utils\n fromBytes(b: Uint8Array): Fp12 {\n const { Fp6 } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n return this.create({\n c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),\n c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)),\n });\n }\n toBytes({ c0, c1 }: Fp12): Uint8Array {\n const { Fp6 } = this;\n return concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1));\n }\n cmov({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12, c: boolean) {\n const { Fp6 } = this;\n return this.create({\n c0: Fp6.cmov(c0, r0, c),\n c1: Fp6.cmov(c1, r1, c),\n });\n }\n // Utils\n // toString() {\n // return '' + 'Fp12(' + this.c0 + this.c1 + '* w');\n // },\n // fromTuple(c: [Fp6, Fp6]) {\n // return new Fp12(...c);\n // }\n fromBigTwelve(tuple: BigintTwelve): Fp12 {\n const { Fp6 } = this;\n if (!Array.isArray(tuple) || tuple.length !== 12) throw new Error('invalid Fp12.fromBigTwelve');\n for (let i = 0; i < 12; i++)\n if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp12.fromBigTwelve');\n const t = tuple;\n return this.create({\n c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix),\n c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix),\n });\n }\n // Raises to q**i -th power\n frobeniusMap(lhs: Fp12, power: number) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);\n const coeff = this.FROBENIUS_COEFFICIENTS[power % 12];\n return Object.freeze({\n c0: Fp6.frobeniusMap(lhs.c0, power),\n c1: Object.freeze({\n c0: Fp2.mul(c0, coeff),\n c1: Fp2.mul(c1, coeff),\n c2: Fp2.mul(c2, coeff),\n }),\n });\n }\n mulByFp2({ c0, c1 }: Fp12, rhs: Fp2): Fp12 {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.mulByFp2(c0, rhs),\n c1: Fp6.mulByFp2(c1, rhs),\n });\n }\n conjugate({ c0, c1 }: Fp12): Fp12 {\n // Reuse `c0` by reference and only negate the `w` coefficient.\n return Object.freeze({ c0, c1: this.Fp6.neg(c1) });\n }\n // Sparse multiplication\n mul014({ c0, c1 }: Fp12, o0: Fp2, o1: Fp2, o4: Fp2) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n let t0 = Fp6.mul01(c0, o0, o1);\n let t1 = Fp6.mul1(c1, o4);\n return Object.freeze({\n c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0\n // (c1 + c0) * [o0, o1+o4] - T0 - T1\n c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1),\n });\n }\n mul034({ c0, c1 }: Fp12, o0: Fp2, o3: Fp2, o4: Fp2) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const a = Object.freeze({\n c0: Fp2.mul(c0.c0, o0),\n c1: Fp2.mul(c0.c1, o0),\n c2: Fp2.mul(c0.c2, o0),\n });\n const b = Fp6.mul01(c1, o3, o4);\n const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4);\n return Object.freeze({\n c0: Fp6.add(Fp6.mulByNonresidue(b), a),\n c1: Fp6.sub(e, Fp6.add(a, b)),\n });\n }\n\n // A cyclotomic group is a subgroup of Fp^n defined by\n // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}\n // The result of any pairing is in a cyclotomic subgroup\n // https://eprint.iacr.org/2009/565.pdf\n // https://eprint.iacr.org/2010/354.pdf\n _cyclotomicSquare({ c0, c1 }: Fp12): Fp12 {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;\n const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;\n const { first: t3, second: t4 } = Fp2.Fp4Square(c0c0, c1c1);\n const { first: t5, second: t6 } = Fp2.Fp4Square(c1c0, c0c2);\n const { first: t7, second: t8 } = Fp2.Fp4Square(c0c1, c1c2);\n const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1)\n return Object.freeze({\n c0: Object.freeze({\n c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3\n c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5\n c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7),\n }), // 2 * (T7 - c0c2) + T7\n c1: Object.freeze({\n c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9\n c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4\n c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6),\n }),\n }); // 2 * (T6 + c1c2) + T6\n }\n // https://eprint.iacr.org/2009/565.pdf\n _cyclotomicExp(num: Fp12, n: bigint): Fp12 {\n // The loop only consumes `X_LEN` bits, so out-of-range exponents would otherwise get silently\n // truncated (or sign-extended for negatives) instead of matching the caller's requested power.\n aInRange('cyclotomic exponent', n, _0n, _1n << BigInt(this.X_LEN));\n let z = this.ONE;\n for (let i = this.X_LEN - 1; i >= 0; i--) {\n z = this._cyclotomicSquare(z);\n if (bitGet(n, i)) z = this.mul(z, num);\n }\n return z;\n }\n}\n\nconst _FROBENIUS_COEFFICIENTS_12 = new WeakMap<_Field12, readonly Fp2[]>();\n\n/**\n * @param opts - Tower construction options. See {@link Tower12Opts}.\n * @returns BLS tower fields.\n * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error}\n * @example\n * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve.\n *\n * ```ts\n * const fields = tower12({\n * ORDER: 17n,\n * X_LEN: 4,\n * FP2_NONRESIDUE: [1n, 1n],\n * Fp2mulByB: (num) => num,\n * Fp12finalExponentiate: (num) => num,\n * });\n * const fp12 = fields.Fp12.ONE;\n * ```\n */\nexport function tower12(opts: TArg<Tower12Opts>): TRet<{\n Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n}> {\n validateObject(\n opts,\n {\n ORDER: 'bigint',\n X_LEN: 'number',\n FP2_NONRESIDUE: 'object',\n Fp2mulByB: 'function',\n Fp12finalExponentiate: 'function',\n },\n { NONRESIDUE: 'bigint' }\n );\n asafenumber(opts.X_LEN, 'X_LEN');\n if (opts.X_LEN < 1) throw new Error('invalid X_LEN');\n const nonresidue = opts.FP2_NONRESIDUE as bigint[];\n if (!Array.isArray(nonresidue) || nonresidue.length !== 2)\n throw new Error('invalid FP2_NONRESIDUE');\n if (typeof nonresidue[0] !== 'bigint' || typeof nonresidue[1] !== 'bigint')\n throw new Error('invalid FP2_NONRESIDUE');\n const Fp = mod.Field(opts.ORDER);\n const Fp2 = new _Field2(Fp, opts);\n const Fp6 = new _Field6(Fp2);\n const Fp12 = new _Field12(Fp6, opts);\n return { Fp, Fp2, Fp6, Fp12 } as TRet<{\n Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n }>;\n}\n","/**\n * bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to:\n\n* Construct zk-SNARKs at the ~120-bit security, as per [Barbulescu-Duquesne 2017](https://hal.science/hal-01534101/file/main.pdf)\n* Efficiently verify N aggregate signatures with 1 pairing and N ec additions:\nthe Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr\n\nBLS can mean 2 different things:\n\n* Barreto-Lynn-Scott: BLS12, a Pairing Friendly Elliptic Curve\n* Boneh-Lynn-Shacham: A Signature Scheme.\n\n### Summary\n\n1. BLS Relies on expensive bilinear pairing\n2. Secret Keys: 32 bytes\n3. Public Keys: 48 OR 96 bytes - big-endian x coordinate of point on G1 OR G2 curve\n4. Signatures: 96 OR 48 bytes - big-endian x coordinate of point on G2 OR G1 curve\n5. The 12 stands for the Embedding degree.\n\nModes of operation:\n\n* Long signatures: 48-byte keys + 96-byte sigs (G1 keys + G2 sigs).\n* Short signatures: 96-byte keys + 48-byte sigs (G2 keys + G1 sigs).\n\n### Formulas\n\n- `P = pk x G` - public keys\n- `S = pk x H(m)` - signing, uses hash-to-curve on m\n- `e(P, H(m)) == e(G, S)` - verification using pairings\n- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation\n\n### Curves\n\nG1 is ordinary elliptic curve. G2 is extension field curve, think \"over complex numbers\".\n\n- G1: y² = x³ + 4\n- G2: y² = x³ + 4(u + 1) where u = √−1; r-order subgroup of E'(Fp²), M-type twist\n\n### Towers\n\nPairing G1 + G2 produces element in Fp₁₂, 12-degree polynomial.\nFp₁₂ is usually implemented using tower of lower-degree polynomials for speed.\n\n- Fp₁₂ = Fp₆² => Fp₂³\n- Fp(u) / (u² - β) where β = -1\n- Fp₂(v) / (v³ - ξ) where ξ = u + 1\n- Fp₆(w) / (w² - γ) where γ = v\n- Fp²[u] = Fp/u²+1\n- Fp⁶[v] = Fp²/v³-1-u\n- Fp¹²[w] = Fp⁶/w²-v\n\n### Params\n\n* Embedding degree (k): 12\n* Seed is sometimes named x or t\n* t = -15132376222941642752\n* p = (t-1)² * (t⁴-t²+1)/3 + t\n* r = t⁴-t²+1\n* Ate loop size: X\n\nTo verify curve parameters, see\n[pairing-friendly-curves spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11).\nBasic math is done over finite fields over p.\nMore complicated math is done over polynominal extension fields.\n\n### Compatibility and notes\n1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC.\nFilecoin uses little endian byte arrays for secret keys - make sure to reverse byte order.\n2. Make sure to correctly select mode: \"long signature\" or \"short signature\".\n3. Compatible with specs:\n RFC 9380,\n [cfrg-pairing-friendly-curves-11](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11),\n [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/).\n\n *\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bls, type BlsCurvePairWithSignatures } from './abstract/bls.ts';\nimport { Field, type IField } from './abstract/modular.ts';\nimport {\n abytes,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n copyBytes,\n hexToBytes,\n numberToBytesBE,\n randomBytes,\n type TArg,\n type TRet,\n} from './utils.ts';\n// Types\nimport { isogenyMap } from './abstract/hash-to-curve.ts';\nimport type { BigintTuple, Fp, Fp12, Fp2, Fp6 } from './abstract/tower.ts';\nimport { psiFrobenius, tower12 } from './abstract/tower.ts';\nimport {\n mapToCurveSimpleSWU,\n weierstrass,\n type AffinePoint,\n type WeierstrassOpts,\n type WeierstrassPoint,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\n// To verify math:\n// https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11\n\n// The BLS parameter x (seed) for BLS12-381. The stored constant is `|x|`; call\n// sites that need the signed parameter apply the minus sign themselves.\n// x = -2^63 - 2^62 - 2^60 - 2^57 - 2^48 - 2^16\nconst BLS_X = BigInt('0xd201000000010000');\n// t = x (called differently in different places)\n// const t = -BLS_X;\nconst BLS_X_LEN = bitLen(BLS_X);\n\n// a=0, b=4\n// P is characteristic of field Fp, in which curve calculations are done.\n// p = (t-1)² * (t⁴-t²+1)/3 + t\n// bls12_381_Fp = (t-1n)**2n * (t**4n - t**2n + 1n) / 3n + t\n// r*h is curve order, amount of points on curve,\n// where r is order of prime subgroup and h is cofactor.\n// r = t⁴-t²+1\n// r = (t**4n - t**2n + 1n)\n// cofactor h of G1: (t - 1)²/3, with the signed convention `t = -x`\n// cofactorG1 = (t-1n)**2n/3n\n// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507\n// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569\nconst bls12_381_CURVE_G1: WeierstrassOpts<bigint> = {\n p: BigInt(\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'\n ),\n n: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'),\n h: BigInt('0x396c8c005555e1568c00aaab0000aaab'),\n a: _0n,\n b: _4n,\n Gx: BigInt(\n '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'\n ),\n Gy: BigInt(\n '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'\n ),\n};\n\n// CURVE FIELDS\n// r = z⁴ − z² + 1; CURVE.n from other curves\n/**\n * bls12-381 Fr (Fn) field.\n * `fromBytes()` reduces modulo `q` instead of rejecting non-canonical encodings.\n */\nexport const bls12_381_Fr: TRet<IField<bigint>> = Field(bls12_381_CURVE_G1.n, {\n modFromBytes: true,\n}) as TRet<IField<bigint>>;\nconst { Fp, Fp2, Fp6, Fp12 } = tower12({\n ORDER: bls12_381_CURVE_G1.p,\n X_LEN: BLS_X_LEN,\n // Finite extension field over irreducible polynominal.\n // Fp(u) / (u² - β) where β = -1\n // Public `Fp2.NONRESIDUE` below is the sextic-tower value `(1, 1) = u + 1`;\n // the quadratic non-residue for the base Fp2 construction is still `-1`.\n FP2_NONRESIDUE: [_1n, _1n],\n Fp2mulByB: ({ c0, c1 }: Fp2) => {\n const t0 = Fp.mul(c0, _4n); // 4 * c0\n const t1 = Fp.mul(c1, _4n); // 4 * c1\n // (T0-T1) + (T0+T1)*i\n return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };\n },\n Fp12finalExponentiate: (num: Fp12) => {\n const x = BLS_X;\n // this^(q⁶) / this\n const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);\n // t0^(q²) * t0\n const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);\n const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));\n const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);\n const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));\n const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));\n const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));\n const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));\n const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);\n const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);\n const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);\n const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);\n // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1\n return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);\n },\n});\n\n// GLV endomorphism Ψ(P), for fast cofactor clearing. `Fp2.NONRESIDUE` here is\n// the tower value `u + 1`, so the Frobenius base passed to psiFrobenius is\n// `1 / (u + 1)`, and psi2 derives the published `1 / 2^((p - 1) / 3)` constant internally.\nlet frob: ReturnType<typeof psiFrobenius> | undefined;\nconst getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)));\n// Eager psiFrobenius setup now dominates `bls12-381.js` import, so defer it to\n// first use. After that these locals are rewritten to the direct helper refs.\nlet G2psi: ReturnType<typeof psiFrobenius>['G2psi'] = (c, P) => {\n const fn = getFrob().G2psi;\n G2psi = fn;\n return fn(c, P);\n};\nlet G2psi2: ReturnType<typeof psiFrobenius>['G2psi2'] = (c, P) => {\n const fn = getFrob().G2psi2;\n G2psi2 = fn;\n return fn(c, P);\n};\n\n/**\n * Default hash_to_field / hash-to-curve for BLS.\n * m: 1 for G1, 2 for G2\n * k: target security level in bits\n * hash: any function, e.g. BBS+ uses BLAKE2: see [github](https://github.com/hyperledger/aries-framework-go/issues/2247).\n * Field/hash parameters come from [section 8.8.2 of RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2),\n * but the `DST` / `encodeDST` strings below are the BLS-signature-suite override.\n */\nconst hasher_opts = Object.freeze({\n DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n p: Fp.ORDER,\n m: 2,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n});\n\n// a=0, b=4\n// cofactor h of G2, derived with the signed convention `t = -x`\n// (t^8 - 4t^7 + 5t^6 - 4t^4 + 6t^3 - 4t^2 - 4t + 13)/9\n// cofactorG2 = (t**8n - 4n*t**7n + 5n*t**6n - 4n*t**4n + 6n*t**3n - 4n*t**2n - 4n*t+13n)/9n\n// x = 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160\n// y = 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905\nconst bls12_381_CURVE_G2 = {\n p: Fp2.ORDER,\n n: bls12_381_CURVE_G1.n,\n h: BigInt(\n '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'\n ),\n a: Fp2.ZERO,\n b: Fp2.fromBigTuple([_4n, _4n]),\n Gx: Fp2.fromBigTuple([\n BigInt(\n '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'\n ),\n BigInt(\n '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'\n ),\n ]),\n Gy: Fp2.fromBigTuple([\n BigInt(\n '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'\n ),\n BigInt(\n '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'\n ),\n ]),\n};\n\n// Encoding utils\nconst sortBit = (parts: bigint[], p: bigint) => {\n for (const part of parts) {\n if (part !== _0n) return Boolean((part * _2n) / p);\n }\n return false;\n};\nconst fp2 = {\n // Generic tower bytes use `c0 || c1`, but the BLS12-381 G2 point/signature wire encoding uses\n // `c1 || c0`, so keep this local wrapper instead of changing generic field serialization.\n encode({ c0, c1 }: Fp2): TRet<Uint8Array> {\n const { BYTES: L } = Fp;\n return concatBytes(numberToBytesBE(c1, L), numberToBytesBE(c0, L)) as TRet<Uint8Array>;\n },\n decode(bytes: TArg<Uint8Array>) {\n const { BYTES: L } = Fp;\n return Fp2.create({\n c0: Fp.create(bytesToNumberBE(bytes.subarray(L))),\n c1: Fp.create(bytesToNumberBE(bytes.subarray(0, L))),\n });\n },\n};\nconst BaseFp = Fp;\ntype Mask = { compressed: boolean; infinity: boolean; sort: boolean };\n// Keep BLS12-381 point/signature codecs on one control-flow skeleton: the G1/G2\n// and point/signature variants differ only in field packing, subgroup bytes, and\n// whether uncompressed form is allowed. Copy-paste decoders were diverging.\nconst coder = <T>(\n name: 'G1' | 'G2',\n Fp: TArg<IField<T>>,\n b: T,\n encode: TArg<(v: T) => TRet<Uint8Array>>,\n decode: TArg<(bytes: TArg<Uint8Array>) => T>,\n yparts: (y: T) => bigint[]\n) => {\n const F = Fp as IField<T>;\n const enc = encode as (v: T) => TRet<Uint8Array>;\n const dec = decode as (bytes: TArg<Uint8Array>) => T;\n const W = F.BYTES;\n return (allowUncompressed: boolean) => ({\n encode(point: WeierstrassPoint<T>, compressed = true): TRet<Uint8Array> {\n if (!compressed && !allowUncompressed)\n throw new Error('invalid signature: expected compressed encoding');\n const infinity = point.is0();\n const { x, y } = point.toAffine();\n const bytes = compressed ? enc(x) : concatBytes(enc(x), enc(y));\n let sort;\n if (compressed && !infinity) sort = sortBit(yparts(y), BaseFp.ORDER);\n return setMask(bytes, { compressed, infinity, sort }) as TRet<Uint8Array>;\n },\n decode(bytes: TArg<Uint8Array>): AffinePoint<T> {\n const raw = allowUncompressed\n ? abytes(bytes, undefined, 'point')\n : abytes(bytes, W, 'signature');\n const { compressed, infinity, sort, value } = parseMask(raw);\n if (!allowUncompressed && !compressed)\n throw new Error('invalid signature: expected compressed encoding');\n const len = compressed ? W : 2 * W;\n if (value.length !== len) throw new Error(`invalid ${name} point: expected ${len} bytes`);\n if (infinity) {\n // Infinity canonicality has to be checked on raw bytes before decode()\n // reduces coordinates modulo p and turns non-empty payloads into zero.\n for (const b of value) {\n if (b) throw new Error(`invalid ${name} point: non-canonical zero`);\n }\n return { x: F.ZERO, y: F.ZERO };\n }\n const x = dec(compressed ? value : value.subarray(0, W));\n let y;\n if (compressed) {\n y = F.sqrt(F.add(F.pow(x, _3n), b));\n if (!y) throw new Error(`invalid ${name} point: compressed`);\n if (sortBit(yparts(y), BaseFp.ORDER) !== sort) y = F.neg(y);\n } else {\n y = dec(value.subarray(W));\n }\n // Noble keeps the permissive coordinate reduction path here, but an\n // omitted infinity flag must not still decode to ZERO afterwards.\n if (!compressed && F.is0(x) && F.is0(y))\n throw new Error(`invalid ${name} point: uncompressed`);\n return { x, y };\n },\n });\n};\n\n// Internal helper only: it copies before clearing the top flag bits. The\n// pairing-friendly-curves draft C.2 step 1 rejects 0x20 / 0x60 / 0xe0 because\n// S_bit must be zero for infinity and for all uncompressed encodings.\nfunction validateMask({ compressed, infinity, sort }: Mask) {\n if (\n (!compressed && !infinity && sort) || // 0010_0000 = 0x20\n (!compressed && infinity && sort) || // 0110_0000 = 0x60\n (compressed && infinity && sort) // 1110_0000 = 0xe0\n )\n throw new Error('invalid encoding flag');\n}\nfunction parseMask(bytes: TArg<Uint8Array>) {\n // Copy, so we can remove mask data.\n // It will be removed also later, when Fp.create will call modulo.\n bytes = copyBytes(bytes);\n const mask = bytes[0] & 0b1110_0000;\n const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000)\n const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000)\n const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000)\n validateMask({ compressed, infinity, sort });\n bytes[0] &= 0b0001_1111; // clear mask (zero first 3 bits)\n return { compressed, infinity, sort, value: bytes };\n}\n\n// Internal helper only: mutates a non-empty fresh buffer in place and just\n// sets bits. Keep the same invalid-flag guard as parseMask() so encoders cannot\n// manufacture states that decoders already reject.\nfunction setMask(bytes: TArg<Uint8Array>, mask: Partial<Mask>) {\n if (bytes[0] & 0b1110_0000) throw new Error('setMask: non-empty mask');\n validateMask({ compressed: !!mask.compressed, infinity: !!mask.infinity, sort: !!mask.sort });\n if (mask.compressed) bytes[0] |= 0b1000_0000;\n if (mask.infinity) bytes[0] |= 0b0100_0000;\n if (mask.sort) bytes[0] |= 0b0010_0000;\n return bytes;\n}\n\nconst g1coder = coder(\n 'G1',\n Fp,\n Fp.create(bls12_381_CURVE_G1.b),\n (x: Fp) => numberToBytesBE(x, Fp.BYTES),\n (bytes: TArg<Uint8Array>) => Fp.create(bytesToNumberBE(bytes) & bitMask(Fp.BITS)),\n (y: Fp) => [y]\n);\nconst g1 = { point: g1coder(true), sig: g1coder(false) };\nconst signatureG1ToBytes = (point: WeierstrassPoint<Fp>): TRet<Uint8Array> => {\n point.assertValidity();\n return g1.sig.encode(point);\n};\nfunction signatureG1FromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp> {\n const Point = bls12_381.G1.Point;\n const point = Point.fromAffine(g1.sig.decode(bytes));\n point.assertValidity();\n return point;\n}\n\nconst g2coder = coder('G2', Fp2, bls12_381_CURVE_G2.b, fp2.encode, fp2.decode, (y: Fp2) => [\n y.c1,\n y.c0,\n]);\nconst g2 = { point: g2coder(true), sig: g2coder(false) };\nconst signatureG2ToBytes = (point: WeierstrassPoint<Fp2>): TRet<Uint8Array> => {\n point.assertValidity();\n return g2.sig.encode(point);\n};\nfunction signatureG2FromBytes(bytes: TArg<Uint8Array>) {\n const Point = bls12_381.G2.Point;\n const point = Point.fromAffine(g2.sig.decode(bytes));\n point.assertValidity();\n return point;\n}\n\nconst signatureCoders = {\n ShortSignature: {\n fromBytes(bytes: TArg<Uint8Array>) {\n return signatureG1FromBytes(abytes(bytes));\n },\n fromHex(hex: string): WeierstrassPoint<Fp> {\n return signatureG1FromBytes(hexToBytes(hex));\n },\n toBytes(point: WeierstrassPoint<Fp>) {\n return signatureG1ToBytes(point);\n },\n // Historical alias: BLS signatures have a single compressed byte format here.\n toRawBytes(point: WeierstrassPoint<Fp>) {\n return signatureG1ToBytes(point);\n },\n toHex(point: WeierstrassPoint<Fp>) {\n return bytesToHex(signatureG1ToBytes(point));\n },\n },\n LongSignature: {\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp2> {\n return signatureG2FromBytes(abytes(bytes));\n },\n fromHex(hex: string): WeierstrassPoint<Fp2> {\n return signatureG2FromBytes(hexToBytes(hex));\n },\n toBytes(point: WeierstrassPoint<Fp2>) {\n return signatureG2ToBytes(point);\n },\n // Historical alias: BLS signatures have a single compressed byte format here.\n toRawBytes(point: WeierstrassPoint<Fp2>) {\n return signatureG2ToBytes(point);\n },\n toHex(point: WeierstrassPoint<Fp2>) {\n return bytesToHex(signatureG2ToBytes(point));\n },\n },\n};\n\nconst fields = {\n Fp,\n Fp2,\n Fp6,\n Fp12,\n Fr: bls12_381_Fr,\n};\nconst G1_Point = weierstrass(bls12_381_CURVE_G1, {\n // Public point APIs still accept infinity, even though the Zcash proof\n // encoding rules cited above only define nonzero point encodings.\n allowInfinityPoint: true,\n Fn: bls12_381_Fr,\n fromBytes: g1.point.decode,\n toBytes: (\n _c: WeierstrassPointCons<Fp>,\n point: WeierstrassPoint<Fp>,\n isComp: boolean\n ): TRet<Uint8Array> => g1.point.encode(point, isComp) as TRet<Uint8Array>,\n // Checks is the point resides in prime-order subgroup.\n // point.isTorsionFree() should return true for valid points\n // It returns false for shitty points.\n // https://eprint.iacr.org/2021/1130.pdf\n isTorsionFree: (c, point): boolean => {\n // GLV endomorphism ψ(P)\n const beta = BigInt(\n '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'\n );\n const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z);\n // TODO: unroll\n const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P\n const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P\n return u2P.equals(phi);\n },\n // Clear cofactor of G1\n // https://eprint.iacr.org/2019/403\n clearCofactor: (_c, point) => {\n // return this.multiplyUnsafe(CURVE.h);\n return point.multiplyUnsafe(BLS_X).add(point); // x*P + P\n },\n});\nconst G2_Point = weierstrass(bls12_381_CURVE_G2, {\n Fp: Fp2,\n // Public point APIs still accept infinity, even though the Zcash proof\n // encoding rules cited above only define nonzero point encodings.\n allowInfinityPoint: true,\n Fn: bls12_381_Fr,\n fromBytes: g2.point.decode,\n toBytes: (\n _c: WeierstrassPointCons<Fp2>,\n point: WeierstrassPoint<Fp2>,\n isComp: boolean\n ): TRet<Uint8Array> => g2.point.encode(point, isComp) as TRet<Uint8Array>,\n // https://eprint.iacr.org/2021/1130.pdf\n // Older version: https://eprint.iacr.org/2019/814.pdf\n isTorsionFree: (c, P): boolean => {\n return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)\n },\n // clear_cofactor_bls12381_g2 from RFC 9380.\n // https://eprint.iacr.org/2017/419.pdf\n // prettier-ignore\n clearCofactor: (c, P) => {\n const x = BLS_X;\n let t1 = P.multiplyUnsafe(x).negate(); // [-x]P\n let t2 = G2psi(c, P); // Ψ(P)\n let t3 = P.double(); // 2P\n t3 = G2psi2(c, t3); // Ψ²(2P)\n t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P)\n t2 = t1.add(t2); // [-x]P + Ψ(P)\n t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P)\n t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P)\n t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P\n const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P\n return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P)\n },\n});\n\nconst bls12_hasher_opts = {\n mapToG1: mapToG1,\n mapToG2: mapToG2,\n hasherOpts: hasher_opts,\n // RFC 9380 Appendix J defines distinct G1/G2 RO and NU suite IDs, and\n // draft-irtf-cfrg-bls-signature-06 §4.2.1 gives separate G1/G2 `_NUL_` DSTs.\n // Keep G1 encode-to-curve on the G1 domain instead of inheriting G2's `encodeDST`.\n hasherOptsG1: {\n ...hasher_opts,\n m: 1,\n DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_',\n encodeDST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_',\n },\n hasherOptsG2: { ...hasher_opts },\n} as const;\n\nconst bls12_params = {\n ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381\n xNegative: true,\n twistType: 'multiplicative' as const,\n randomBytes: randomBytes,\n};\n\n/**\n * bls12-381 pairing-friendly curve construction.\n * Provides both longSignatures and shortSignatures.\n * @example\n * bls12-381 pairing-friendly curve construction.\n *\n * ```ts\n * const bls = bls12_381.longSignatures;\n * const { secretKey, publicKey } = bls.keygen();\n * const msg = bls.hash(new TextEncoder().encode('hello noble'));\n * const sig = bls.sign(msg, secretKey);\n * const isValid = bls.verify(sig, msg, publicKey);\n * ```\n */\nexport const bls12_381: BlsCurvePairWithSignatures = bls(\n fields,\n G1_Point,\n G2_Point,\n bls12_params,\n bls12_hasher_opts,\n signatureCoders\n);\n\n// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3\n// Coefficients stay in ascending `k_(?,0)`..`k_(?,d)` order; isogenyMap()\n// reverses them internally for Horner evaluation.\nconst isogenyMapG2 = isogenyMap(\n Fp2,\n [\n // xNum\n [\n [\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n ],\n [\n '0x0',\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d',\n ],\n [\n '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1',\n '0x0',\n ],\n ],\n // xDen\n [\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63',\n ],\n [\n '0xc',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n // yNum\n [\n [\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n ],\n [\n '0x0',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f',\n ],\n [\n '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10',\n '0x0',\n ],\n ],\n // yDen\n [\n [\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n ],\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3',\n ],\n [\n '0x12',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt) as BigintTuple))) as [\n Fp2[],\n Fp2[],\n Fp2[],\n Fp2[],\n ]\n);\n// 11-isogeny map from E' to E. Coefficients stay in ascending\n// `k_(?,0)`..`k_(?,d)` order; isogenyMap() reverses them for Horner evaluation.\nconst isogenyMapG1 = isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7',\n '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb',\n '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0',\n '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861',\n '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9',\n '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983',\n '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84',\n '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e',\n '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317',\n '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e',\n '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b',\n '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229',\n ],\n // xDen\n [\n '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c',\n '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff',\n '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19',\n '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8',\n '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e',\n '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5',\n '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a',\n '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e',\n '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641',\n '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33',\n '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696',\n '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6',\n '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb',\n '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb',\n '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0',\n '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2',\n '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29',\n '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587',\n '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30',\n '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132',\n '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e',\n '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8',\n '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133',\n '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b',\n '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604',\n ],\n // yDen\n [\n '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1',\n '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d',\n '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2',\n '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416',\n '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d',\n '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac',\n '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c',\n '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9',\n '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a',\n '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55',\n '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8',\n '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092',\n '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc',\n '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7',\n '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]]\n);\n\nlet G1_SWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nlet G2_SWU: ((u: Fp2) => { x: Fp2; y: Fp2 }) | undefined;\n// SWU setup validates the pre-isogeny curve parameters and builds sqrt-ratio helpers.\n// Doing that eagerly adds about 10ms to `bls12-381.js` import here, so keep it lazy; after the\n// first map call the cached mapper is reused directly.\nconst getG1_SWU = () =>\n G1_SWU ||\n (G1_SWU = mapToCurveSimpleSWU(Fp, {\n A: Fp.create(\n BigInt(\n '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d'\n )\n ),\n B: Fp.create(\n BigInt(\n '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0'\n )\n ),\n Z: Fp.create(BigInt(11)),\n }));\nconst getG2_SWU = () =>\n G2_SWU ||\n (G2_SWU = mapToCurveSimpleSWU(Fp2, {\n // SWU map for the RFC 9380 §8.8.2 pre-isogeny G2 curve E':\n // y² = x³ + 240i * x + 1012 + 1012i\n A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I\n B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I)\n Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I)\n }));\n\n// Internal hash-to-curve step: G1 uses `m = 1`, so only `scalars[0]` is read,\n// and the result is the isogeny image on E before the subgroup clear.\nfunction mapToG1(scalars: bigint[]) {\n const { x, y } = getG1_SWU()(Fp.create(scalars[0]));\n return isogenyMapG1(x, y);\n}\n// Internal hash-to-curve step: G2 expects the RFC `m = 2` pair, and the result\n// is the isogeny image on E before the subgroup clear.\nfunction mapToG2(scalars: bigint[]) {\n const { x, y } = getG2_SWU()(Fp2.fromBigTuple(scalars as BigintTuple));\n return isogenyMapG2(x, y);\n}\n","import { bls12_381 } from '@noble/curves/bls12-381.js';\n\n// ETH2 BLS uses G1 public keys (48 bytes) and G2 signatures (96 bytes) — longSignatures mode.\n// The Ethereum consensus spec uses the POP (Proof of Possession) DST, not the noble/curves NUL default.\nconst { longSignatures: ls } = bls12_381;\nconst ETH2_DST = 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_';\n\nexport function blsVerify(\n pubkey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(signature, ls.hash(message, ETH2_DST), pubkey);\n } catch {\n return false;\n }\n}\n\nexport function blsAggregatePublicKeys(pubkeys: Uint8Array[]): Uint8Array {\n if (pubkeys.length === 0) {\n throw new Error('cannot aggregate empty pubkey set');\n }\n return ls.aggregatePublicKeys(pubkeys).toBytes() as Uint8Array;\n}\n\nexport function blsVerifyAggregate(\n pubkeys: Uint8Array[],\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(\n signature,\n ls.hash(message, ETH2_DST),\n ls.aggregatePublicKeys(pubkeys),\n );\n } catch {\n return false;\n }\n}\n\n/** Verify when the pubkey set is already aggregated to a single G1 key. */\nexport function blsVerifyWithAggregatedPubkey(\n aggregatedPubkey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(signature, ls.hash(message, ETH2_DST), aggregatedPubkey);\n } catch {\n return false;\n }\n}\n\nexport function blsVerifyMultiple(\n pubkeys: Uint8Array[],\n messages: Uint8Array[],\n signature: Uint8Array,\n): boolean {\n try {\n if (pubkeys.length !== messages.length) return false;\n const items = messages.map((msg, i) => ({\n message: ls.hash(msg, ETH2_DST),\n publicKey: pubkeys[i],\n }));\n return ls.verifyBatch(signature, items);\n } catch {\n return false;\n }\n}\n\nexport function blsAggregateSignatures(signatures: Uint8Array[]): Uint8Array {\n return ls.Signature.toBytes(ls.aggregateSignatures(signatures)) as Uint8Array;\n}\n\nfunction lagrangeCoeffAtZero(shareIndex: bigint, indices: bigint[]): bigint {\n const { Fr } = bls12_381.fields;\n let num = BigInt(1);\n let den = BigInt(1);\n for (const j of indices) {\n if (j === shareIndex) continue;\n num = Fr.mul(num, Fr.neg(j));\n den = Fr.mul(den, Fr.sub(shareIndex, j));\n }\n return Fr.mul(num, Fr.inv(den));\n}\n\nfunction blsRecoverWithIndices(\n shares: Uint8Array[],\n indices: bigint[],\n): Uint8Array | null {\n try {\n let recovered = bls12_381.G1.Point.ZERO;\n for (let i = 0; i < shares.length; i++) {\n const point = bls12_381.G1.Point.fromBytes(shares[i]);\n const coeff = lagrangeCoeffAtZero(indices[i], indices);\n recovered = recovered.add(point.multiply(coeff));\n }\n return recovered.toBytes() as Uint8Array;\n } catch {\n return null;\n }\n}\n\n// Recover validator distributed pubkey from threshold public shares using\n// Lagrange interpolation in G1 at x=0. Shares are assumed to be at 1-based\n// consecutive positions (index 1, 2, ..., threshold).\nexport function blsRecoverDistributedPubkeyFromShares(\n pubshares: Uint8Array[],\n threshold: number,\n): Uint8Array | null {\n if (threshold <= 0 || pubshares.length < threshold) return null;\n const selected = pubshares.slice(0, threshold);\n const indices = selected.map((_, i) => BigInt(i + 1));\n return blsRecoverWithIndices(selected, indices);\n}\n\n// Verify that every share beyond the first threshold lies on the same\n// polynomial as the first threshold shares. Replaces the last share of the\n// threshold subset with the extra share (keeping its real 1-based index) and\n// checks the reconstruction still produces the same distributed key.\nexport function blsVerifyExtraShares(\n pubshares: Uint8Array[],\n threshold: number,\n distributedPubkey: Uint8Array,\n): boolean {\n // Don't trust the caller — refuse to vacuously pass when there aren't\n // enough shares to even form a threshold-sized subset.\n if (threshold <= 0 || pubshares.length < threshold) return false;\n try {\n const baseShares = pubshares.slice(0, threshold - 1);\n const baseIndices = baseShares.map((_, i) => BigInt(i + 1));\n for (let i = threshold; i < pubshares.length; i++) {\n const shares = [...baseShares, pubshares[i]];\n const indices = [...baseIndices, BigInt(i + 1)];\n const recovered = blsRecoverWithIndices(shares, indices);\n // Length guard before .every() — Uint8Array#every only iterates the\n // shorter array's indices, so a shorter `recovered` would pass\n // vacuously without this check.\n if (\n !recovered ||\n recovered.length !== distributedPubkey.length ||\n !recovered.every((b, j) => b === distributedPubkey[j])\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Thrown when attempting to create a resource that already exists\n * (e.g. posting a duplicate cluster definition, or accepting already-accepted terms).\n */\nexport class ConflictError extends Error {\n name = 'ConflictError';\n\n constructor() {\n super('This Cluster has been already posted.');\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * Thrown when a method that requires an ethers `Signer` is called on a\n * client that was constructed without one.\n *\n * To fix: pass a `Wallet` or `JsonRpcSigner` as the second argument to\n * `new Client(config, signer)`.\n */\nexport class SignerRequiredError extends Error {\n name = 'SignerRequiredError';\n\n constructor(method: string) {\n super(`Signer is required in ${method}`);\n Object.setPrototypeOf(this, SignerRequiredError.prototype);\n }\n}\n\n/**\n * Thrown when an operation is attempted on a chain ID that does not support it\n * (e.g. deploying splitters on a chain without factory contracts).\n */\nexport class UnsupportedChainError extends Error {\n name = 'UnsupportedChainError';\n\n constructor(chainId: number, operation: string) {\n super(`${operation} is not supported on chain ${chainId}`);\n Object.setPrototypeOf(this, UnsupportedChainError.prototype);\n }\n}\n\n/**\n * Thrown when full lock validation (`validateClusterLock` worker path) exceeds\n * the worker time limit (large clusters). HTTP gateways should respond with\n * **504**; this is distinct from cryptographic failure (**false** → **400**).\n */\n/**\n * Thrown when {@link Client} is constructed with a baseUrl that is not an\n * an allowed Obol API base URL (see {@link ALLOWED_OBOL_API_BASE_URLS}).\n */\nexport class InvalidBaseUrlError extends Error {\n name = 'InvalidBaseUrlError';\n\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, InvalidBaseUrlError.prototype);\n }\n}\n\nexport class ClusterLockValidationTimeoutError extends Error {\n name = 'ClusterLockValidationTimeoutError';\n\n /**\n * @param timeoutMs - Same value as SDK whole-lock validation worker timeout.\n */\n constructor(public readonly timeoutMs: number) {\n super(\n `Cluster lock validation exceeded worker time limit (${timeoutMs} ms). Retry later; this does not imply invalid lock data.`,\n );\n Object.setPrototypeOf(this, ClusterLockValidationTimeoutError.prototype);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,iBAA8B;;;AC0GxB,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;AAE9B;AAcM,SAAU,QAAQ,GAAW,QAAgB,IAAE;AACnD,MAAI,OAAO,MAAM,UAAU;AACzB,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,UAAU,GAAG,MAAM,wBAAwB,OAAO,CAAC,EAAE;EACjE;AACA,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI,GAAG;AACrC,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,WAAW,GAAG,MAAM,8BAA8B,CAAC,EAAE;EACjE;AACF;AAgBM,SAAU,OACd,OACA,QACA,QAAgB,IAAE;AAElB,QAAM,QAAQ,QAAQ,KAAK;AAC3B,QAAM,MAAM,+BAAO;AACnB,QAAM,WAAW,WAAW;AAC5B,MAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;AAC1C,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,QAAQ,WAAW,cAAc,MAAM,KAAK;AAClD,UAAM,MAAM,QAAQ,UAAU,GAAG,KAA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WAAO,MAAM,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC5C,UAAI,UAAU;AACd,YAAM,SAAS,IAAI,GAAG,OAAO,YAAY;AAAA,QACvC,YAAY,EAAE,MAAM,WAAW;AAAA,MACjC,CAAC;AAID,YAAM,QAAQ,WAAW,MAAM;AAC7B,YAAI,QAAS;AACb,kBAAU;AACV,qBAAa,KAAK;AAClB,aAAK,OAAO,UAAU;AACtB;AAAA,UACE,IAAI,kCAAkC,4BAA4B;AAAA,QACpE;AAAA,MACF,GAAG,4BAA4B;AAC/B,YAAM,SAAS,CAAC,WAAiC;AAC/C,YAAI,QAAS;AACb,kBAAU;AACV,qBAAa,KAAK;AAElB,eAAO,UAAU;AACjB,gBAAQ,MAAM;AAAA,MAChB;AACA,aAAO,KAAK,WAAW,CAAC,QAAiB;AACvC,eAAO,QAAQ,IAAI;AAAA,MACrB,CAAC;AACD,aAAO,KAAK,SAAS,MAAM;AACzB,eAAO,IAAI;AAAA,MACb,CAAC;AACD,aAAO,KAAK,QAAQ,UAAQ;AAC1B,YAAI,SAAS,EAAG,QAAO,IAAI;AAAA,MAC7B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA;","names":["abytes","anumber","bytesToHex","concatBytes","hexToBytes","isBytes","randomBytes","abytes","fields","_0n","_1n","_0n","_1n","Fp","_1n","Fp","_0n","Fp","_1n","anumber","_0n","abytes","_1n","abytes","_0n","_1n","_1n","_0n","_1n","_0n","Fp","isBytes","abytes","concatBytes","createHasher","_2n","_0n","_1n","abytes","_0n","_1n","_2n","_3n","_4n","Fp","concatBytes","hexToBytes","endo","bytesToHex","tv5","c1","c2","x","_0n","_1n","_2n","_3n","fields","Fp2","Fp12","g1","g2","randomBytes","abytes","msg","G1_Point","G2_Point","Fp","Fp6","createHasher","signatureCoders","_0n","_1n","_2n","_3n","Fp","Fp","Fp2","_1n","_3n","_2n","G2psi","G2psi2","_0n","abytes","concatBytes","frob","Fp6","Fp12","_0n","_1n","_2n","_3n","_4n","concatBytes","Fp","abytes","b","hexToBytes","bytesToHex","randomBytes"]}
1
+ {"version":3,"sources":["../../../../src/verification/parallelPool.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/utils.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/_md.ts","../../../../node_modules/@noble/curves/node_modules/@noble/hashes/src/sha2.ts","../../../../node_modules/@noble/curves/src/utils.ts","../../../../node_modules/@noble/curves/src/abstract/modular.ts","../../../../node_modules/@noble/curves/src/abstract/curve.ts","../../../../node_modules/@noble/curves/src/abstract/hash-to-curve.ts","../../../../node_modules/@noble/curves/src/abstract/weierstrass.ts","../../../../node_modules/@noble/curves/src/abstract/bls.ts","../../../../node_modules/@noble/curves/src/abstract/tower.ts","../../../../node_modules/@noble/curves/src/bls12-381.ts","../../../../src/blsUtils.ts","../../../../src/errors.ts"],"sourcesContent":["// Parallel BLS verification via Node worker_threads.\n//\n// IMPORTANT: only the CJS build actually runs in parallel. ESM Node and\n// browser bundles transparently fall back to sync. See the matrix in\n// PARALLEL_VALIDATION_PLAN.md. The main consumer flow (charon DKG ->\n// obol-api NestJS handler -> SDK CJS) is CJS, so it gets the speedup.\n//\n// Strategy:\n// - Look up the worker file via __dirname (CJS only). If undefined or the\n// file isn't where we expect (ESM, browser, source-mode tsx/jest), return\n// undefined and fall back to sync.\n// - Below MIN_PARALLEL_* thresholds, sync wins (worker spin-up dominates).\n// - Spawn one worker per chunk, await all, collapse to a single boolean.\n\nimport { fromHexString } from '@chainsafe/ssz';\nimport {\n blsAggregatePublicKeys,\n blsAggregateSignatures,\n blsRecoverDistributedPubkeyFromShares,\n blsVerifyAggregate,\n blsVerifyExtraShares,\n blsVerifyMultiple,\n blsVerifyWithAggregatedPubkey,\n} from '../blsUtils.js';\n// Type-only imports — erased at compile time, so they don't pull node:*\n// modules into the browser bundle.\nimport type * as WTNs from 'node:worker_threads';\nimport type * as OsNs from 'node:os';\nimport type * as PathNs from 'node:path';\nimport type * as FsNs from 'node:fs';\nimport { ClusterLockValidationTimeoutError } from '../errors.js';\nimport type { BlsSignatureCheck, ClusterLock, SafeRpcUrl } from '../types.js';\nimport type { AggregatePubkeysInput, WorkerInput } from './lockWorker.js';\n\nconst MIN_PARALLEL_VALIDATORS = 50;\nconst MIN_PARALLEL_BATCH_PAIRS = 100;\nconst MAX_WORKERS = 8;\nconst MIN_VALIDATORS_PER_WORKER = 25;\nconst MIN_PAIRS_PER_WORKER = 50;\nconst MIN_PARALLEL_AGGREGATE_KEYS = 400;\nconst MIN_KEYS_PER_WORKER_AGG = 100;\n// Hard ceiling so a stuck worker can't leak past obol-api / ingress timeouts.\n// Bench ~3s per chunk on fast CPU; dev pods (~500m) need more headroom for ~1k DVs.\nconst MIN_VALIDATORS_FOR_VALIDATION_WORKER = 50;\nconst VALIDATION_WORKER_TIMEOUT_MS = 300_000;\nconst WORKER_TIMEOUT_MS = 180_000;\n\n/** Posted from clusterLockValidationWorker when a nested BLS worker times out. */\nexport type LockValidationWorkerTimeoutReply = {\n validationTimeoutMs: number;\n};\n\nfunction isValidationTimeoutReply(\n msg: unknown,\n): msg is LockValidationWorkerTimeoutReply {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n 'validationTimeoutMs' in msg &&\n typeof (msg as LockValidationWorkerTimeoutReply).validationTimeoutMs ===\n 'number'\n );\n}\n// Cap simultaneous workers (memory). Scales up for large jobs on multi-core hosts.\nconst MAX_CONCURRENT_WORKERS_CAP = 8;\n\nfunction maxConcurrentWorkers(numWorkers: number): number {\n return Math.min(numWorkers, MAX_CONCURRENT_WORKERS_CAP);\n}\n\ntype WorkerThreads = typeof WTNs;\ntype NodeOs = typeof OsNs;\n\nlet workerThreadsCache: WorkerThreads | null | undefined;\nlet osCache: NodeOs | null | undefined;\n// Tri-state per worker file: undefined = uncached, null = unavailable, string = path.\nconst workerPathByFile = new Map<string, string | null | undefined>();\n\nfunction loadWorkerThreads(): WorkerThreads | null {\n if (workerThreadsCache !== undefined) return workerThreadsCache;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n workerThreadsCache = require('node:worker_threads') as WorkerThreads;\n } catch {\n workerThreadsCache = null;\n }\n return workerThreadsCache;\n}\n\nfunction loadOs(): NodeOs | null {\n if (osCache !== undefined) return osCache;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n osCache = require('node:os') as NodeOs;\n } catch {\n osCache = null;\n }\n return osCache;\n}\n\nfunction getWorkerPath(filename: string): string | null {\n const cached = workerPathByFile.get(filename);\n if (cached !== undefined) return cached;\n if (typeof __dirname === 'undefined') {\n workerPathByFile.set(filename, null);\n return null;\n }\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const path = require('node:path') as typeof PathNs;\n // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n const fs = require('node:fs') as typeof FsNs;\n // Bundled index.js: __dirname is dist/cjs/src; workers live in verification/.\n // Standalone parallelPool.js entry: __dirname is already verification/.\n const candidates = [\n path.join(__dirname, filename),\n path.join(__dirname, 'verification', filename),\n ];\n try {\n for (const candidate of candidates) {\n if (fs.existsSync(candidate)) {\n workerPathByFile.set(filename, candidate);\n return candidate;\n }\n }\n } catch {\n // fall through\n }\n workerPathByFile.set(filename, null);\n return null;\n}\n\nasync function mapWithConcurrency<T, R>(\n items: T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = new Array(items.length);\n let next = 0;\n const runners = Array.from(\n { length: Math.min(concurrency, items.length) },\n async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i], i);\n }\n },\n );\n await Promise.all(runners);\n return results;\n}\n\nfunction chunkArrays<T>(arr: T[], n: number): T[][] {\n const size = Math.ceil(arr.length / n);\n const out: T[][] = [];\n for (let i = 0; i < arr.length; i += size) {\n out.push(arr.slice(i, i + size));\n }\n return out;\n}\n\nfunction verifySharesSync(\n shares: string[][],\n distributedKeys: string[],\n threshold: number,\n): boolean {\n for (let i = 0; i < shares.length; i++) {\n const sharesBytes = shares[i].map(s => fromHexString(s));\n const dkBytes = fromHexString(distributedKeys[i]);\n const recovered = blsRecoverDistributedPubkeyFromShares(\n sharesBytes,\n threshold,\n );\n if (!recovered) return false;\n if (recovered.length !== dkBytes.length) return false;\n for (let j = 0; j < recovered.length; j++) {\n if (recovered[j] !== dkBytes[j]) return false;\n }\n if (!blsVerifyExtraShares(sharesBytes, threshold, dkBytes)) {\n return false;\n }\n }\n return true;\n}\n\nasync function runWorkerAggregatePubkeys(\n wt: WorkerThreads,\n workerFile: string,\n data: AggregatePubkeysInput,\n): Promise<Uint8Array | null> {\n return await new Promise((resolve, reject) => {\n let settled = false;\n const worker = new wt.Worker(workerFile, { workerData: data });\n const finish = (result: Uint8Array | null): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n reject(new ClusterLockValidationTimeoutError(WORKER_TIMEOUT_MS));\n }, WORKER_TIMEOUT_MS);\n worker.once('message', (msg: unknown) => {\n finish(msg instanceof Uint8Array ? msg : null);\n });\n worker.once('error', () => {\n finish(null);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(null);\n });\n });\n}\n\nasync function runWorker(\n wt: WorkerThreads,\n workerFile: string,\n data: WorkerInput,\n): Promise<boolean> {\n return await new Promise((resolve, reject) => {\n let settled = false;\n const worker = new wt.Worker(workerFile, { workerData: data });\n const finish = (result: boolean): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n reject(new ClusterLockValidationTimeoutError(WORKER_TIMEOUT_MS));\n }, WORKER_TIMEOUT_MS);\n worker.once('message', (msg: unknown) => {\n finish(msg === true);\n });\n worker.once('error', () => {\n finish(false);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(false);\n });\n });\n}\n\nfunction poolSize(\n itemCount: number,\n minPerWorker: number,\n): {\n numWorkers: number;\n wt: WorkerThreads | null;\n workerFile: string | null;\n} {\n const wt = loadWorkerThreads();\n const os = loadOs();\n const workerFile = getWorkerPath('lockWorker.js');\n const numCpus = os ? Math.max(1, os.cpus().length) : 1;\n const numWorkers = Math.min(\n MAX_WORKERS,\n Math.max(1, Math.floor(itemCount / minPerWorker)),\n numCpus,\n );\n return { numWorkers, wt, workerFile };\n}\n\nasync function runWorkerChunks(\n wt: WorkerThreads,\n workerFile: string,\n chunks: WorkerInput[],\n): Promise<boolean> {\n const results = await mapWithConcurrency(\n chunks,\n maxConcurrentWorkers(chunks.length),\n async data => await runWorker(wt, workerFile, data),\n );\n return results.every(Boolean);\n}\n\nexport async function verifySharesBinding(\n shares: string[][],\n distributedKeys: string[],\n threshold: number,\n): Promise<boolean> {\n if (shares.length !== distributedKeys.length) return false;\n if (shares.length === 0) return true;\n\n const { numWorkers, wt, workerFile } = poolSize(\n shares.length,\n MIN_VALIDATORS_PER_WORKER,\n );\n\n // Inline the guard so TS narrows wt/workerFile for the parallel path below\n // (avoids non-null assertions).\n if (\n wt === null ||\n workerFile === null ||\n shares.length < MIN_PARALLEL_VALIDATORS ||\n numWorkers < 2\n ) {\n return verifySharesSync(shares, distributedKeys, threshold);\n }\n\n const shareChunks = chunkArrays(shares, numWorkers);\n const keyChunks = chunkArrays(distributedKeys, numWorkers);\n\n return await runWorkerChunks(\n wt,\n workerFile,\n shareChunks.map((chunk, i) => ({\n mode: 'shareBinding',\n shares: chunk,\n distributedKeys: keyChunks[i],\n threshold,\n })),\n );\n}\n\n/** Verify deposit + builder BLS signatures collected from `depositBlsCheck` / `builderBlsCheck`. */\nexport async function verifyBlsChecksParallel(\n checks: BlsSignatureCheck[],\n): Promise<boolean> {\n if (checks.length === 0) return true;\n return await verifyBatchParallel(\n checks.map(c => c.pubkey),\n checks.map(c => c.message),\n checks.map(c => c.signature),\n );\n}\n\n// Verify a batch of (pubkey, message, individual signature) triples.\n// Sync path aggregates all sigs and runs blsVerifyMultiple once (matches the\n// previous behavior). Parallel path splits into chunks; each chunk's sigs are\n// aggregated and verified independently — same total pairing count, K× wall\n// time speedup.\nexport async function verifyBatchParallel(\n pubkeys: Uint8Array[],\n messages: Uint8Array[],\n signatures: Uint8Array[],\n): Promise<boolean> {\n if (\n pubkeys.length !== messages.length ||\n pubkeys.length !== signatures.length\n ) {\n return false;\n }\n if (pubkeys.length === 0) return true;\n\n const { numWorkers, wt, workerFile } = poolSize(\n pubkeys.length,\n MIN_PAIRS_PER_WORKER,\n );\n\n if (\n wt === null ||\n workerFile === null ||\n pubkeys.length < MIN_PARALLEL_BATCH_PAIRS ||\n numWorkers < 2\n ) {\n return blsVerifyMultiple(\n pubkeys,\n messages,\n blsAggregateSignatures(signatures),\n );\n }\n\n const pkChunks = chunkArrays(pubkeys, numWorkers);\n const msgChunks = chunkArrays(messages, numWorkers);\n const sigChunks = chunkArrays(signatures, numWorkers);\n\n return await runWorkerChunks(\n wt,\n workerFile,\n pkChunks.map((pks, i) => ({\n mode: 'verifyBatch',\n pubkeys: pks,\n messages: msgChunks[i],\n signatures: sigChunks[i],\n })),\n );\n}\n\n// Lock signature_aggregate: aggregate many operator shares (validators × operators)\n// then verify one BLS signature over lock_hash. Parallel path aggregates pubkey\n// chunks in workers, combines partial aggregates on the main thread, then verifies.\nexport async function verifyAggregateParallel(\n pubkeys: Uint8Array[],\n message: Uint8Array,\n signature: Uint8Array,\n): Promise<boolean> {\n if (pubkeys.length === 0) return false;\n\n const { numWorkers, wt, workerFile } = poolSize(\n pubkeys.length,\n MIN_KEYS_PER_WORKER_AGG,\n );\n\n if (\n wt === null ||\n workerFile === null ||\n pubkeys.length < MIN_PARALLEL_AGGREGATE_KEYS ||\n numWorkers < 2\n ) {\n return blsVerifyAggregate(pubkeys, message, signature);\n }\n\n const pkChunks = chunkArrays(pubkeys, numWorkers);\n const partials = await mapWithConcurrency(\n pkChunks,\n maxConcurrentWorkers(pkChunks.length),\n async chunk =>\n await runWorkerAggregatePubkeys(wt, workerFile, {\n mode: 'aggregatePubkeys',\n pubkeys: chunk,\n }),\n );\n if (partials.some(p => p === null)) return false;\n\n const aggregated = blsAggregatePublicKeys(partials as Uint8Array[]);\n return blsVerifyWithAggregatedPubkey(aggregated, message, signature);\n}\n\n/**\n * Large locks: run full validation off the main thread (obol-api stays responsive).\n * Returns null when workers are unavailable — caller should use sync validation.\n */\nexport async function validateClusterLockInWorker(\n lock: ClusterLock,\n safeRpcUrl?: SafeRpcUrl,\n): Promise<boolean | null> {\n const n = lock.distributed_validators?.length ?? 0;\n if (n < MIN_VALIDATORS_FOR_VALIDATION_WORKER) return null;\n\n const wt = loadWorkerThreads();\n const workerFile = getWorkerPath('clusterLockValidationWorker.js');\n if (wt === null || workerFile === null) return null;\n\n return await new Promise((resolve, reject) => {\n let settled = false;\n const worker = new wt.Worker(workerFile, {\n workerData: { lock, safeRpcUrl },\n });\n // Timeout rejects (ClusterLockValidationTimeoutError) instead of resolving\n // false: callers must distinguish **504** gateway timeout from **400** invalid\n // crypto. Do not resolve null here — full sync fallback would block Node again.\n const timer = setTimeout(() => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n void worker.terminate();\n reject(\n new ClusterLockValidationTimeoutError(VALIDATION_WORKER_TIMEOUT_MS),\n );\n }, VALIDATION_WORKER_TIMEOUT_MS);\n const finish = (result: boolean | null): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n resolve(result);\n };\n worker.once('message', (msg: unknown) => {\n if (isValidationTimeoutReply(msg)) {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n worker.terminate();\n reject(new ClusterLockValidationTimeoutError(msg.validationTimeoutMs));\n return;\n }\n finish(msg === true);\n });\n worker.once('error', () => {\n finish(null);\n });\n worker.once('exit', code => {\n if (code !== 0) finish(null);\n });\n });\n}\n","/**\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 * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nabstract class SHA2_32B<T extends SHA2_32B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nabstract class SHA2_64B<T extends SHA2_64B<T>> extends HashMD<T> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet<CHash<_SHA256>> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet<CHash<_SHA224>> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet<CHash<_SHA512>> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet<CHash<_SHA384>> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet<CHash<_SHA512_256>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet<CHash<_SHA512_224>> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg<T> = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet<T> = T extends BigInt64Array\n ? ReturnType<typeof BigInt64Array.of>\n : T extends BigUint64Array\n ? ReturnType<typeof BigUint64Array.of>\n : T extends Float32Array\n ? ReturnType<typeof Float32Array.of>\n : T extends Float64Array\n ? ReturnType<typeof Float64Array.of>\n : T extends Int16Array\n ? ReturnType<typeof Int16Array.of>\n : T extends Int32Array\n ? ReturnType<typeof Int32Array.of>\n : T extends Int8Array\n ? ReturnType<typeof Int8Array.of>\n : T extends Uint16Array\n ? ReturnType<typeof Uint16Array.of>\n : T extends Uint32Array\n ? ReturnType<typeof Uint32Array.of>\n : T extends Uint8ClampedArray\n ? ReturnType<typeof Uint8ClampedArray.of>\n : T extends Uint8Array\n ? ReturnType<typeof Uint8Array.of>\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg<T> =\n | T\n | ([TypedArg<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet<A[K]> }) => TArg<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg<A>, ...{ [K in keyof R]: TArg<R[K]> }]\n : T extends (infer A)[]\n ? TArg<A>[]\n : T extends readonly (infer A)[]\n ? readonly TArg<A>[]\n : T extends Promise<infer A>\n ? Promise<TArg<A>>\n : T extends object\n ? { [K in keyof T]: TArg<T[K]> }\n : T\n : TypedArg<T>);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet<T> = T extends unknown\n ? T &\n ([TypedRet<T>] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg<A[K]> }) => TRet<R>) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;\n }\n : T extends [infer A, ...infer R]\n ? [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet<A>, ...{ [K in keyof R]: TRet<R[K]> }]\n : T extends (infer A)[]\n ? TRet<A>[]\n : T extends readonly (infer A)[]\n ? readonly TRet<A>[]\n : T extends Promise<infer A>\n ? Promise<TRet<A>>\n : T extends object\n ? { [K in keyof T]: TRet<T[K]> }\n : T\n : TypedRet<T>)\n : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = <T extends TArg<Uint8Array>>(value: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg<Uint8Array[]>): TRet<Uint8Array> =>\n concatBytes_(...arrays) as TRet<Uint8Array>;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet<Uint8Array> => hexToBytes_(hex) as TRet<Uint8Array>;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet<Uint8Array> =>\n randomBytes_(bytesLength) as TRet<Uint8Array>;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg<Uint8Array>): TRet<Uint8Array>;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg<Uint8Array>, message: TArg<Uint8Array>) => TRet<Uint8Array>;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber<T extends number | bigint>(n: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg<Uint8Array>): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array> {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet<Uint8Array>;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet<Uint8Array> {\n return numberToBytesBE(n, len).reverse() as TRet<Uint8Array>;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet<Uint8Array> {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet<Uint8Array>;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array> {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet<Uint8Array>;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet<Uint8Array> {\n if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet<Uint8Array>;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred<T> = (v: TArg<Uint8Array>) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg<HmacFn>\n): TRet<(seed: Uint8Array, predicate: Pred<T>) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet<Uint8Array> => new Uint8Array(len) as TRet<Uint8Array>;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs: TArg<Uint8Array[]>) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg<Uint8Array> = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: TArg<Uint8Array>, pred: TArg<Pred<T>>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred<T>)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred<T>) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n object: Record<string, any>,\n fields: Record<string, string> = {},\n optFields: Record<string, string> = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare<T>(Fp: TArg<IField<T>>, root: T, n: T): void {\n const F = Fp as IField<T>;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8<T>(Fp: TArg<IField<T>>, n: T) {\n const F = Fp as IField<T>;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return (<T>(Fp: TArg<IField<T>>, n: T): T => {\n const F = Fp as IField<T>;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n }) as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: TArg<IField<T>>, n: T): T {\n const F = Fp as IField<T>;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n } as TRet<<T>(Fp: IField<T>, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<<T>(Fp: IField<T>, n: T) => T> {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<<T>(Fp: IField<T>, n: T) => T>;\n // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField<T> {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField<T>(field: TArg<IField<T>>): TRet<IField<T>> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet<IField<T>>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow<T>(Fp: TArg<IField<T>>, num: T, power: bigint): T {\n const F = Fp as IField<T>;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch<T>(Fp: TArg<IField<T>>, nums: T[], passZero = false): T[] {\n const F = Fp as IField<T>;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv<T>(Fp: TArg<IField<T>>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField<T>;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre<T>(Fp: TArg<IField<T>>, n: T): -1 | 0 | 1 {\n const F = Fp as IField<T>;\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare<T>(Fp: TArg<IField<T>>, n: T): boolean {\n const l = FpLegendre(Fp as IField<T>, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap<object, ReturnType<typeof FpSqrt>>();\nclass _Field implements IField<bigint> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet<Readonly<FpField>> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven<T>(Fp: TArg<IField<T>>, elm: T): T {\n const F = Fp as IField<T>;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n key: TArg<Uint8Array>,\n fieldOrder: bigint,\n isLE = false\n): TRet<Uint8Array> {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint<T> = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint<F, P extends CurvePoint<F, P>> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint<F>;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons<P extends CurvePoint<any, P>> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField<P_F<P>>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField<bigint>;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint<P_F<P>>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint<PC>': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint<PC>': it won't be accesible for arguments/return types\n// * `CurvePointCons<P extends CurvePoint<any, P>>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons<any>`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint<any, P>.\n// this means we need to do stuff like\n// `function test<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(`\n// if we want type safety around P, otherwise PC_P<PC> will be any\n\n/** Returns the affine field type for a point instance (`P_F<P> == P.F`). */\nexport type P_F<P extends CurvePoint<any, P>> = P extends CurvePoint<infer F, P> ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F<PC> == PC.P.F`). */\nexport type PC_F<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P<PC> == PC.P`). */\nexport type PC_P<PC extends CurvePointCons<CurvePoint<any, any>>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons<CurvePoint<any, any>>`, will return `any` after 1 operation\n// * `CurvePointCons<any>: WeierstrassPointCons<bigint> extends CurvePointCons<any> = false`\n// * `P extends CurvePoint, PC extends CurvePointCons<P>`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons<F, P>`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any,\n CurvePoint<any, any>\n >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons<P extends CurvePoint<any, P>>(Point: CurvePointCons<P>): void {\n const pc = Point as unknown as CurvePointCons<any>;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper<T> = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt<T extends { negate: () => T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap<any, any[]>();\nconst pointWindowSizes = new WeakMap<any, number>();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF<PC extends PC_ANY> {\n private readonly BASE: PC_P<PC>;\n private readonly ZERO: PC_P<PC>;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P<PC>, n: bigint, p: PC_P<PC> = this.ZERO): PC_P<PC> {\n let d: PC_P<PC> = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P<PC>, W: number): PC_P<PC>[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P<PC>[] = [];\n let p: PC_P<PC> = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P<PC>[], n: bigint): { p: PC_P<PC>; f: PC_P<PC> } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P<PC>[],\n n: bigint,\n acc: PC_P<PC> = this.ZERO\n ): PC_P<PC> {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P<PC>, transform?: Mapper<PC_P<PC>>): PC_P<PC>[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P<PC>[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P<PC>,\n scalar: bigint,\n transform?: Mapper<PC_P<PC>>\n ): { p: PC_P<PC>; f: PC_P<PC> } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P<PC>, scalar: bigint, transform?: Mapper<PC_P<PC>>, prev?: PC_P<PC>): PC_P<PC> {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P<PC>, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P<PC>): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe<P extends CurvePoint<any, P>, PC extends CurvePointCons<P>>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams<T> = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField<T>(order: bigint, field?: TArg<IField<T>>, isLE?: boolean): TRet<IField<T>> {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet<IField<T>>;\n } else {\n return Field(order, { isLE }) as unknown as TRet<IField<T>>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn<T> = {\n /** Base field used for curve coordinates. */\n Fp: IField<T>;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField<bigint>;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields<T>(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams<T>,\n curveOpts: TArg<Partial<FpFn<T>>> = {},\n FpFnLE?: boolean\n): TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn } as TRet<FpFn<T> & { CURVE: ValidCurveParams<T> }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: TArg<Signer['getPublicKey']>\n): TRet<KeygenFn> {\n return function keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed) as TRet<Uint8Array>;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet<Uint8Array> };\n };\n}\n","/**\n * hash-to-curve from RFC 9380.\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * https://www.rfc-editor.org/rfc/rfc9380\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport type { CHash, TArg, TRet } from '../utils.ts';\nimport {\n abytes,\n asafenumber,\n asciiToBytes,\n bytesToNumberBE,\n copyBytes,\n concatBytes,\n isBytes,\n validateObject,\n} from '../utils.ts';\nimport type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts';\nimport { FpInvertBatch, mod, type IField } from './modular.ts';\n\n/** ASCII domain-separation tag or raw bytes. */\nexport type AsciiOrBytes = string | Uint8Array;\ntype H2CDefaults = {\n DST: AsciiOrBytes;\n expand: 'xmd' | 'xof';\n hash: CHash;\n p: bigint;\n m: number;\n k: number;\n encodeDST?: AsciiOrBytes;\n};\n\n/**\n * * `DST` is a domain separation tag, defined in section 2.2.5\n * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m\n * * `m` is extension degree (1 for prime fields)\n * * `k` is the target security target in bits (e.g. 128), from section 5.1\n * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)\n * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props\n */\nexport type H2COpts = {\n /** Domain separation tag. */\n DST: AsciiOrBytes;\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n /** Base-field characteristic. */\n p: bigint;\n /** Extension degree (`1` for prime fields). */\n m: number;\n /** Target security level in bits. */\n k: number;\n};\n/** Hash-only subset of RFC 9380 options used by per-call overrides. */\nexport type H2CHashOpts = {\n /** Expander family used by RFC 9380. */\n expand: 'xmd' | 'xof';\n /** Hash or XOF implementation used by the expander. */\n hash: CHash;\n};\n/**\n * Map one hash-to-field output tuple onto affine curve coordinates.\n * Implementations receive the validated scalar tuple by reference for performance and MUST treat it\n * as read-only. Callers that need scratch space should copy before mutating.\n * @param scalar - Field-element tuple produced by `hash_to_field`.\n * @returns Affine point before subgroup clearing.\n */\nexport type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;\n\n// Separated from initialization opts, so users won't accidentally change per-curve parameters\n// (changing DST is ok!)\n/** Per-call override for the domain-separation tag. */\nexport type H2CDSTOpts = {\n /** Domain-separation tag override. */\n DST: AsciiOrBytes;\n};\n/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */\nexport type H2CHasherBase<PC extends PC_ANY> = {\n /**\n * Hash arbitrary bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after hash-to-curve.\n */\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /**\n * Hash arbitrary bytes to one scalar.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Scalar reduced into the target field.\n */\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint;\n /**\n * Derive one curve point from non-uniform bytes without the random-oracle\n * guarantees of `hashToCurve`.\n * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve\n * path instead of the random-oracle construction.\n */\n deriveToCurve?(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Point constructor for the target curve. */\n Point: PC;\n};\n/**\n * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}.\n *\n * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing)\n * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing)\n * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing)\n */\nexport type H2CHasher<PC extends PC_ANY> = H2CHasherBase<PC> & {\n /**\n * Encode non-uniform bytes to one curve point.\n * @param msg - Input message bytes.\n * @param options - Optional domain-separation override. See {@link H2CDSTOpts}.\n * @returns Curve point after encode-to-curve.\n */\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC>;\n /** Deterministic map from `hash_to_field` tuples into affine coordinates. */\n mapToCurve: MapToCurve<PC_F<PC>>;\n /** Default RFC 9380 options captured by this hasher bundle. */\n defaults: H2CDefaults;\n};\n\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value: number, length: number): TRet<Uint8Array> {\n asafenumber(value);\n asafenumber(length);\n // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length);\n if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0) as number[];\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res) as TRet<Uint8Array>;\n}\n\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a: TArg<Uint8Array>, b: TArg<Uint8Array>): TRet<Uint8Array> {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr as TRet<Uint8Array>;\n}\n\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST: TArg<AsciiOrBytes>): TRet<Uint8Array> {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n // RFC 9380 §3.1 requirement 2: tags \"MUST have nonzero length\".\n if (dst.length === 0) throw new Error('DST must be non-empty');\n return dst as TRet<Uint8Array>;\n}\n\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array<Uint8Array>(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n // by reaching `I2OSP(256, 1)`.\n for (let i = 1; i < ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n * new TextEncoder().encode('hello noble'),\n * 'DST',\n * 32,\n * 128,\n * shake256\n * );\n * ```\n */\nexport function expand_message_xof(\n msg: TArg<Uint8Array>,\n DST: TArg<AsciiOrBytes>,\n lenInBytes: number,\n k: number,\n H: TArg<CHash>\n): TRet<Uint8Array> {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // RFC 9380 §5.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (\n H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest()\n );\n}\n\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n * DST: 'DST',\n * p: 17n,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(\n msg: TArg<Uint8Array>,\n count: number,\n options: TArg<H2COpts>\n): bigint[][] {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires\n // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n if (count < 1) throw new Error('hash_to_field: expected count >= 1');\n if (m < 1) throw new Error('hash_to_field: expected m >= 1');\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n } else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n } else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n } else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n\ntype XY<T> = (x: T, y: T) => { x: T; y: T };\ntype XYRatio<T> = [T[], T[], T[], T[]]; // xn/xd, yn/yd\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap<T, F extends IField<T>>(field: F, map: XYRatio<T>): XY<T> {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x: T, y: T) => {\n const [xn, xd, yn, yd] = coeff.map((val) =>\n val.reduce((acc, i) => field.add(field.mul(acc, x), i))\n );\n // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must\n // return the identity on E.\n // Shipped Weierstrass consumers encode that affine identity as all-zero\n // coordinates, so `passZero=true` intentionally collapses zero\n // denominators to `{ x: 0, y: 0 }`.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-' as const;\n\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n * the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n * DST: 'P256_XMD:SHA-256_SSWU_RO_',\n * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n * p: p256.Point.Fp.ORDER,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher<PC extends PC_ANY>(\n Point: PC,\n mapToCurve: MapToCurve<PC_F<PC>>,\n defaults: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>\n): H2CHasher<PC> {\n if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined');\n // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n const snapshot = (src: TArg<H2COpts & { encodeDST?: AsciiOrBytes }>): TRet<H2CDefaults> =>\n Object.freeze({\n ...src,\n DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n ...(src.encodeDST === undefined\n ? {}\n : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n }) as TRet<H2CDefaults>;\n // Keep one private defaults snapshot for actual hashing and expose fresh\n // detached snapshots via the public getter.\n // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n // the singleton hasher for every other consumer in the same process.\n const safeDefaults = snapshot(defaults);\n function map(num: bigint[]): PC_P<PC> {\n return Point.fromAffine(mapToCurve(num)) as PC_P<PC>;\n }\n function clear(initial: PC_P<PC>): PC_P<PC> {\n const P = initial.clearCofactor();\n // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n if (P.equals(Point.ZERO)) return Point.ZERO as PC_P<PC>;\n P.assertValidity();\n return P as PC_P<PC>;\n }\n\n return Object.freeze({\n get defaults() {\n return snapshot(safeDefaults);\n },\n Point,\n\n hashToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const opts = Object.assign({}, safeDefaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1) as PC_P<PC>);\n },\n encodeToCurve(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): PC_P<PC> {\n const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n const opts = Object.assign({}, safeDefaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars: bigint | bigint[]): PC_P<PC> {\n // Curves with m=1 accept only single scalar\n if (safeDefaults.m === 1) {\n if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars)) throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint') throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n hashToScalar(msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>): bigint {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n });\n}\n","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abignumber,\n abool,\n abytes,\n aInRange,\n asafenumber,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type HmacFn,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n FpIsSquare,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)`\n * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1\n * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1\n * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n /** Cube root of unity used by the GLV endomorphism. */\n beta: bigint;\n /** Reduced lattice basis used for scalar splitting. */\n basises?: EndoBasis;\n /**\n * Optional custom scalar-splitting helper.\n * Receives one scalar and returns two half-sized scalar components.\n */\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n /** Whether the first split scalar should be negated. */\n k1neg: boolean;\n /** Absolute value of the first split scalar. */\n k1: bigint;\n /** Whether the second split scalar should be negated. */\n k2neg: boolean;\n /** Absolute value of the second split scalar. */\n k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n /** Whether to hash the message before signature recovery. */\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n /** Whether to hash the message before verification. */\n prehash?: boolean;\n /** Whether to reject high-S signatures. */\n lowS?: boolean;\n /** Signature encoding to accept. */\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n * security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n /** Whether to hash the message before signing. */\n prehash?: boolean;\n /** Whether to normalize signatures into the low-S half-order. */\n lowS?: boolean;\n /** Signature encoding to produce. */\n format?: ECDSASignatureFormat;\n /** Optional hedging input for deterministic k generation. */\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts<T extends ECDSASignOpts, D extends Required<ECDSASignOpts>>(\n opts: T,\n def: D\n): D {\n validateObject(opts);\n const optsn = {} as D;\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def) as (keyof D)[]) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint<T> extends CurvePoint<T, WeierstrassPoint<T>> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /**\n * Encode the point into compressed or uncompressed SEC1 bytes.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point bytes.\n */\n toBytes(isCompressed?: boolean): TRet<Uint8Array>;\n /**\n * Encode the point into compressed or uncompressed SEC1 hex.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point hex.\n */\n toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons<T> extends CurvePointCons<WeierstrassPoint<T>> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint<T>;\n /**\n * Return the curve parameters captured by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): WeierstrassOpts<T>;\n}\n\n/**\n * Weierstrass curve options.\n *\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, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts<T> = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Weierstrass curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts<T> = Partial<{\n /** Optional base-field override. */\n Fp: IField<T>;\n /** Optional scalar-field override. */\n Fn: IField<bigint>;\n /** Whether the point constructor accepts infinity points. */\n allowInfinityPoint: boolean;\n /** Optional GLV endomorphism data. */\n endo: EndomorphismOpts;\n /** Optional torsion-check override. */\n isTorsionFree: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => boolean;\n /** Optional cofactor-clearing override. */\n clearCofactor: (c: WeierstrassPointCons<T>, point: WeierstrassPoint<T>) => WeierstrassPoint<T>;\n /** Optional custom point decoder. */\n fromBytes: (bytes: TArg<Uint8Array>) => AffinePoint<T>;\n /** Optional custom point encoder. */\n toBytes: (\n c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ) => TRet<Uint8Array>;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n * low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n * `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n /** Default low-S policy for this ECDSA instance. */\n lowS: boolean;\n /** HMAC implementation used by RFC6979 DRBG. */\n hmac: HmacFn;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet<Uint8Array>;\n /** Hash-to-integer conversion override. */\n bits2int: (bytes: TArg<Uint8Array>) => bigint;\n /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n bits2int_modN: (bytes: TArg<Uint8Array>) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\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 * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg<Uint8Array>, isCompressed?: boolean) => TRet<Uint8Array>;\n /**\n * Compute the shared secret point from a secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded shared point.\n */\n getSharedSecret: (\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed?: boolean\n ) => TRet<Uint8Array>;\n /** Point constructor used by this ECDH instance. */\n Point: WeierstrassPointCons<bigint>;\n /** Validation and random-key helpers. */\n utils: {\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>, isCompressed?: boolean) => boolean;\n /** Generate a valid random secret key. */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n };\n /** Byte lengths for keys and signatures exposed by this curve. */\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n /**\n * Sign a message with the given secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts?: TArg<ECDSASignOpts>\n ) => TRet<Uint8Array>;\n /**\n * Verify a signature against a message and public key.\n * @param signature - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n * @returns Whether the signature is valid.\n */\n verify: (\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts?: TArg<ECDSAVerifyOpts>\n ) => boolean;\n /**\n * Recover the public key encoded into a recoverable signature.\n * @param signature - Recoverable signature bytes.\n * @param message - Message bytes.\n * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n * @returns Encoded recovered public key.\n */\n recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts?: TArg<ECDSARecoverOpts>\n ): TRet<Uint8Array>;\n /** Signature constructor and parser helpers. */\n Signature: ECDSASignatureCons;\n}\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n // asn.1 DER encoding utils\n /**\n * DER-specific error constructor.\n * @param m - Error message.\n * @returns DER-specific error instance.\n */\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n /** Low-level tag-length-value helpers used by DER encoders. */\n _tlv: {\n /**\n * Encode one TLV record.\n * @param tag - ASN.1 tag byte.\n * @param data - Hex-encoded value payload.\n * @returns Encoded TLV string.\n */\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n /**\n * Decode one TLV record and return the value plus leftover bytes.\n * @param tag - Expected ASN.1 tag byte.\n * @param data - Remaining DER bytes.\n * @returns Parsed value plus leftover bytes.\n */\n decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }>;\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n /** Positive-integer DER helpers used by ECDSA signature encoding. */\n _int: {\n /**\n * Encode one positive bigint as a DER INTEGER.\n * @param num - Positive integer to encode.\n * @returns Encoded DER INTEGER.\n */\n encode(num: bigint): string;\n /**\n * Decode one DER INTEGER into a bigint.\n * @param data - DER INTEGER bytes.\n * @returns Decoded bigint.\n */\n decode(data: TArg<Uint8Array>): bigint;\n };\n /**\n * Parse a DER signature into `{ r, s }`.\n * @param bytes - DER signature bytes.\n * @returns Parsed signature components.\n */\n toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint };\n /**\n * Encode `{ r, s }` as a DER signature.\n * @param sig - Signature components.\n * @returns DER-encoded signature hex.\n */\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof data);\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: TArg<Uint8Array>): TRet<{ v: Uint8Array; l: Uint8Array }> {\n const { Err: E } = DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n abignumber(num);\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: TArg<Uint8Array>): bigint {\n const { Err: E } = DER;\n if (data.length < 1) throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes: TArg<Uint8Array>): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\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), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass<T>(\n params: WeierstrassOpts<T>,\n extraOpts: WeierstrassExtraOpts<T> = {}\n): WeierstrassPointCons<T> {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp as IField<T>;\n const Fn = validated.Fn as IField<bigint>;\n let CURVE = validated.CURVE as WeierstrassOpts<T>;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp as TArg<IField<T>>, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons<T>,\n point: WeierstrassPoint<T>,\n isCompressed: boolean\n ): TRet<Uint8Array> {\n // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet<Uint8Array>;\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx) as TRet<Uint8Array>;\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet<Uint8Array>;\n }\n }\n function pointFromBytes(bytes: TArg<Uint8Array>) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x² * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y² == x³ + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n return Fp.eql(left, right);\n }\n\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y² = x³ + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown): asserts other is Point {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint<T> {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts<T> {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: TArg<Uint8Array>): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: WeierstrassPoint<T>): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: WeierstrassPoint<T>): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: WeierstrassPoint<T>) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-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)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\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 secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint<T> {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n if (cofactor === _1n) return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n\n toBytes(isCompressed = true): TRet<Uint8Array> {\n abool(isCompressed, 'isCompressed');\n // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\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 (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/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n /** Signature component `r`. */\n readonly r: bigint;\n /** Signature component `s`. */\n readonly s: bigint;\n /** Optional recovery bit for recoverable signatures. */\n readonly recovery?: number;\n /**\n * Return a copy of the signature with a recovery bit attached.\n * @param recovery - Recovery bit to attach.\n * @returns Signature with an attached recovery bit.\n */\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n /**\n * Check whether the signature uses the high-S half-order.\n * @returns Whether the signature uses the high-S half-order.\n */\n hasHighS(): boolean;\n /**\n * Recover the public key from the hashed message and recovery bit.\n * @param messageHash - Hashed message bytes.\n * @returns Recovered public-key point.\n */\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint>;\n /**\n * Encode the signature into bytes.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature bytes.\n */\n toBytes(format?: string): TRet<Uint8Array>;\n /**\n * Encode the signature into hex.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature hex.\n */\n toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n /** Create a signature from `r`, `s`, and an optional recovery bit. */\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n /**\n * Decode a signature from bytes.\n * @param bytes - Encoded signature bytes.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromBytes(bytes: TArg<Uint8Array>, format?: ECDSASignatureFormat): ECDSASignature;\n /**\n * Decode a signature from hex.\n * @param hex - Encoded signature hex.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet<Uint8Array> {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet<Uint8Array>;\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio<T>(\n Fp: TArg<IField<T>>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp as IField<T>) as IField<T>;\n // Generic implementation\n const q = F.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: TArg<IField<T>>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n const F = validateField(Fp as IField<T>) as IField<T>;\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 §6.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField<T>` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths<T>(Fp: TArg<IField<T>>, Fn: TArg<IField<bigint>>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(\n Point: WeierstrassPointCons<bigint>,\n ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet<Uint8Array> }> = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n\n function isValidSecretKey(secretKey: TArg<Uint8Array>) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: TArg<Uint8Array>, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed?: TArg<Uint8Array>): TRet<Uint8Array> {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet<Uint8Array>;\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: TArg<Uint8Array>, isCompressed = true): TRet<Uint8Array> {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: TArg<Uint8Array>): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n if (!isBytes(item)) return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec) return undefined;\n return isPub;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(\n secretKeyA: TArg<Uint8Array>,\n publicKeyB: TArg<Uint8Array>,\n isCompressed = true\n ): TRet<Uint8Array> {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons<bigint>,\n hash: TArg<CHash>,\n ecdsaOpts: TArg<ECDSAOpts> = {}\n): ECDSA {\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash as CHash;\n ahash(hash_);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac =\n ecdsaOpts.hmac === undefined\n ? (key: TArg<Uint8Array>, msg: TArg<Uint8Array>) => nobleHmac(hash_, key, msg)\n : (ecdsaOpts.hmac as HmacFn);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required<ECDSASignOpts> = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertRecoverableCurve(): void {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: TArg<Uint8Array>, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: TArg<Uint8Array>,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash: TArg<Uint8Array>): WeierstrassPoint<bigint> {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet<Uint8Array> {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet<Uint8Array>;\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet<Uint8Array>;\n }\n return concatBytes(rb, sb) as TRet<Uint8Array>;\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int === undefined\n ? function bits2int_def(bytes: TArg<Uint8Array>): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : (ecdsaOpts.bits2int as (bytes: TArg<Uint8Array>) => bigint);\n const bits2int_modN: (bytes: TArg<Uint8Array>) => bigint =\n ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes: TArg<Uint8Array>): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : (ecdsaOpts.bits2int_modN as (bytes: TArg<Uint8Array>) => bigint);\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): TRet<Uint8Array> {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num) as TRet<Uint8Array>;\n }\n\n function validateMsgAndHash(message: TArg<Uint8Array>, prehash: boolean): TRet<Uint8Array> {\n abytes(message, undefined, 'message');\n return (\n prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n ) as TRet<Uint8Array>;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts>\n ) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs: TArg<Uint8Array>[] = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs) as TRet<Uint8Array>; // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k⋅G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: TArg<Uint8Array>): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(\n message: TArg<Uint8Array>,\n secretKey: TArg<Uint8Array>,\n opts: TArg<ECDSASignOpts> = {}\n ): TRet<Uint8Array> {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg<Signature>(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1⋅G + u2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n publicKey: TArg<Uint8Array>,\n opts: TArg<ECDSAVerifyOpts> = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: TArg<Uint8Array>,\n message: TArg<Uint8Array>,\n opts: TArg<ECDSARecoverOpts> = {}\n ): TRet<Uint8Array> {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n }) satisfies Signer;\n}\n","/**\n * BLS != BLS.\n * The file implements BLS (Boneh-Lynn-Shacham) signatures.\n * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig)\n * families of pairing-friendly curves.\n * Consists of two curves: G1 and G2:\n * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.\n * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1\n * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in\n * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not.\n * Pairing is used to aggregate and verify signatures.\n * There are two modes of operation:\n * - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs).\n * - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs).\n * @module\n **/\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes, notImplemented, randomBytes, type TArg, type TRet } from '../utils.ts';\nimport { type CurveLengths } from './curve.ts';\nimport {\n createHasher,\n type H2CDSTOpts,\n type H2CHasher,\n type H2COpts,\n type MapToCurve,\n} from './hash-to-curve.ts';\nimport { getMinHashLength, mapHashToField, type IField } from './modular.ts';\nimport type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6Bls } from './tower.ts';\nimport { type WeierstrassPoint, type WeierstrassPointCons } from './weierstrass.ts';\n\ntype Fp = bigint; // Can be different field?\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n\n/**\n * Twist convention used by the pairing formulas for a concrete curve family.\n * BLS12-381 uses a multiplicative twist, while BN254 uses a divisive one.\n */\nexport type BlsTwistType = 'multiplicative' | 'divisive';\n\n/**\n * Codec exposed as `curve.shortSignatures.Signature`.\n * Use it to parse or serialize G1 signatures in short-signature mode.\n * In this mode, public keys live in G2.\n */\nexport type BlsShortSignatureCoder<Fp> = {\n /**\n * Parse a compressed signature from raw bytes.\n * @param bytes - Compressed signature bytes.\n * @returns Parsed signature point.\n */\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;\n /**\n * Parse a compressed signature from a hex string.\n * @param hex - Compressed signature hex string.\n * @returns Parsed signature point.\n */\n fromHex(hex: string): WeierstrassPoint<Fp>;\n /**\n * Encode a signature point into compressed bytes.\n * @param point - Signature point.\n * @returns Compressed signature bytes.\n */\n toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;\n /**\n * Encode a signature point into a hex string.\n * @param point - Signature point.\n * @returns Compressed signature hex.\n */\n toHex(point: WeierstrassPoint<Fp>): string;\n};\n\n/**\n * Codec exposed as `curve.longSignatures.Signature`.\n * Use it to parse or serialize G2 signatures in long-signature mode.\n * In this mode, public keys live in G1.\n */\nexport type BlsLongSignatureCoder<Fp> = {\n /**\n * Parse a compressed signature from raw bytes.\n * @param bytes - Compressed signature bytes.\n * @returns Parsed signature point.\n */\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp>;\n /**\n * Parse a compressed signature from a hex string.\n * @param hex - Compressed signature hex string.\n * @returns Parsed signature point.\n */\n fromHex(hex: string): WeierstrassPoint<Fp>;\n /**\n * Encode a signature point into compressed bytes.\n * @param point - Signature point.\n * @returns Compressed signature bytes.\n */\n toBytes(point: WeierstrassPoint<Fp>): TRet<Uint8Array>;\n /**\n * Encode a signature point into a hex string.\n * @param point - Signature point.\n * @returns Compressed signature hex.\n */\n toHex(point: WeierstrassPoint<Fp>): string;\n};\n\n/** Tower fields needed by pairing code, hash-to-curve, and subgroup arithmetic. */\nexport type BlsFields = {\n /** Base field of G1 coordinates. */\n Fp: IField<Fp>;\n /** Scalar field used for secret scalars and subgroup order arithmetic. */\n Fr: IField<bigint>;\n /** Quadratic extension field used by G2. */\n Fp2: Fp2Bls;\n /** Sextic extension field used inside pairing arithmetic. */\n Fp6: Fp6Bls;\n /** Degree-12 extension field that contains the GT target group. */\n Fp12: Fp12Bls;\n};\n\n/**\n * Callback used by pairing post-processing hooks to add one more G2 point to the Miller-loop state.\n * @param Rx - Current projective X coordinate.\n * @param Ry - Current projective Y coordinate.\n * @param Rz - Current projective Z coordinate.\n * @param Qx - G2 affine x coordinate.\n * @param Qy - G2 affine y coordinate.\n * @returns Updated projective accumulator coordinates.\n */\nexport type BlsPostPrecomputePointAddFn = (\n Rx: Fp2,\n Ry: Fp2,\n Rz: Fp2,\n Qx: Fp2,\n Qy: Fp2\n) => { Rx: Fp2; Ry: Fp2; Rz: Fp2 };\n/**\n * Hook for curve-specific pairing cleanup after the Miller loop precomputes are built.\n * @param Rx - Current projective X coordinate.\n * @param Ry - Current projective Y coordinate.\n * @param Rz - Current projective Z coordinate.\n * @param Qx - G2 affine x coordinate.\n * @param Qy - G2 affine y coordinate.\n * @param pointAdd - Callback used to fold one more point into the accumulator.\n */\nexport type BlsPostPrecomputeFn = (\n Rx: Fp2,\n Ry: Fp2,\n Rz: Fp2,\n Qx: Fp2,\n Qy: Fp2,\n pointAdd: BlsPostPrecomputePointAddFn\n) => void;\n/** Low-level pairing helpers shared by BLS curve bundles. */\nexport type BlsPairing = {\n /** Byte lengths for keys and signatures exposed by this pairing family. */\n lengths: CurveLengths;\n /** Scalar field used by the pairing and signing helpers. */\n Fr: IField<bigint>;\n /** Target field used for the GT result of pairings. */\n Fp12: Fp12Bls;\n /**\n * Build Miller-loop precomputes for one G2 point.\n * @param p - G2 point to precompute.\n * @returns Pairing precompute table.\n */\n calcPairingPrecomputes: (p: WeierstrassPoint<Fp2>) => Precompute;\n /**\n * Evaluate a batch of Miller loops from precomputed line coefficients.\n * @param pairs - Precomputed Miller-loop inputs.\n * @returns Accumulated GT value before or after final exponentiation.\n */\n millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12;\n /**\n * Pair one G1 point with one G2 point.\n * @param P - G1 point.\n * @param Q - G2 point.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result.\n * @throws If either point is the point at infinity. {@link Error}\n */\n pairing: (P: WeierstrassPoint<Fp>, Q: WeierstrassPoint<Fp2>, withFinalExponent?: boolean) => Fp12;\n /**\n * Pair many G1/G2 pairs in one batch.\n * @param pairs - Point pairs to accumulate.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result. Empty input returns the multiplicative identity in GT.\n */\n pairingBatch: (\n pairs: { g1: WeierstrassPoint<Fp>; g2: WeierstrassPoint<Fp2> }[],\n withFinalExponent?: boolean\n ) => Fp12;\n /**\n * Generate a random secret key for this pairing family.\n * @param seed - Optional seed material.\n * @returns Secret key bytes.\n */\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n};\n\n/**\n * Parameters that define the Miller-loop shape and twist handling\n * for a concrete pairing family.\n */\nexport type BlsPairingParams = {\n // MSB is always ignored and used as marker for length, otherwise leading zeros will be lost.\n // Can be different from `X` (seed) param.\n /** Signed loop parameter used by the Miller loop. */\n ateLoopSize: bigint;\n /** Whether the signed Miller-loop parameter is negative. */\n xNegative: boolean;\n /**\n * Twist convention used by the pairing formulas.\n * BLS12-381 is multiplicative; BN254 is divisive.\n */\n twistType: BlsTwistType;\n /**\n * Optional RNG override used by helper constructors.\n * Receives the requested byte length and returns random bytes.\n */\n randomBytes?: (len?: number) => TRet<Uint8Array>;\n /**\n * Optional hook for curve-specific untwisting after precomputation.\n * Used by BN254 after the Miller loop.\n */\n postPrecompute?: BlsPostPrecomputeFn;\n};\n/** Hash-to-curve settings shared by the G1 and G2 hashers inside a BLS curve bundle. */\nexport type BlsHasherParams = {\n /**\n * Optional map-to-curve override for G1.\n * Receives the hash-to-field tuple and returns one affine G1 point.\n */\n mapToG1?: MapToCurve<Fp>;\n /**\n * Optional map-to-curve override for G2.\n * Receives the hash-to-field tuple and returns one affine G2 point.\n */\n mapToG2?: MapToCurve<Fp2>;\n /** Shared baseline hash-to-curve options. */\n hasherOpts: H2COpts;\n /** G1-specific hash-to-curve options merged on top of `hasherOpts`. */\n hasherOptsG1: H2COpts;\n /** G2-specific hash-to-curve options merged on top of `hasherOpts`. */\n hasherOptsG2: H2COpts;\n};\ntype PrecomputeSingle = [Fp2, Fp2, Fp2][];\ntype Precompute = PrecomputeSingle[];\n\n/**\n * BLS consists of two curves: G1 and G2:\n * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4.\n * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1\n */\nexport interface BlsCurvePair {\n /** Byte lengths for keys and signatures exposed by this curve family. */\n lengths: CurveLengths;\n /**\n * Shared Miller-loop batch evaluator.\n * @param pairs - Precomputed Miller-loop inputs.\n * @returns Accumulated GT value.\n */\n millerLoopBatch: BlsPairing['millerLoopBatch'];\n /**\n * Pair one G1 point with one G2 point.\n * @param P - G1 point.\n * @param Q - G2 point.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result.\n * @throws If either point is the point at infinity. {@link Error}\n */\n pairing: BlsPairing['pairing'];\n /**\n * Pair many G1/G2 pairs in one batch.\n * @param pairs - Point pairs to accumulate.\n * @param withFinalExponent - Whether to apply the final exponentiation step.\n * @returns GT pairing result. Empty input returns the multiplicative identity in GT.\n */\n pairingBatch: BlsPairing['pairingBatch'];\n /** G1 point constructor for the base field subgroup. */\n G1: { Point: WeierstrassPointCons<Fp> };\n /** G2 point constructor for the twist subgroup. */\n G2: { Point: WeierstrassPointCons<Fp2> };\n /** Tower fields exposed by the pairing implementation. */\n fields: {\n Fp: IField<Fp>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n Fr: IField<bigint>;\n };\n /** Utility helpers shared by hashers and signers. */\n utils: {\n randomSecretKey: (seed?: TArg<Uint8Array>) => TRet<Uint8Array>;\n calcPairingPrecomputes: BlsPairing['calcPairingPrecomputes'];\n };\n /** Public pairing parameters exposed for introspection. */\n params: {\n ateLoopSize: bigint;\n twistType: BlsTwistType;\n };\n}\n\n/** BLS curve bundle extended with hash-to-curve helpers for G1 and G2. */\nexport interface BlsCurvePairWithHashers extends BlsCurvePair {\n /** G1 hasher bundle with RFC 9380 helpers. */\n G1: H2CHasher<WeierstrassPointCons<Fp>>;\n /** G2 hasher bundle with RFC 9380 helpers. */\n G2: H2CHasher<WeierstrassPointCons<Fp2>>;\n}\n\n/** BLS curve bundle extended with both hashers and signature helpers. */\nexport interface BlsCurvePairWithSignatures extends BlsCurvePairWithHashers {\n /** Long-signature mode: G1 public keys and G2 signatures. */\n longSignatures: BlsSigs<bigint, Fp2>;\n /** Short-signature mode: G2 public keys and G1 signatures. */\n shortSignatures: BlsSigs<Fp2, bigint>;\n}\n\ntype BLSInput = TArg<Uint8Array>;\n/** BLS signer helpers for one signature mode. */\nexport interface BlsSigs<P, S> {\n /** Byte lengths for secret keys, public keys, and signatures. */\n lengths: CurveLengths;\n /**\n * Generate a secret/public key pair for this signature mode.\n * @param seed - Optional seed material.\n * @returns Secret and public key pair.\n */\n keygen(seed?: TArg<Uint8Array>): {\n secretKey: TRet<Uint8Array>;\n publicKey: WeierstrassPoint<P>;\n };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public-key point.\n */\n getPublicKey(secretKey: TArg<Uint8Array>): WeierstrassPoint<P>;\n /**\n * Sign a message already hashed onto the signature subgroup.\n * @param hashedMessage - Message mapped to the signature subgroup.\n * @param secretKey - Secret key bytes.\n * @returns Signature point.\n */\n sign(hashedMessage: WeierstrassPoint<S>, secretKey: TArg<Uint8Array>): WeierstrassPoint<S>;\n /**\n * Verify one signature against one public key and hashed message.\n * @param signature - Signature point or encoded signature.\n * @param message - Hashed message point.\n * @param publicKey - Public-key point or encoded key.\n * @returns Whether the signature is valid.\n */\n verify(\n signature: WeierstrassPoint<S> | BLSInput,\n message: WeierstrassPoint<S>,\n publicKey: WeierstrassPoint<P> | BLSInput\n ): boolean;\n /**\n * Verify one aggregated signature against many `(message, publicKey)` pairs.\n * @param signature - Aggregated signature.\n * @param items - Message/public-key pairs.\n * @returns Whether the aggregated signature is valid. Same-message aggregate verification still\n * requires proof of possession or another rogue-key defense from the caller.\n */\n verifyBatch: (\n signature: WeierstrassPoint<S> | BLSInput,\n items: { message: WeierstrassPoint<S>; publicKey: WeierstrassPoint<P> | BLSInput }[]\n ) => boolean;\n /**\n * Add many public keys into one aggregate point.\n * @param publicKeys - Public keys to aggregate.\n * @returns Aggregated public-key point. This is raw point addition and does not add proof of\n * possession or rogue-key protection on its own.\n */\n aggregatePublicKeys(publicKeys: (WeierstrassPoint<P> | BLSInput)[]): WeierstrassPoint<P>;\n /**\n * Add many signatures into one aggregate point.\n * @param signatures - Signatures to aggregate.\n * @returns Aggregated signature point. This is raw point addition and does not change the proof\n * of possession requirements of the aggregate-verification scheme.\n */\n aggregateSignatures(signatures: (WeierstrassPoint<S> | BLSInput)[]): WeierstrassPoint<S>;\n /**\n * Hash an arbitrary message onto the signature subgroup.\n * @param message - Message bytes.\n * @param DST - Optional domain separation tag.\n * @returns Curve point on the signature subgroup.\n */\n hash(message: TArg<Uint8Array>, DST?: TArg<string | Uint8Array>): WeierstrassPoint<S>;\n /** Signature codec for this mode. */\n Signature: BlsLongSignatureCoder<S>;\n}\n\n// Signed non-adjacent decomposition of the spec-defined Miller-loop parameter.\n// BN254 benefits most because `6x+2` has multiple adjacent `11` runs, but BLS12-381's\n// stored `|x|` still starts with `11`, so the Miller loop must also handle one `-1` digit there.\nfunction NAfDecomposition(a: bigint) {\n const res = [];\n // a>1 because of marker bit\n for (; a > _1n; a >>= _1n) {\n if ((a & _1n) === _0n) res.unshift(0);\n else if ((a & _3n) === _3n) {\n res.unshift(-1);\n a += _1n;\n } else res.unshift(1);\n }\n return res;\n}\nfunction aNonEmpty(arr: any[]) {\n // Aggregate helpers use this to reject empty variable-length inputs consistently.\n // Without the guard, each caller would fall through into a different empty-input / identity\n // case and hide missing inputs behind outputs that still look structurally valid.\n if (!Array.isArray(arr) || arr.length === 0) throw new Error('expected non-empty array');\n}\n\n// This should be enough for bn254, no need to export full stuff?\nfunction createBlsPairing(\n fields: TArg<BlsFields>,\n G1: WeierstrassPointCons<Fp>,\n G2: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>\n): BlsPairing {\n const { Fr, Fp2, Fp12 } = fields;\n const { twistType, ateLoopSize, xNegative, postPrecompute } = params;\n type G1 = typeof G1.BASE;\n type G2 = typeof G2.BASE;\n // Applies sparse multiplication as line function\n let lineFunction: (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => Fp12;\n if (twistType === 'multiplicative') {\n lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) =>\n Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py));\n } else if (twistType === 'divisive') {\n // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of\n // precompute calculations.\n lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) =>\n Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0);\n } else throw new Error('bls: unknown twist type');\n\n const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n));\n function pointDouble(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2) {\n const t0 = Fp2.sqr(Ry); // Ry²\n const t1 = Fp2.sqr(Rz); // Rz²\n const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B\n const t3 = Fp2.mul(t2, _3n); // 3 * T2\n const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0\n const c0 = Fp2.sub(t2, t0); // T2 - T0 (i)\n const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx²\n const c2 = Fp2.neg(t4); // -T4 (-h)\n\n ell.push([c0, c1, c2]);\n\n Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2\n // ((T0 + T3) / 2)² - 3 * T2²\n Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n));\n Rz = Fp2.mul(t0, t4); // T0 * T4\n return { Rx, Ry, Rz };\n }\n function pointAdd(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) {\n // Addition\n const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz\n const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz\n const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy\n const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry\n const c2 = t1; // == Rx - Qx * Rz\n\n ell.push([c0, c1, c2]);\n\n const t2 = Fp2.sqr(t1); // T1²\n const t3 = Fp2.mul(t2, t1); // T2 * T1\n const t4 = Fp2.mul(t2, Rx); // T2 * Rx\n // T3 - 2 * T4 + T0² * Rz\n const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz));\n Rx = Fp2.mul(t1, t5); // T1 * T5\n Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry\n Rz = Fp2.mul(Rz, t3); // Rz * T3\n return { Rx, Ry, Rz };\n }\n\n // Pre-compute coefficients for sparse multiplication\n // Point addition and point double calculations is reused for coefficients\n // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine\n // add + double in windowed precomputes here, otherwise it would be single op (since X is static)\n const ATE_NAF = NAfDecomposition(ateLoopSize);\n\n const calcPairingPrecomputes = (point: G2) => {\n const p = point;\n const { x, y } = p.toAffine();\n // prettier-ignore\n const Qx = x, Qy = y, negQy = Fp2.neg(y);\n // prettier-ignore\n let Rx = Qx, Ry = Qy, Rz = Fp2.ONE;\n const ell: Precompute = [];\n for (const bit of ATE_NAF) {\n const cur: PrecomputeSingle = [];\n ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz));\n if (bit) ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy));\n ell.push(cur);\n }\n if (postPrecompute) {\n const last = ell[ell.length - 1];\n postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last));\n }\n return ell;\n };\n\n // Main pairing logic is here. Computes product of miller loops + final exponentiate\n // Applies calculated precomputes\n type MillerInput = [Precompute, Fp, Fp][];\n function millerLoopBatch(pairs: MillerInput, withFinalExponent: boolean = false) {\n let f12 = Fp12.ONE;\n if (pairs.length) {\n const ellLen = pairs[0][0].length;\n for (let i = 0; i < ellLen; i++) {\n f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings\n // NOTE: we apply multiple pairings in parallel here\n for (const [ell, Px, Py] of pairs) {\n for (const [c0, c1, c2] of ell[i]) f12 = lineFunction(c0, c1, c2, f12, Px, Py);\n }\n }\n }\n if (xNegative) f12 = Fp12.conjugate(f12);\n return withFinalExponent ? Fp12.finalExponentiate(f12) : f12;\n }\n type PairingInput = { g1: G1; g2: G2 };\n // Calculates product of multiple pairings\n // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))`\n function pairingBatch(pairs: PairingInput[], withFinalExponent: boolean = true) {\n const res: MillerInput = [];\n for (const { g1, g2 } of pairs) {\n // Mathematically, a zero pairing term contributes GT.ONE. We still reject it here because\n // this API mainly backs BLS verification, where ZERO inputs usually mean broken hash /\n // wiring. Silently skipping them would turn those failures into a neutral pairing product.\n // Callers that want the algebraic neutral-element behavior can filter ZERO terms first.\n if (g1.is0() || g2.is0()) throw new Error('pairing is not available for ZERO point');\n // This uses toAffine inside\n g1.assertValidity();\n g2.assertValidity();\n const Qa = g1.toAffine();\n res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]);\n }\n return millerLoopBatch(res, withFinalExponent);\n }\n // Calculates bilinear pairing\n function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 {\n return pairingBatch([{ g1: Q, g2: P }], withFinalExponent);\n }\n const lengths = {\n seed: getMinHashLength(Fr.ORDER),\n };\n const rand = params.randomBytes === undefined ? randomBytes : params.randomBytes;\n // Seeded calls deterministically reduce exactly `lengths.seed` bytes into `1..Fr.ORDER-1`;\n // omitting `seed` just fills that input buffer from the configured RNG first.\n const randomSecretKey = (seed?: TArg<Uint8Array>): TRet<Uint8Array> => {\n seed = seed === undefined ? rand(lengths.seed) : seed;\n abytes(seed, lengths.seed, 'seed');\n return mapHashToField(seed, Fr.ORDER) as TRet<Uint8Array>;\n };\n Object.freeze(lengths);\n return {\n lengths,\n Fr,\n Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12!\n millerLoopBatch,\n pairing,\n pairingBatch,\n calcPairingPrecomputes,\n randomSecretKey,\n };\n}\n\nfunction createBlsSig<P, S>(\n blsPairing: BlsPairing,\n PubPoint: WeierstrassPointCons<P>,\n SigPoint: WeierstrassPointCons<S>,\n isSigG1: boolean,\n hashToSigCurve: (msg: TArg<Uint8Array>, options?: TArg<H2CDSTOpts>) => WeierstrassPoint<S>,\n SignatureCoder?: BlsLongSignatureCoder<S>\n): BlsSigs<P, S> {\n const { Fr, Fp12, pairingBatch, randomSecretKey, lengths } = blsPairing;\n if (!SignatureCoder) {\n SignatureCoder = {\n fromBytes: notImplemented,\n fromHex: notImplemented,\n toBytes: notImplemented,\n toHex: notImplemented,\n };\n }\n type PubPoint = WeierstrassPoint<P>;\n type SigPoint = WeierstrassPoint<S>;\n function normPub(point: PubPoint | BLSInput): PubPoint {\n return point instanceof PubPoint ? (point as PubPoint) : PubPoint.fromBytes(point);\n }\n function normSig(point: SigPoint | BLSInput): SigPoint {\n return point instanceof SigPoint ? (point as SigPoint) : SigPoint.fromBytes(point);\n }\n // Sign/verify here take points already hashed onto the signature subgroup.\n // Raw bytes and points from the other subgroup must fail this constructor-brand\n // check before later validity checks run.\n function amsg(m: unknown): SigPoint {\n if (!(m instanceof SigPoint))\n throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`);\n return m as SigPoint;\n }\n\n type G1 = WeierstrassPoint<Fp>;\n type G2 = WeierstrassPoint<Fp2>;\n type PairingInput = { g1: G1; g2: G2 };\n // What matters here is what point pairing API accepts as G1 or G2, not actual size or names\n const pair: (a: PubPoint, b: SigPoint) => PairingInput = !isSigG1\n ? (a: PubPoint, b: SigPoint) => ({ g1: a, g2: b }) as PairingInput\n : (a: PubPoint, b: SigPoint) => ({ g1: b, g2: a }) as PairingInput;\n return Object.freeze({\n lengths: Object.freeze({ ...lengths, secretKey: Fr.BYTES }),\n keygen(seed?: TArg<Uint8Array>) {\n const secretKey = randomSecretKey(seed);\n const publicKey = this.getPublicKey(secretKey);\n return { secretKey, publicKey };\n },\n // P = pk x G\n getPublicKey(secretKey: TArg<Uint8Array>): PubPoint {\n let sec;\n try {\n sec = PubPoint.Fn.fromBytes(secretKey);\n } catch (error) {\n // @ts-ignore\n throw new Error('invalid private key: ' + typeof secretKey, { cause: error });\n }\n return PubPoint.BASE.multiply(sec);\n },\n // S = pk x H(m)\n sign(message: SigPoint, secretKey: TArg<Uint8Array>, unusedArg?: any): SigPoint {\n if (unusedArg != null) throw new Error('sign() expects 2 arguments');\n const sec = PubPoint.Fn.fromBytes(secretKey);\n amsg(message).assertValidity();\n return message.multiply(sec);\n },\n // Checks if pairing of public key & hash is equal to pairing of generator & signature.\n // e(P, H(m)) == e(G, S)\n // e(S, G) == e(H(m), P)\n verify(\n signature: SigPoint | BLSInput,\n message: SigPoint,\n publicKey: PubPoint | BLSInput,\n unusedArg?: any\n ): boolean {\n if (unusedArg != null) throw new Error('verify() expects 3 arguments');\n signature = normSig(signature);\n publicKey = normPub(publicKey);\n const P = publicKey.negate();\n const G = PubPoint.BASE;\n const Hm = amsg(message);\n const S = signature;\n // This code was changed in 1.9.x:\n // Before it was G.negate() in G2, now it's always pubKey.negate\n // e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair).\n // We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1\n try {\n const exp = pairingBatch([pair(P, Hm), pair(G, S)]);\n return Fp12.eql(exp, Fp12.ONE);\n } catch {\n return false;\n }\n },\n // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407\n // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))\n // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead?\n verifyBatch(\n signature: SigPoint | BLSInput,\n items: { message: SigPoint; publicKey: PubPoint | BLSInput }[]\n ): boolean {\n aNonEmpty(items);\n const sig = normSig(signature);\n const nMessages = items.map((i) => i.message);\n const nPublicKeys = items.map((i) => normPub(i.publicKey));\n // NOTE: this works only for exact same object\n const messagePubKeyMap = new Map<SigPoint, PubPoint[]>();\n for (let i = 0; i < nPublicKeys.length; i++) {\n const pub = nPublicKeys[i];\n const msg = nMessages[i];\n let keys = messagePubKeyMap.get(msg);\n if (keys === undefined) {\n keys = [];\n messagePubKeyMap.set(msg, keys);\n }\n keys.push(pub);\n }\n const paired = [];\n const G = PubPoint.BASE;\n try {\n for (const [msg, keys] of messagePubKeyMap) {\n const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg));\n paired.push(pair(groupPublicKey, msg));\n }\n paired.push(pair(G.negate(), sig));\n return Fp12.eql(pairingBatch(paired), Fp12.ONE);\n } catch {\n return false;\n }\n },\n // Adds a bunch of public key points together.\n // pk1 + pk2 + pk3 = pkA\n aggregatePublicKeys(publicKeys: (PubPoint | BLSInput)[]): PubPoint {\n aNonEmpty(publicKeys);\n publicKeys = publicKeys.map((pub) => normPub(pub));\n const agg = (publicKeys as PubPoint[]).reduce((sum, p) => sum.add(p), PubPoint.ZERO);\n agg.assertValidity();\n return agg;\n },\n\n // Adds a bunch of signature points together.\n // pk1 + pk2 + pk3 = pkA\n aggregateSignatures(signatures: (SigPoint | BLSInput)[]): SigPoint {\n aNonEmpty(signatures);\n signatures = signatures.map((sig) => normSig(sig));\n const agg = (signatures as SigPoint[]).reduce((sum, s) => sum.add(s), SigPoint.ZERO);\n agg.assertValidity();\n return agg;\n },\n\n hash(messageBytes: TArg<Uint8Array>, DST?: TArg<string | Uint8Array>): SigPoint {\n abytes(messageBytes);\n const opts = DST ? { DST } : undefined;\n return hashToSigCurve(messageBytes, opts);\n },\n Signature: Object.freeze({ ...SignatureCoder }),\n }) /*satisfies Signer */;\n}\n\ntype BlsSignatureCoders = Partial<{\n LongSignature: BlsLongSignatureCoder<Fp2>;\n ShortSignature: BlsShortSignatureCoder<Fp>;\n}>;\n\n// NOTE: separate function instead of function override, so we don't depend on hasher in bn254.\n/**\n * @param fields - Tower field implementations.\n * @param G1_Point - G1 point constructor.\n * @param G2_Point - G2 point constructor.\n * @param params - Pairing parameters. See {@link BlsPairingParams}.\n * @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while\n * empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the\n * low-level pairing API fail-closed for BLS-style callers, where identity points usually signal\n * broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly\n * precomputes the G1 base-point table as a performance side effect.\n * @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error}\n * @example\n * ```ts\n * import { blsBasic } from '@noble/curves/abstract/bls.js';\n * import { bn254 } from '@noble/curves/bn254.js';\n * // Pair a G1 point with a G2 point without the higher-level signer helpers.\n * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE);\n * ```\n */\nexport function blsBasic(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>\n): BlsCurvePair {\n // Fields are specific for curve, so for now we'll need to pass them with opts\n const { Fp, Fr, Fp2, Fp6, Fp12 } = fields;\n // Point on G1 curve: (x, y)\n // const G1_Point = weierstrass(CURVE.G1, { Fn: Fr });\n const G1 = { Point: G1_Point };\n // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i)\n const G2 = { Point: G2_Point };\n\n const pairingRes = createBlsPairing(fields, G1_Point, G2_Point, params);\n const {\n millerLoopBatch,\n pairing,\n pairingBatch,\n calcPairingPrecomputes,\n randomSecretKey,\n lengths,\n } = pairingRes;\n\n G1.Point.BASE.precompute(4);\n Object.freeze(G1);\n Object.freeze(G2);\n return Object.freeze({\n lengths: Object.freeze(lengths),\n millerLoopBatch,\n pairing,\n pairingBatch,\n G1,\n G2,\n fields: Object.freeze({ Fr, Fp, Fp2, Fp6, Fp12 }),\n params: Object.freeze({\n ateLoopSize: params.ateLoopSize,\n twistType: params.twistType,\n }),\n utils: Object.freeze({\n randomSecretKey,\n calcPairingPrecomputes,\n }),\n });\n}\n\n// We can export this too, but seems there is not much reasons for now? If user wants hasher, they can just create hasher.\nfunction blsHashers(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>,\n hasherParams: TArg<BlsHasherParams>\n): BlsCurvePairWithHashers {\n const base = blsBasic(fields, G1_Point, G2_Point, params);\n // Missing map hooks intentionally fail closed via notImplemented on first hash use.\n const G1Hasher = createHasher(\n G1_Point,\n hasherParams.mapToG1 === undefined ? notImplemented : hasherParams.mapToG1,\n {\n ...hasherParams.hasherOpts,\n ...hasherParams.hasherOptsG1,\n }\n );\n const G2Hasher = createHasher(\n G2_Point,\n hasherParams.mapToG2 === undefined ? notImplemented : hasherParams.mapToG2,\n {\n ...hasherParams.hasherOpts,\n ...hasherParams.hasherOptsG2,\n }\n );\n return Object.freeze({ ...base, G1: G1Hasher, G2: G2Hasher });\n}\n\n// G1_Point: ProjConstructor<bigint>, G2_Point: ProjConstructor<Fp2>,\n// Rename to blsSignatures?\n/**\n * @param fields - Tower field implementations.\n * @param G1_Point - G1 point constructor.\n * @param G2_Point - G2 point constructor.\n * @param params - Pairing parameters. See {@link BlsPairingParams}.\n * @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}.\n * @param signatureCoders - Signature codecs.\n * @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs,\n * and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate\n * verification still requires proof of possession or another rogue-key defense from the caller.\n * @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error}\n * @example\n * ```ts\n * import { bls } from '@noble/curves/abstract/bls.js';\n * import { bls12_381 } from '@noble/curves/bls12-381.js';\n * const sigs = bls12_381.longSignatures;\n * // Use the full BLS helper set when you need hashing, keygen, signing, and verification.\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = sigs.hash(new TextEncoder().encode('hello noble'));\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function bls(\n fields: TArg<BlsFields>,\n G1_Point: WeierstrassPointCons<Fp>,\n G2_Point: WeierstrassPointCons<Fp2>,\n params: TArg<BlsPairingParams>,\n hasherParams: TArg<BlsHasherParams>,\n signatureCoders: BlsSignatureCoders\n): BlsCurvePairWithSignatures {\n const base = blsHashers(fields, G1_Point, G2_Point, params, hasherParams);\n const pairingRes: BlsPairing = {\n ...base,\n Fr: base.fields.Fr,\n Fp12: base.fields.Fp12,\n calcPairingPrecomputes: base.utils.calcPairingPrecomputes,\n randomSecretKey: base.utils.randomSecretKey,\n };\n const longSignatures = createBlsSig(\n pairingRes,\n G1_Point,\n G2_Point,\n false,\n base.G2.hashToCurve,\n signatureCoders?.LongSignature\n );\n const shortSignatures = createBlsSig(\n pairingRes,\n G2_Point,\n G1_Point,\n true,\n base.G1.hashToCurve,\n signatureCoders?.ShortSignature\n );\n return Object.freeze({ ...base, longSignatures, shortSignatures });\n}\n","/**\n * Towered extension fields.\n * Rather than implementing a massive 12th-degree extension directly, it is more efficient\n * to build it up from smaller extensions: a tower of extensions.\n *\n * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension,\n * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp.\n *\n * For more info: \"Pairings for beginners\" by Costello, section 7.3.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes,\n aInRange,\n asafenumber,\n bitGet,\n bitLen,\n concatBytes,\n notImplemented,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport * as mod from './modular.ts';\nimport type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass.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), _3n = /* @__PURE__ */ BigInt(3), _6n = /* @__PURE__ */ BigInt(6), _12n = /* @__PURE__ */ BigInt(12);\n\n// Fp₂ over complex plane\n/** Pair of bigints used for quadratic-extension tuples. */\nexport type BigintTuple = [bigint, bigint];\n/** Prime-field element. */\nexport type Fp = bigint;\n// Finite extension field over irreducible polynominal.\n// Fp(u) / (u² - β) where β = -1\n/** Quadratic-extension field element `c0 + c1 * u`. */\nexport type Fp2 = {\n /** Real component. */\n c0: bigint;\n /** Imaginary component. */\n c1: bigint;\n};\n/** Six bigints used for sextic-extension tuples. */\nexport type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint];\n/** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */\nexport type Fp6 = {\n /** Constant coefficient. */\n c0: Fp2;\n /** Linear coefficient. */\n c1: Fp2;\n /** Quadratic coefficient. */\n c2: Fp2;\n};\n/**\n * Degree-12 extension field element `c0 + c1 * w`.\n * Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v.\n */\nexport type Fp12 = {\n /** Constant coefficient. */\n c0: Fp6;\n /** Linear coefficient. */\n c1: Fp6;\n};\n// prettier-ignore\n/** Twelve bigints used for degree-12 extension tuples. */\nexport type BigintTwelve = [\n bigint, bigint, bigint, bigint, bigint, bigint,\n bigint, bigint, bigint, bigint, bigint, bigint\n];\n\nconst isObj = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object';\n\n/** BLS-friendly helpers on top of the quadratic extension field. */\nexport type Fp2Bls = mod.IField<Fp2> & {\n /** Underlying prime field. */\n Fp: mod.IField<Fp>;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp2, power: number): Fp2;\n /** Build one field element from a raw bigint tuple. */\n fromBigTuple(num: BigintTuple): Fp2;\n /** Multiply by the curve `b` constant. */\n mulByB: (num: Fp2) => Fp2;\n /** Multiply by the quadratic non-residue. */\n mulByNonresidue: (num: Fp2) => Fp2;\n /** Split one quadratic element into real and imaginary components. */\n reim: (num: Fp2) => { re: Fp; im: Fp };\n /** Specialized helper used by sextic squaring formulas. */\n Fp4Square: (a: Fp2, b: Fp2) => { first: Fp2; second: Fp2 };\n /** Quadratic non-residue used by the extension. */\n NONRESIDUE: Fp2;\n};\n\n/** BLS-friendly helpers on top of the sextic extension field. */\nexport type Fp6Bls = mod.IField<Fp6> & {\n /** Underlying quadratic extension field. */\n Fp2: Fp2Bls;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp6, power: number): Fp6;\n /** Build one field element from a raw six-bigint tuple. */\n fromBigSix: (tuple: BigintSix) => Fp6;\n /** Multiply by a sparse `(0, b1, 0)` sextic element. */\n mul1(num: Fp6, b1: Fp2): Fp6;\n /** Multiply by a sparse `(b0, b1, 0)` sextic element. */\n mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6;\n /** Multiply by one quadratic-extension element. */\n mulByFp2(lhs: Fp6, rhs: Fp2): Fp6;\n /** Multiply by the sextic non-residue. */\n mulByNonresidue: (num: Fp6) => Fp6;\n};\n\n/** BLS-friendly helpers on top of the degree-12 extension field. */\nexport type Fp12Bls = mod.IField<Fp12> & {\n /** Underlying sextic extension field. */\n Fp6: Fp6Bls;\n /** Apply one Frobenius map. */\n frobeniusMap(num: Fp12, power: number): Fp12;\n /** Build one field element from a raw twelve-bigint tuple. */\n fromBigTwelve: (t: BigintTwelve) => Fp12;\n /** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */\n mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12;\n /** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */\n mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12;\n /** Multiply by one quadratic-extension element. */\n mulByFp2(lhs: Fp12, rhs: Fp2): Fp12;\n /** Conjugate one degree-12 element. */\n conjugate(num: Fp12): Fp12;\n /** Apply the final exponentiation from pairing arithmetic. */\n finalExponentiate(num: Fp12): Fp12;\n /** Apply one cyclotomic square. */\n _cyclotomicSquare(num: Fp12): Fp12;\n /** Apply one cyclotomic exponentiation. */\n _cyclotomicExp(num: Fp12, n: bigint): Fp12;\n};\n\nfunction calcFrobeniusCoefficients<T>(\n Fp: TArg<mod.IField<T>>,\n nonResidue: T,\n modulus: bigint,\n degree: number,\n num: number = 1,\n divisor?: number\n): T[][] {\n asafenumber(num, 'num');\n const F = Fp as mod.IField<T>;\n // Generic callers can hit empty / fractional row counts through `__TEST`; fail closed instead of\n // silently returning `[]` or deriving extra Frobenius rows from a truncated loop bound.\n if (num <= 0)\n throw new Error('calcFrobeniusCoefficients: expected positive row count, got ' + num);\n const _divisor = BigInt(divisor === undefined ? degree : divisor);\n const towerModulus: any = modulus ** BigInt(degree);\n const res: T[][] = [];\n // Derive tower-basis multipliers for the `p^k` Frobenius action. The\n // divisions below are expected to be exact for the chosen tower parameters.\n for (let i = 0; i < num; i++) {\n const a = BigInt(i + 1);\n const powers: T[] = [];\n for (let j = 0, qPower = _1n; j < degree; j++) {\n const numer = a * qPower - a;\n // Shipped towers divide cleanly here, but generic callers can pick bad\n // params. Bigint division would floor and derive the wrong Frobenius table.\n if (numer % _divisor) throw new Error('calcFrobeniusCoefficients: inexact tower exponent');\n const power = (numer / _divisor) % towerModulus;\n powers.push(F.pow(nonResidue, power));\n qPower *= modulus;\n }\n res.push(powers);\n }\n return res;\n}\n\nexport const __TEST: { calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients } =\n /* @__PURE__ */ Object.freeze({\n calcFrobeniusCoefficients,\n });\n\n// This works same at least for bls12-381, bn254 and bls12-377\n/**\n * @param Fp - Base field implementation.\n * @param Fp2 - Quadratic extension field.\n * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants.\n * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`.\n * @returns Frobenius endomorphism helpers.\n * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error}\n * @example\n * Build Frobenius endomorphism helpers for a BLS extension tower.\n *\n * ```ts\n * import { psiFrobenius } from '@noble/curves/abstract/tower.js';\n * import { bls12_381 } from '@noble/curves/bls12-381.js';\n * const Fp = bls12_381.fields.Fp;\n * const Fp2 = bls12_381.fields.Fp2;\n * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE));\n * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE);\n * ```\n */\nexport function psiFrobenius(\n Fp: TArg<mod.IField<Fp>>,\n Fp2: TArg<Fp2Bls>,\n base: TArg<Fp2>\n): {\n psi: (x: Fp2, y: Fp2) => [Fp2, Fp2];\n psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2];\n G2psi: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;\n G2psi2: (c: WeierstrassPointCons<Fp2>, P: WeierstrassPoint<Fp2>) => WeierstrassPoint<Fp2>;\n PSI_X: Fp2;\n PSI_Y: Fp2;\n PSI2_X: Fp2;\n PSI2_Y: Fp2;\n} {\n // GLV endomorphism Ψ(P)\n const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3)\n const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2)\n function psi(x: Fp2, y: Fp2): [Fp2, Fp2] {\n // This x10 faster than previous version in bls12-381\n const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X);\n const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y);\n return [x2, y2];\n }\n // Ψ²(P) endomorphism (psi2(x) = psi(psi(x)))\n const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3)\n // Current towers rely on this landing on `-1`, which lets psi2 map `y` with\n // one negation instead of carrying a separate Frobenius multiplier.\n const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/2)\n if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) throw new Error('psiFrobenius: PSI2_Y!==-1');\n function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] {\n return [Fp2.mul(x, PSI2_X), Fp2.neg(y)];\n }\n // Map points\n const mapAffine =\n <T>(fn: (x: T, y: T) => [T, T]) =>\n (c: WeierstrassPointCons<T>, P: WeierstrassPoint<T>) => {\n const affine = P.toAffine();\n const p = fn(affine.x, affine.y);\n return c.fromAffine({ x: p[0], y: p[1] });\n };\n const G2psi = mapAffine(psi);\n const G2psi2 = mapAffine(psi2);\n return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y };\n}\n\n/** Construction options for the BLS-style degree-12 tower. */\nexport type Tower12Opts = {\n /** Prime-field order. */\n ORDER: bigint;\n /** Bit length of the BLS parameter `x`. */\n X_LEN: number;\n /** Prime-field non-residue used by the quadratic extension. */\n NONRESIDUE?: Fp;\n /** Quadratic-extension non-residue used by the sextic tower. */\n FP2_NONRESIDUE: BigintTuple;\n /**\n * Optional custom quadratic square-root helper.\n * Receives one quadratic-extension element and returns one square root.\n */\n Fp2sqrt?: (num: Fp2) => Fp2;\n /**\n * Multiply one quadratic element by the curve `b` constant.\n * @param num - Quadratic-extension element to scale.\n * @returns Product by the curve `b` constant.\n */\n Fp2mulByB: (num: Fp2) => Fp2;\n /**\n * Final exponentiation used by pairing arithmetic.\n * @param num - Degree-12 field element to exponentiate.\n * @returns Pairing result after final exponentiation.\n */\n Fp12finalExponentiate: (num: Fp12) => Fp12;\n};\n\nclass _Field2 implements mod.IField<Fp2> {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp2;\n readonly ONE: Fp2;\n readonly Fp: mod.IField<bigint>;\n\n readonly NONRESIDUE: Fp2;\n readonly mulByB: Tower12Opts['Fp2mulByB'];\n readonly Fp_NONRESIDUE: bigint;\n readonly Fp_div2: bigint;\n readonly FROBENIUS_COEFFICIENTS: readonly Fp[];\n\n constructor(\n Fp: mod.IField<bigint>,\n opts: Partial<{\n NONRESIDUE: bigint;\n FP2_NONRESIDUE: BigintTuple;\n Fp2mulByB: Tower12Opts['Fp2mulByB'];\n }> = {}\n ) {\n const { NONRESIDUE = BigInt(-1), FP2_NONRESIDUE, Fp2mulByB } = opts;\n const ORDER = Fp.ORDER;\n const FP2_ORDER = ORDER * ORDER;\n this.Fp = Fp;\n this.ORDER = FP2_ORDER;\n this.BITS = bitLen(FP2_ORDER);\n this.BYTES = Math.ceil(bitLen(FP2_ORDER) / 8);\n this.isLE = Fp.isLE;\n this.ZERO = this.create({ c0: Fp.ZERO, c1: Fp.ZERO });\n this.ONE = this.create({ c0: Fp.ONE, c1: Fp.ZERO });\n\n // These knobs only swap constants for the shipped quadratic tower shape:\n // arithmetic below assumes `u^2 = -1`, and bytes are handled as two adjacent\n // `Fp` limbs (`fromBytes` / `toBytes` expect the shipped `2 * Fp.BYTES` layout).\n this.Fp_NONRESIDUE = Fp.create(NONRESIDUE);\n this.Fp_div2 = Fp.div(Fp.ONE, _2n); // 1/2\n this.NONRESIDUE = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] });\n // const Fp2Nonresidue = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] });\n this.FROBENIUS_COEFFICIENTS = Object.freeze(\n calcFrobeniusCoefficients(Fp, this.Fp_NONRESIDUE, Fp.ORDER, 2)[0]\n );\n this.mulByB = (num) => {\n // This config hook is trusted to return a canonical Fp2 value already.\n // Copy+freeze it to keep the tower immutability invariant without mutating caller objects.\n const { c0, c1 } = Fp2mulByB!(num);\n return Object.freeze({ c0, c1 });\n };\n Object.freeze(this);\n }\n fromBigTuple(tuple: BigintTuple) {\n if (!Array.isArray(tuple) || tuple.length !== 2) throw new Error('invalid Fp2.fromBigTuple');\n const [c0, c1] = tuple;\n if (typeof c0 !== 'bigint' || typeof c1 !== 'bigint')\n throw new Error('invalid Fp2.fromBigTuple');\n return this.create({ c0, c1 });\n }\n create(num: Fp2) {\n const { Fp } = this;\n const c0 = Fp.create(num.c0);\n const c1 = Fp.create(num.c1);\n // Bigint field elements are immutable values, and higher-level code relies on\n // that invariant. Copy+freeze tower values too without mutating caller-owned objects.\n return Object.freeze({ c0, c1 });\n }\n isValid(num: Fp2) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1 } = num;\n const { Fp } = this;\n // Match base-field `isValid(...)`: malformed coordinate types are errors, not a `false`\n // predicate result.\n return Fp.isValid(c0) && Fp.isValid(c1);\n }\n is0(num: Fp2) {\n if (!isObj(num)) return false;\n const { c0, c1 } = num;\n const { Fp } = this;\n return Fp.is0(c0) && Fp.is0(c1);\n }\n isValidNot0(num: Fp2) {\n return !this.is0(num) && this.isValid(num);\n }\n eql({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) {\n const { Fp } = this;\n return Fp.eql(c0, r0) && Fp.eql(c1, r1);\n }\n neg({ c0, c1 }: Fp2) {\n const { Fp } = this;\n return Object.freeze({ c0: Fp.neg(c0), c1: Fp.neg(c1) });\n }\n pow(num: Fp2, power: bigint): Fp2 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp2[]): Fp2[] {\n return mod.FpInvertBatch(this, nums);\n }\n // Normalized\n add(f1: Fp2, f2: Fp2): Fp2 {\n const { Fp } = this;\n const { c0, c1 } = f1;\n const { c0: r0, c1: r1 } = f2;\n return Object.freeze({\n c0: Fp.add(c0, r0),\n c1: Fp.add(c1, r1),\n });\n }\n sub({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) {\n const { Fp } = this;\n return Object.freeze({\n c0: Fp.sub(c0, r0),\n c1: Fp.sub(c1, r1),\n });\n }\n mul({ c0, c1 }: Fp2, rhs: Fp2) {\n const { Fp } = this;\n if (typeof rhs === 'bigint') return Object.freeze({ c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) });\n // (a+bi)(c+di) = (ac−bd) + (ad+bc)i\n const { c0: r0, c1: r1 } = rhs;\n let t1 = Fp.mul(c0, r0); // c0 * o0\n let t2 = Fp.mul(c1, r1); // c1 * o1\n // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i\n const o0 = Fp.sub(t1, t2);\n const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2));\n return Object.freeze({ c0: o0, c1: o1 });\n }\n sqr({ c0, c1 }: Fp2) {\n const { Fp } = this;\n const a = Fp.add(c0, c1);\n const b = Fp.sub(c0, c1);\n const c = Fp.add(c0, c0);\n return Object.freeze({ c0: Fp.mul(a, b), c1: Fp.mul(c, c1) });\n }\n // NonNormalized stuff\n addN(a: Fp2, b: Fp2): Fp2 {\n return this.add(a, b);\n }\n subN(a: Fp2, b: Fp2): Fp2 {\n return this.sub(a, b);\n }\n mulN(a: Fp2, b: Fp2): Fp2 {\n return this.mul(a, b);\n }\n sqrN(a: Fp2): Fp2 {\n return this.sqr(a);\n }\n // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context?\n div(lhs: Fp2, rhs: Fp2): Fp2 {\n const { Fp } = this;\n // @ts-ignore\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n inv({ c0: a, c1: b }: Fp2): Fp2 {\n // We wish to find the multiplicative inverse of a nonzero\n // element a + bu in Fp2. We leverage an identity\n //\n // (a + bu)(a - bu) = a² + b²\n //\n // which holds because u² = -1. This can be rewritten as\n //\n // (a + bu)(a - bu)/(a² + b²) = 1\n //\n // because a² + b² = 0 has no nonzero solutions for (a, b).\n // This gives that (a - bu)/(a² + b²) is the inverse\n // of (a + bu). Importantly, this can be computing using\n // only a single inversion in Fp.\n const { Fp } = this;\n const factor = Fp.inv(Fp.create(a * a + b * b));\n return Object.freeze({ c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) });\n }\n sqrt(num: Fp2) {\n // This is generic for all quadratic extensions (Fp2)\n const { Fp } = this;\n const Fp2 = this;\n const { c0, c1 } = num;\n if (Fp.is0(c1)) {\n // if c0 is quadratic residue\n if (mod.FpLegendre(Fp, c0) === 1) return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO });\n else return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, this.Fp_NONRESIDUE)) });\n }\n const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), this.Fp_NONRESIDUE)));\n let d = Fp.mul(Fp.add(a, c0), this.Fp_div2);\n const legendre = mod.FpLegendre(Fp, d);\n // -1, Quadratic non residue\n if (legendre === -1) d = Fp.sub(d, a);\n const a0 = Fp.sqrt(d);\n const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, this.Fp_div2), a0) });\n if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) throw new Error('Cannot find square root');\n // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num\n const x1 = candidateSqrt;\n const x2 = Fp2.neg(x1);\n const { re: re1, im: im1 } = Fp2.reim(x1);\n const { re: re2, im: im2 } = Fp2.reim(x2);\n if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1;\n return x2;\n }\n // Same as sgn0_m_eq_2 in RFC 9380\n isOdd(x: Fp2) {\n const { re: x0, im: x1 } = this.reim(x);\n const sign_0 = x0 % _2n;\n const zero_0 = x0 === _0n;\n const sign_1 = x1 % _2n;\n return BigInt(sign_0 || (zero_0 && sign_1)) == _1n;\n }\n // Bytes util\n fromBytes(b: Uint8Array): Fp2 {\n const { Fp } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n return this.create({\n c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)),\n c1: Fp.fromBytes(b.subarray(Fp.BYTES)),\n });\n }\n toBytes({ c0, c1 }: Fp2): Uint8Array {\n return concatBytes(this.Fp.toBytes(c0), this.Fp.toBytes(c1));\n }\n cmov({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2, c: boolean) {\n const { Fp } = this;\n return this.create({\n c0: Fp.cmov(c0, r0, c),\n c1: Fp.cmov(c1, r1, c),\n });\n }\n reim({ c0, c1 }: Fp2) {\n return { re: c0, im: c1 };\n }\n Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } {\n const Fp2 = this;\n const a2 = Fp2.sqr(a);\n const b2 = Fp2.sqr(b);\n return {\n first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a²\n second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b²\n };\n }\n // multiply by u + 1\n mulByNonresidue({ c0, c1 }: Fp2) {\n return this.mul({ c0, c1 }, this.NONRESIDUE);\n }\n frobeniusMap({ c0, c1 }: Fp2, power: number): Fp2 {\n return Object.freeze({\n c0,\n c1: this.Fp.mul(c1, this.FROBENIUS_COEFFICIENTS[power % 2]),\n });\n }\n}\n\nclass _Field6 implements Fp6Bls {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp6;\n readonly ONE: Fp6;\n readonly Fp2: Fp2Bls;\n\n constructor(Fp2: Fp2Bls) {\n this.Fp2 = Fp2;\n // `IField.ORDER` is the field cardinality `q`; for sextic extensions that is `p^6`.\n // Generic helpers like Frobenius-style `x^q = x` checks rely on the literal field size here.\n this.ORDER = Fp2.Fp.ORDER ** _6n;\n this.BITS = 3 * Fp2.BITS;\n this.BYTES = 3 * Fp2.BYTES;\n this.isLE = Fp2.isLE;\n this.ZERO = this.create({ c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO });\n this.ONE = this.create({ c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO });\n Object.freeze(this);\n }\n // Most callers never touch Frobenius maps, so keep the sextic tables lazy:\n // eagerly deriving them dominates `bls12-381.js` / `bn254.js` import time.\n get FROBENIUS_COEFFICIENTS_1(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_6.get(this);\n if (frob) return frob[0];\n const { Fp2 } = this;\n const { Fp } = Fp2;\n const rows = calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 6, 2, 3);\n const cache = [Object.freeze(rows[0]), Object.freeze(rows[1])] as const;\n _FROBENIUS_COEFFICIENTS_6.set(this, cache);\n return cache[0];\n }\n get FROBENIUS_COEFFICIENTS_2(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_6.get(this);\n if (frob) return frob[1];\n void this.FROBENIUS_COEFFICIENTS_1;\n return _FROBENIUS_COEFFICIENTS_6.get(this)![1];\n }\n add({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.add(c0, r0),\n c1: Fp2.add(c1, r1),\n c2: Fp2.add(c2, r2),\n });\n }\n sub({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.sub(c0, r0),\n c1: Fp2.sub(c1, r1),\n c2: Fp2.sub(c2, r2),\n });\n }\n mul({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) {\n const { Fp2 } = this;\n if (typeof rhs === 'bigint') {\n return Object.freeze({\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n });\n }\n const { c0: r0, c1: r1, c2: r2 } = rhs;\n const t0 = Fp2.mul(c0, r0); // c0 * o0\n const t1 = Fp2.mul(c1, r1); // c1 * o1\n const t2 = Fp2.mul(c2, r2); // c2 * o2\n return Object.freeze({\n // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1)\n c0: Fp2.add(\n t0,\n Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))\n ),\n // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1)\n c1: Fp2.add(\n Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)),\n Fp2.mulByNonresidue(t2)\n ),\n // T1 + (c0 + c2) * (r0 + r2) - T0 + T2\n c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)),\n });\n }\n sqr({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n let t0 = Fp2.sqr(c0); // c0²\n let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1\n let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2\n let t4 = Fp2.sqr(c2); // c2²\n return Object.freeze({\n c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0\n c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1\n // T1 + (c0 - c1 + c2)² + T3 - T0 - T4\n c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4),\n });\n }\n addN(a: Fp6, b: Fp6): Fp6 {\n return this.add(a, b);\n }\n subN(a: Fp6, b: Fp6): Fp6 {\n return this.sub(a, b);\n }\n mulN(a: Fp6, b: Fp6): Fp6 {\n return this.mul(a, b);\n }\n sqrN(a: Fp6): Fp6 {\n return this.sqr(a);\n }\n\n create(num: Fp6) {\n const { Fp2 } = this;\n const c0 = Fp2.create(num.c0);\n const c1 = Fp2.create(num.c1);\n const c2 = Fp2.create(num.c2);\n return Object.freeze({ c0, c1, c2 });\n }\n\n isValid(num: Fp6) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1, c2 } = num;\n const { Fp2 } = this;\n return Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2);\n }\n is0(num: Fp6) {\n if (!isObj(num)) return false;\n const { c0, c1, c2 } = num;\n const { Fp2 } = this;\n return Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2);\n }\n isValidNot0(num: Fp6) {\n return !this.is0(num) && this.isValid(num);\n }\n neg({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) });\n }\n eql({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) {\n const { Fp2 } = this;\n return Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2);\n }\n sqrt(_: Fp6) {\n // Sextic extensions can use generic odd-field Tonelli-Shanks, but the helper must work\n // over `IField<T>` with a quadratic non-residue from Fp6 itself. The current\n // `mod.tonelliShanks(P)` precomputation only searches integer residues in the base field.\n return notImplemented();\n }\n // Do we need division by bigint at all? Should be done via order:\n div(lhs: Fp6, rhs: Fp6) {\n const { Fp2 } = this;\n const { Fp } = Fp2;\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n pow(num: Fp6, power: Fp): Fp6 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp6[]): Fp6[] {\n return mod.FpInvertBatch(this, nums);\n }\n\n inv({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1)\n let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1\n let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2\n // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0)\n let t4 = Fp2.inv(\n Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))\n );\n return Object.freeze({ c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) });\n }\n // Bytes utils\n fromBytes(b: Uint8Array): Fp6 {\n const { Fp2 } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n const B2 = Fp2.BYTES;\n return this.create({\n c0: Fp2.fromBytes(b.subarray(0, B2)),\n c1: Fp2.fromBytes(b.subarray(B2, B2 * 2)),\n c2: Fp2.fromBytes(b.subarray(2 * B2)),\n });\n }\n toBytes({ c0, c1, c2 }: Fp6): Uint8Array {\n const { Fp2 } = this;\n return concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2));\n }\n cmov({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c: boolean) {\n const { Fp2 } = this;\n return this.create({\n c0: Fp2.cmov(c0, r0, c),\n c1: Fp2.cmov(c1, r1, c),\n c2: Fp2.cmov(c2, r2, c),\n });\n }\n fromBigSix(tuple: BigintSix): Fp6 {\n const { Fp2 } = this;\n if (!Array.isArray(tuple) || tuple.length !== 6) throw new Error('invalid Fp6.fromBigSix');\n for (let i = 0; i < 6; i++)\n if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp6.fromBigSix');\n const t = tuple;\n return this.create({\n c0: Fp2.fromBigTuple(t.slice(0, 2) as BigintTuple),\n c1: Fp2.fromBigTuple(t.slice(2, 4) as BigintTuple),\n c2: Fp2.fromBigTuple(t.slice(4, 6) as BigintTuple),\n });\n }\n frobeniusMap({ c0, c1, c2 }: Fp6, power: number) {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.frobeniusMap(c0, power),\n c1: Fp2.mul(Fp2.frobeniusMap(c1, power), this.FROBENIUS_COEFFICIENTS_1[power % 6]),\n c2: Fp2.mul(Fp2.frobeniusMap(c2, power), this.FROBENIUS_COEFFICIENTS_2[power % 6]),\n });\n }\n mulByFp2({ c0, c1, c2 }: Fp6, rhs: Fp2): Fp6 {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.mul(c0, rhs),\n c1: Fp2.mul(c1, rhs),\n c2: Fp2.mul(c2, rhs),\n });\n }\n mulByNonresidue({ c0, c1, c2 }: Fp6) {\n const { Fp2 } = this;\n return Object.freeze({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 });\n }\n // Sparse multiplication\n mul1({ c0, c1, c2 }: Fp6, b1: Fp2): Fp6 {\n const { Fp2 } = this;\n return Object.freeze({\n c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)),\n c1: Fp2.mul(c0, b1),\n c2: Fp2.mul(c1, b1),\n });\n }\n // Sparse multiplication\n mul01({ c0, c1, c2 }: Fp6, b0: Fp2, b1: Fp2): Fp6 {\n const { Fp2 } = this;\n let t0 = Fp2.mul(c0, b0); // c0 * b0\n let t1 = Fp2.mul(c1, b1); // c1 * b1\n return Object.freeze({\n // ((c1 + c2) * b1 - T1) * (u + 1) + T0\n c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0),\n // (b0 + b1) * (c0 + c1) - T0 - T1\n c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1),\n // (c0 + c2) * b0 - T0 + T1\n c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1),\n });\n }\n}\n\n// Keep lazy tower caches off-object: field instances stay frozen, and debugger output\n// stays readable without JS private slots while second/subsequent lookups still hit cache.\nconst _FROBENIUS_COEFFICIENTS_6 = new WeakMap<_Field6, readonly [readonly Fp2[], readonly Fp2[]]>();\n\nclass _Field12 implements Fp12Bls {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n\n readonly ZERO: Fp12;\n readonly ONE: Fp12;\n\n readonly Fp6: Fp6Bls;\n readonly X_LEN: number;\n readonly finalExponentiate: Tower12Opts['Fp12finalExponentiate'];\n\n constructor(Fp6: Fp6Bls, opts: Tower12Opts) {\n const { X_LEN, Fp12finalExponentiate } = opts;\n const { Fp2 } = Fp6;\n const { Fp } = Fp2;\n this.Fp6 = Fp6;\n\n // `IField.ORDER` is the field cardinality `q`; for degree-12 extensions that is `p^12`.\n // Keeping `p^2` here breaks generic field identities like `x^q = x` on Fp12.\n this.ORDER = Fp.ORDER ** _12n;\n this.BITS = 2 * Fp6.BITS;\n this.BYTES = 2 * Fp6.BYTES;\n this.isLE = Fp6.isLE;\n // Returned tower values are frozen, so larger constants can safely reuse\n // already-frozen child coefficients instead of cloning them.\n this.ZERO = this.create({ c0: Fp6.ZERO, c1: Fp6.ZERO });\n this.ONE = this.create({ c0: Fp6.ONE, c1: Fp6.ZERO });\n this.X_LEN = X_LEN;\n this.finalExponentiate = (num) => {\n const copy2 = ({ c0, c1 }: Fp2): Fp2 => Object.freeze({ c0, c1 });\n const copy6 = ({ c0, c1, c2 }: Fp6): Fp6 =>\n Object.freeze({ c0: copy2(c0), c1: copy2(c1), c2: copy2(c2) });\n // This config hook is trusted to return a canonical Fp12 value already.\n // Copy+freeze it to keep the tower immutability invariant without mutating caller objects.\n const res = Fp12finalExponentiate(num);\n return Object.freeze({ c0: copy6(res.c0), c1: copy6(res.c1) });\n };\n Object.freeze(this);\n }\n // Keep the degree-12 Frobenius row lazy too; after the first lookup the cached\n // array is reused exactly like the old eager table.\n get FROBENIUS_COEFFICIENTS(): readonly Fp2[] {\n const frob = _FROBENIUS_COEFFICIENTS_12.get(this);\n if (frob) return frob;\n const { Fp2 } = this.Fp6;\n const { Fp } = Fp2;\n const cache = Object.freeze(\n calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 12, 1, 6)[0]\n );\n _FROBENIUS_COEFFICIENTS_12.set(this, cache);\n return cache;\n }\n create(num: Fp12) {\n const { Fp6 } = this;\n const c0 = Fp6.create(num.c0);\n const c1 = Fp6.create(num.c1);\n return Object.freeze({ c0, c1 });\n }\n isValid(num: Fp12) {\n if (!isObj(num))\n throw new TypeError('invalid field element: expected object, got ' + typeof num);\n const { c0, c1 } = num;\n const { Fp6 } = this;\n return Fp6.isValid(c0) && Fp6.isValid(c1);\n }\n is0(num: Fp12) {\n if (!isObj(num)) return false;\n const { c0, c1 } = num;\n const { Fp6 } = this;\n return Fp6.is0(c0) && Fp6.is0(c1);\n }\n isValidNot0(num: Fp12) {\n return !this.is0(num) && this.isValid(num);\n }\n neg({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) });\n }\n eql({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Fp6.eql(c0, r0) && Fp6.eql(c1, r1);\n }\n sqrt(_: Fp12): Fp12 {\n // Fp12 is quadratic over Fp6, so a dedicated quadratic-extension sqrt is possible here\n // once Fp6.sqrt() exists. Without that lower-level sqrt, only a field-generic\n // Tonelli-Shanks path over Fp12 itself would work.\n return notImplemented();\n }\n inv({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v)\n // ((C0 * T) * T) + (-C1 * T) * w\n return Object.freeze({ c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) });\n }\n div(lhs: Fp12, rhs: Fp12) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { Fp } = Fp2;\n return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs));\n }\n pow(num: Fp12, power: bigint): Fp12 {\n return mod.FpPow(this, num, power);\n }\n invertBatch(nums: Fp12[]): Fp12[] {\n return mod.FpInvertBatch(this, nums);\n }\n\n // Normalized\n add({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.add(c0, r0),\n c1: Fp6.add(c1, r1),\n });\n }\n sub({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.sub(c0, r0),\n c1: Fp6.sub(c1, r1),\n });\n }\n mul({ c0, c1 }: Fp12, rhs: Fp12 | bigint) {\n const { Fp6 } = this;\n if (typeof rhs === 'bigint')\n return Object.freeze({ c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) });\n let { c0: r0, c1: r1 } = rhs;\n let t1 = Fp6.mul(c0, r0); // c0 * r0\n let t2 = Fp6.mul(c1, r1); // c1 * r1\n return Object.freeze({\n c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v\n // (c0 + c1) * (r0 + r1) - (T1 + T2)\n c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)),\n });\n }\n sqr({ c0, c1 }: Fp12) {\n const { Fp6 } = this;\n let ab = Fp6.mul(c0, c1); // c0 * c1\n return Object.freeze({\n // (c1 * v + c0) * (c0 + c1) - AB - AB * v\n c0: Fp6.sub(\n Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab),\n Fp6.mulByNonresidue(ab)\n ),\n c1: Fp6.add(ab, ab),\n }); // AB + AB\n }\n // NonNormalized stuff\n addN(a: Fp12, b: Fp12): Fp12 {\n return this.add(a, b);\n }\n subN(a: Fp12, b: Fp12): Fp12 {\n return this.sub(a, b);\n }\n mulN(a: Fp12, b: Fp12): Fp12 {\n return this.mul(a, b);\n }\n sqrN(a: Fp12): Fp12 {\n return this.sqr(a);\n }\n\n // Bytes utils\n fromBytes(b: Uint8Array): Fp12 {\n const { Fp6 } = this;\n abytes(b);\n if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length);\n return this.create({\n c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)),\n c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)),\n });\n }\n toBytes({ c0, c1 }: Fp12): Uint8Array {\n const { Fp6 } = this;\n return concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1));\n }\n cmov({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12, c: boolean) {\n const { Fp6 } = this;\n return this.create({\n c0: Fp6.cmov(c0, r0, c),\n c1: Fp6.cmov(c1, r1, c),\n });\n }\n // Utils\n // toString() {\n // return '' + 'Fp12(' + this.c0 + this.c1 + '* w');\n // },\n // fromTuple(c: [Fp6, Fp6]) {\n // return new Fp12(...c);\n // }\n fromBigTwelve(tuple: BigintTwelve): Fp12 {\n const { Fp6 } = this;\n if (!Array.isArray(tuple) || tuple.length !== 12) throw new Error('invalid Fp12.fromBigTwelve');\n for (let i = 0; i < 12; i++)\n if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp12.fromBigTwelve');\n const t = tuple;\n return this.create({\n c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix),\n c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix),\n });\n }\n // Raises to q**i -th power\n frobeniusMap(lhs: Fp12, power: number) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power);\n const coeff = this.FROBENIUS_COEFFICIENTS[power % 12];\n return Object.freeze({\n c0: Fp6.frobeniusMap(lhs.c0, power),\n c1: Object.freeze({\n c0: Fp2.mul(c0, coeff),\n c1: Fp2.mul(c1, coeff),\n c2: Fp2.mul(c2, coeff),\n }),\n });\n }\n mulByFp2({ c0, c1 }: Fp12, rhs: Fp2): Fp12 {\n const { Fp6 } = this;\n return Object.freeze({\n c0: Fp6.mulByFp2(c0, rhs),\n c1: Fp6.mulByFp2(c1, rhs),\n });\n }\n conjugate({ c0, c1 }: Fp12): Fp12 {\n // Reuse `c0` by reference and only negate the `w` coefficient.\n return Object.freeze({ c0, c1: this.Fp6.neg(c1) });\n }\n // Sparse multiplication\n mul014({ c0, c1 }: Fp12, o0: Fp2, o1: Fp2, o4: Fp2) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n let t0 = Fp6.mul01(c0, o0, o1);\n let t1 = Fp6.mul1(c1, o4);\n return Object.freeze({\n c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0\n // (c1 + c0) * [o0, o1+o4] - T0 - T1\n c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1),\n });\n }\n mul034({ c0, c1 }: Fp12, o0: Fp2, o3: Fp2, o4: Fp2) {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const a = Object.freeze({\n c0: Fp2.mul(c0.c0, o0),\n c1: Fp2.mul(c0.c1, o0),\n c2: Fp2.mul(c0.c2, o0),\n });\n const b = Fp6.mul01(c1, o3, o4);\n const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4);\n return Object.freeze({\n c0: Fp6.add(Fp6.mulByNonresidue(b), a),\n c1: Fp6.sub(e, Fp6.add(a, b)),\n });\n }\n\n // A cyclotomic group is a subgroup of Fp^n defined by\n // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1}\n // The result of any pairing is in a cyclotomic subgroup\n // https://eprint.iacr.org/2009/565.pdf\n // https://eprint.iacr.org/2010/354.pdf\n _cyclotomicSquare({ c0, c1 }: Fp12): Fp12 {\n const { Fp6 } = this;\n const { Fp2 } = Fp6;\n const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0;\n const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1;\n const { first: t3, second: t4 } = Fp2.Fp4Square(c0c0, c1c1);\n const { first: t5, second: t6 } = Fp2.Fp4Square(c1c0, c0c2);\n const { first: t7, second: t8 } = Fp2.Fp4Square(c0c1, c1c2);\n const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1)\n return Object.freeze({\n c0: Object.freeze({\n c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3\n c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5\n c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7),\n }), // 2 * (T7 - c0c2) + T7\n c1: Object.freeze({\n c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9\n c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4\n c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6),\n }),\n }); // 2 * (T6 + c1c2) + T6\n }\n // https://eprint.iacr.org/2009/565.pdf\n _cyclotomicExp(num: Fp12, n: bigint): Fp12 {\n // The loop only consumes `X_LEN` bits, so out-of-range exponents would otherwise get silently\n // truncated (or sign-extended for negatives) instead of matching the caller's requested power.\n aInRange('cyclotomic exponent', n, _0n, _1n << BigInt(this.X_LEN));\n let z = this.ONE;\n for (let i = this.X_LEN - 1; i >= 0; i--) {\n z = this._cyclotomicSquare(z);\n if (bitGet(n, i)) z = this.mul(z, num);\n }\n return z;\n }\n}\n\nconst _FROBENIUS_COEFFICIENTS_12 = new WeakMap<_Field12, readonly Fp2[]>();\n\n/**\n * @param opts - Tower construction options. See {@link Tower12Opts}.\n * @returns BLS tower fields.\n * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error}\n * @example\n * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve.\n *\n * ```ts\n * const fields = tower12({\n * ORDER: 17n,\n * X_LEN: 4,\n * FP2_NONRESIDUE: [1n, 1n],\n * Fp2mulByB: (num) => num,\n * Fp12finalExponentiate: (num) => num,\n * });\n * const fp12 = fields.Fp12.ONE;\n * ```\n */\nexport function tower12(opts: TArg<Tower12Opts>): TRet<{\n Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n}> {\n validateObject(\n opts,\n {\n ORDER: 'bigint',\n X_LEN: 'number',\n FP2_NONRESIDUE: 'object',\n Fp2mulByB: 'function',\n Fp12finalExponentiate: 'function',\n },\n { NONRESIDUE: 'bigint' }\n );\n asafenumber(opts.X_LEN, 'X_LEN');\n if (opts.X_LEN < 1) throw new Error('invalid X_LEN');\n const nonresidue = opts.FP2_NONRESIDUE as bigint[];\n if (!Array.isArray(nonresidue) || nonresidue.length !== 2)\n throw new Error('invalid FP2_NONRESIDUE');\n if (typeof nonresidue[0] !== 'bigint' || typeof nonresidue[1] !== 'bigint')\n throw new Error('invalid FP2_NONRESIDUE');\n const Fp = mod.Field(opts.ORDER);\n const Fp2 = new _Field2(Fp, opts);\n const Fp6 = new _Field6(Fp2);\n const Fp12 = new _Field12(Fp6, opts);\n return { Fp, Fp2, Fp6, Fp12 } as TRet<{\n Fp: Readonly<mod.IField<bigint> & Required<Pick<mod.IField<bigint>, 'isOdd'>>>;\n Fp2: Fp2Bls;\n Fp6: Fp6Bls;\n Fp12: Fp12Bls;\n }>;\n}\n","/**\n * bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to:\n\n* Construct zk-SNARKs at the ~120-bit security, as per [Barbulescu-Duquesne 2017](https://hal.science/hal-01534101/file/main.pdf)\n* Efficiently verify N aggregate signatures with 1 pairing and N ec additions:\nthe Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr\n\nBLS can mean 2 different things:\n\n* Barreto-Lynn-Scott: BLS12, a Pairing Friendly Elliptic Curve\n* Boneh-Lynn-Shacham: A Signature Scheme.\n\n### Summary\n\n1. BLS Relies on expensive bilinear pairing\n2. Secret Keys: 32 bytes\n3. Public Keys: 48 OR 96 bytes - big-endian x coordinate of point on G1 OR G2 curve\n4. Signatures: 96 OR 48 bytes - big-endian x coordinate of point on G2 OR G1 curve\n5. The 12 stands for the Embedding degree.\n\nModes of operation:\n\n* Long signatures: 48-byte keys + 96-byte sigs (G1 keys + G2 sigs).\n* Short signatures: 96-byte keys + 48-byte sigs (G2 keys + G1 sigs).\n\n### Formulas\n\n- `P = pk x G` - public keys\n- `S = pk x H(m)` - signing, uses hash-to-curve on m\n- `e(P, H(m)) == e(G, S)` - verification using pairings\n- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation\n\n### Curves\n\nG1 is ordinary elliptic curve. G2 is extension field curve, think \"over complex numbers\".\n\n- G1: y² = x³ + 4\n- G2: y² = x³ + 4(u + 1) where u = √−1; r-order subgroup of E'(Fp²), M-type twist\n\n### Towers\n\nPairing G1 + G2 produces element in Fp₁₂, 12-degree polynomial.\nFp₁₂ is usually implemented using tower of lower-degree polynomials for speed.\n\n- Fp₁₂ = Fp₆² => Fp₂³\n- Fp(u) / (u² - β) where β = -1\n- Fp₂(v) / (v³ - ξ) where ξ = u + 1\n- Fp₆(w) / (w² - γ) where γ = v\n- Fp²[u] = Fp/u²+1\n- Fp⁶[v] = Fp²/v³-1-u\n- Fp¹²[w] = Fp⁶/w²-v\n\n### Params\n\n* Embedding degree (k): 12\n* Seed is sometimes named x or t\n* t = -15132376222941642752\n* p = (t-1)² * (t⁴-t²+1)/3 + t\n* r = t⁴-t²+1\n* Ate loop size: X\n\nTo verify curve parameters, see\n[pairing-friendly-curves spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11).\nBasic math is done over finite fields over p.\nMore complicated math is done over polynominal extension fields.\n\n### Compatibility and notes\n1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC.\nFilecoin uses little endian byte arrays for secret keys - make sure to reverse byte order.\n2. Make sure to correctly select mode: \"long signature\" or \"short signature\".\n3. Compatible with specs:\n RFC 9380,\n [cfrg-pairing-friendly-curves-11](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11),\n [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/).\n\n *\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bls, type BlsCurvePairWithSignatures } from './abstract/bls.ts';\nimport { Field, type IField } from './abstract/modular.ts';\nimport {\n abytes,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n copyBytes,\n hexToBytes,\n numberToBytesBE,\n randomBytes,\n type TArg,\n type TRet,\n} from './utils.ts';\n// Types\nimport { isogenyMap } from './abstract/hash-to-curve.ts';\nimport type { BigintTuple, Fp, Fp12, Fp2, Fp6 } from './abstract/tower.ts';\nimport { psiFrobenius, tower12 } from './abstract/tower.ts';\nimport {\n mapToCurveSimpleSWU,\n weierstrass,\n type AffinePoint,\n type WeierstrassOpts,\n type WeierstrassPoint,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\n// To verify math:\n// https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11\n\n// The BLS parameter x (seed) for BLS12-381. The stored constant is `|x|`; call\n// sites that need the signed parameter apply the minus sign themselves.\n// x = -2^63 - 2^62 - 2^60 - 2^57 - 2^48 - 2^16\nconst BLS_X = BigInt('0xd201000000010000');\n// t = x (called differently in different places)\n// const t = -BLS_X;\nconst BLS_X_LEN = bitLen(BLS_X);\n\n// a=0, b=4\n// P is characteristic of field Fp, in which curve calculations are done.\n// p = (t-1)² * (t⁴-t²+1)/3 + t\n// bls12_381_Fp = (t-1n)**2n * (t**4n - t**2n + 1n) / 3n + t\n// r*h is curve order, amount of points on curve,\n// where r is order of prime subgroup and h is cofactor.\n// r = t⁴-t²+1\n// r = (t**4n - t**2n + 1n)\n// cofactor h of G1: (t - 1)²/3, with the signed convention `t = -x`\n// cofactorG1 = (t-1n)**2n/3n\n// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507\n// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569\nconst bls12_381_CURVE_G1: WeierstrassOpts<bigint> = {\n p: BigInt(\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'\n ),\n n: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'),\n h: BigInt('0x396c8c005555e1568c00aaab0000aaab'),\n a: _0n,\n b: _4n,\n Gx: BigInt(\n '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'\n ),\n Gy: BigInt(\n '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'\n ),\n};\n\n// CURVE FIELDS\n// r = z⁴ − z² + 1; CURVE.n from other curves\n/**\n * bls12-381 Fr (Fn) field.\n * `fromBytes()` reduces modulo `q` instead of rejecting non-canonical encodings.\n */\nexport const bls12_381_Fr: TRet<IField<bigint>> = Field(bls12_381_CURVE_G1.n, {\n modFromBytes: true,\n}) as TRet<IField<bigint>>;\nconst { Fp, Fp2, Fp6, Fp12 } = tower12({\n ORDER: bls12_381_CURVE_G1.p,\n X_LEN: BLS_X_LEN,\n // Finite extension field over irreducible polynominal.\n // Fp(u) / (u² - β) where β = -1\n // Public `Fp2.NONRESIDUE` below is the sextic-tower value `(1, 1) = u + 1`;\n // the quadratic non-residue for the base Fp2 construction is still `-1`.\n FP2_NONRESIDUE: [_1n, _1n],\n Fp2mulByB: ({ c0, c1 }: Fp2) => {\n const t0 = Fp.mul(c0, _4n); // 4 * c0\n const t1 = Fp.mul(c1, _4n); // 4 * c1\n // (T0-T1) + (T0+T1)*i\n return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) };\n },\n Fp12finalExponentiate: (num: Fp12) => {\n const x = BLS_X;\n // this^(q⁶) / this\n const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num);\n // t0^(q²) * t0\n const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0);\n const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x));\n const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2);\n const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x));\n const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x));\n const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2));\n const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x));\n const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2);\n const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3);\n const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1);\n const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1);\n // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1\n return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1);\n },\n});\n\n// GLV endomorphism Ψ(P), for fast cofactor clearing. `Fp2.NONRESIDUE` here is\n// the tower value `u + 1`, so the Frobenius base passed to psiFrobenius is\n// `1 / (u + 1)`, and psi2 derives the published `1 / 2^((p - 1) / 3)` constant internally.\nlet frob: ReturnType<typeof psiFrobenius> | undefined;\nconst getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)));\n// Eager psiFrobenius setup now dominates `bls12-381.js` import, so defer it to\n// first use. After that these locals are rewritten to the direct helper refs.\nlet G2psi: ReturnType<typeof psiFrobenius>['G2psi'] = (c, P) => {\n const fn = getFrob().G2psi;\n G2psi = fn;\n return fn(c, P);\n};\nlet G2psi2: ReturnType<typeof psiFrobenius>['G2psi2'] = (c, P) => {\n const fn = getFrob().G2psi2;\n G2psi2 = fn;\n return fn(c, P);\n};\n\n/**\n * Default hash_to_field / hash-to-curve for BLS.\n * m: 1 for G1, 2 for G2\n * k: target security level in bits\n * hash: any function, e.g. BBS+ uses BLAKE2: see [github](https://github.com/hyperledger/aries-framework-go/issues/2247).\n * Field/hash parameters come from [section 8.8.2 of RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2),\n * but the `DST` / `encodeDST` strings below are the BLS-signature-suite override.\n */\nconst hasher_opts = Object.freeze({\n DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_',\n p: Fp.ORDER,\n m: 2,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n});\n\n// a=0, b=4\n// cofactor h of G2, derived with the signed convention `t = -x`\n// (t^8 - 4t^7 + 5t^6 - 4t^4 + 6t^3 - 4t^2 - 4t + 13)/9\n// cofactorG2 = (t**8n - 4n*t**7n + 5n*t**6n - 4n*t**4n + 6n*t**3n - 4n*t**2n - 4n*t+13n)/9n\n// x = 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160\n// y = 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905\nconst bls12_381_CURVE_G2 = {\n p: Fp2.ORDER,\n n: bls12_381_CURVE_G1.n,\n h: BigInt(\n '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'\n ),\n a: Fp2.ZERO,\n b: Fp2.fromBigTuple([_4n, _4n]),\n Gx: Fp2.fromBigTuple([\n BigInt(\n '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'\n ),\n BigInt(\n '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'\n ),\n ]),\n Gy: Fp2.fromBigTuple([\n BigInt(\n '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'\n ),\n BigInt(\n '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'\n ),\n ]),\n};\n\n// Encoding utils\nconst sortBit = (parts: bigint[], p: bigint) => {\n for (const part of parts) {\n if (part !== _0n) return Boolean((part * _2n) / p);\n }\n return false;\n};\nconst fp2 = {\n // Generic tower bytes use `c0 || c1`, but the BLS12-381 G2 point/signature wire encoding uses\n // `c1 || c0`, so keep this local wrapper instead of changing generic field serialization.\n encode({ c0, c1 }: Fp2): TRet<Uint8Array> {\n const { BYTES: L } = Fp;\n return concatBytes(numberToBytesBE(c1, L), numberToBytesBE(c0, L)) as TRet<Uint8Array>;\n },\n decode(bytes: TArg<Uint8Array>) {\n const { BYTES: L } = Fp;\n return Fp2.create({\n c0: Fp.create(bytesToNumberBE(bytes.subarray(L))),\n c1: Fp.create(bytesToNumberBE(bytes.subarray(0, L))),\n });\n },\n};\nconst BaseFp = Fp;\ntype Mask = { compressed: boolean; infinity: boolean; sort: boolean };\n// Keep BLS12-381 point/signature codecs on one control-flow skeleton: the G1/G2\n// and point/signature variants differ only in field packing, subgroup bytes, and\n// whether uncompressed form is allowed. Copy-paste decoders were diverging.\nconst coder = <T>(\n name: 'G1' | 'G2',\n Fp: TArg<IField<T>>,\n b: T,\n encode: TArg<(v: T) => TRet<Uint8Array>>,\n decode: TArg<(bytes: TArg<Uint8Array>) => T>,\n yparts: (y: T) => bigint[]\n) => {\n const F = Fp as IField<T>;\n const enc = encode as (v: T) => TRet<Uint8Array>;\n const dec = decode as (bytes: TArg<Uint8Array>) => T;\n const W = F.BYTES;\n return (allowUncompressed: boolean) => ({\n encode(point: WeierstrassPoint<T>, compressed = true): TRet<Uint8Array> {\n if (!compressed && !allowUncompressed)\n throw new Error('invalid signature: expected compressed encoding');\n const infinity = point.is0();\n const { x, y } = point.toAffine();\n const bytes = compressed ? enc(x) : concatBytes(enc(x), enc(y));\n let sort;\n if (compressed && !infinity) sort = sortBit(yparts(y), BaseFp.ORDER);\n return setMask(bytes, { compressed, infinity, sort }) as TRet<Uint8Array>;\n },\n decode(bytes: TArg<Uint8Array>): AffinePoint<T> {\n const raw = allowUncompressed\n ? abytes(bytes, undefined, 'point')\n : abytes(bytes, W, 'signature');\n const { compressed, infinity, sort, value } = parseMask(raw);\n if (!allowUncompressed && !compressed)\n throw new Error('invalid signature: expected compressed encoding');\n const len = compressed ? W : 2 * W;\n if (value.length !== len) throw new Error(`invalid ${name} point: expected ${len} bytes`);\n if (infinity) {\n // Infinity canonicality has to be checked on raw bytes before decode()\n // reduces coordinates modulo p and turns non-empty payloads into zero.\n for (const b of value) {\n if (b) throw new Error(`invalid ${name} point: non-canonical zero`);\n }\n return { x: F.ZERO, y: F.ZERO };\n }\n const x = dec(compressed ? value : value.subarray(0, W));\n let y;\n if (compressed) {\n y = F.sqrt(F.add(F.pow(x, _3n), b));\n if (!y) throw new Error(`invalid ${name} point: compressed`);\n if (sortBit(yparts(y), BaseFp.ORDER) !== sort) y = F.neg(y);\n } else {\n y = dec(value.subarray(W));\n }\n // Noble keeps the permissive coordinate reduction path here, but an\n // omitted infinity flag must not still decode to ZERO afterwards.\n if (!compressed && F.is0(x) && F.is0(y))\n throw new Error(`invalid ${name} point: uncompressed`);\n return { x, y };\n },\n });\n};\n\n// Internal helper only: it copies before clearing the top flag bits. The\n// pairing-friendly-curves draft C.2 step 1 rejects 0x20 / 0x60 / 0xe0 because\n// S_bit must be zero for infinity and for all uncompressed encodings.\nfunction validateMask({ compressed, infinity, sort }: Mask) {\n if (\n (!compressed && !infinity && sort) || // 0010_0000 = 0x20\n (!compressed && infinity && sort) || // 0110_0000 = 0x60\n (compressed && infinity && sort) // 1110_0000 = 0xe0\n )\n throw new Error('invalid encoding flag');\n}\nfunction parseMask(bytes: TArg<Uint8Array>) {\n // Copy, so we can remove mask data.\n // It will be removed also later, when Fp.create will call modulo.\n bytes = copyBytes(bytes);\n const mask = bytes[0] & 0b1110_0000;\n const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000)\n const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000)\n const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000)\n validateMask({ compressed, infinity, sort });\n bytes[0] &= 0b0001_1111; // clear mask (zero first 3 bits)\n return { compressed, infinity, sort, value: bytes };\n}\n\n// Internal helper only: mutates a non-empty fresh buffer in place and just\n// sets bits. Keep the same invalid-flag guard as parseMask() so encoders cannot\n// manufacture states that decoders already reject.\nfunction setMask(bytes: TArg<Uint8Array>, mask: Partial<Mask>) {\n if (bytes[0] & 0b1110_0000) throw new Error('setMask: non-empty mask');\n validateMask({ compressed: !!mask.compressed, infinity: !!mask.infinity, sort: !!mask.sort });\n if (mask.compressed) bytes[0] |= 0b1000_0000;\n if (mask.infinity) bytes[0] |= 0b0100_0000;\n if (mask.sort) bytes[0] |= 0b0010_0000;\n return bytes;\n}\n\nconst g1coder = coder(\n 'G1',\n Fp,\n Fp.create(bls12_381_CURVE_G1.b),\n (x: Fp) => numberToBytesBE(x, Fp.BYTES),\n (bytes: TArg<Uint8Array>) => Fp.create(bytesToNumberBE(bytes) & bitMask(Fp.BITS)),\n (y: Fp) => [y]\n);\nconst g1 = { point: g1coder(true), sig: g1coder(false) };\nconst signatureG1ToBytes = (point: WeierstrassPoint<Fp>): TRet<Uint8Array> => {\n point.assertValidity();\n return g1.sig.encode(point);\n};\nfunction signatureG1FromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp> {\n const Point = bls12_381.G1.Point;\n const point = Point.fromAffine(g1.sig.decode(bytes));\n point.assertValidity();\n return point;\n}\n\nconst g2coder = coder('G2', Fp2, bls12_381_CURVE_G2.b, fp2.encode, fp2.decode, (y: Fp2) => [\n y.c1,\n y.c0,\n]);\nconst g2 = { point: g2coder(true), sig: g2coder(false) };\nconst signatureG2ToBytes = (point: WeierstrassPoint<Fp2>): TRet<Uint8Array> => {\n point.assertValidity();\n return g2.sig.encode(point);\n};\nfunction signatureG2FromBytes(bytes: TArg<Uint8Array>) {\n const Point = bls12_381.G2.Point;\n const point = Point.fromAffine(g2.sig.decode(bytes));\n point.assertValidity();\n return point;\n}\n\nconst signatureCoders = {\n ShortSignature: {\n fromBytes(bytes: TArg<Uint8Array>) {\n return signatureG1FromBytes(abytes(bytes));\n },\n fromHex(hex: string): WeierstrassPoint<Fp> {\n return signatureG1FromBytes(hexToBytes(hex));\n },\n toBytes(point: WeierstrassPoint<Fp>) {\n return signatureG1ToBytes(point);\n },\n // Historical alias: BLS signatures have a single compressed byte format here.\n toRawBytes(point: WeierstrassPoint<Fp>) {\n return signatureG1ToBytes(point);\n },\n toHex(point: WeierstrassPoint<Fp>) {\n return bytesToHex(signatureG1ToBytes(point));\n },\n },\n LongSignature: {\n fromBytes(bytes: TArg<Uint8Array>): WeierstrassPoint<Fp2> {\n return signatureG2FromBytes(abytes(bytes));\n },\n fromHex(hex: string): WeierstrassPoint<Fp2> {\n return signatureG2FromBytes(hexToBytes(hex));\n },\n toBytes(point: WeierstrassPoint<Fp2>) {\n return signatureG2ToBytes(point);\n },\n // Historical alias: BLS signatures have a single compressed byte format here.\n toRawBytes(point: WeierstrassPoint<Fp2>) {\n return signatureG2ToBytes(point);\n },\n toHex(point: WeierstrassPoint<Fp2>) {\n return bytesToHex(signatureG2ToBytes(point));\n },\n },\n};\n\nconst fields = {\n Fp,\n Fp2,\n Fp6,\n Fp12,\n Fr: bls12_381_Fr,\n};\nconst G1_Point = weierstrass(bls12_381_CURVE_G1, {\n // Public point APIs still accept infinity, even though the Zcash proof\n // encoding rules cited above only define nonzero point encodings.\n allowInfinityPoint: true,\n Fn: bls12_381_Fr,\n fromBytes: g1.point.decode,\n toBytes: (\n _c: WeierstrassPointCons<Fp>,\n point: WeierstrassPoint<Fp>,\n isComp: boolean\n ): TRet<Uint8Array> => g1.point.encode(point, isComp) as TRet<Uint8Array>,\n // Checks is the point resides in prime-order subgroup.\n // point.isTorsionFree() should return true for valid points\n // It returns false for shitty points.\n // https://eprint.iacr.org/2021/1130.pdf\n isTorsionFree: (c, point): boolean => {\n // GLV endomorphism ψ(P)\n const beta = BigInt(\n '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'\n );\n const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z);\n // TODO: unroll\n const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P\n const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P\n return u2P.equals(phi);\n },\n // Clear cofactor of G1\n // https://eprint.iacr.org/2019/403\n clearCofactor: (_c, point) => {\n // return this.multiplyUnsafe(CURVE.h);\n return point.multiplyUnsafe(BLS_X).add(point); // x*P + P\n },\n});\nconst G2_Point = weierstrass(bls12_381_CURVE_G2, {\n Fp: Fp2,\n // Public point APIs still accept infinity, even though the Zcash proof\n // encoding rules cited above only define nonzero point encodings.\n allowInfinityPoint: true,\n Fn: bls12_381_Fr,\n fromBytes: g2.point.decode,\n toBytes: (\n _c: WeierstrassPointCons<Fp2>,\n point: WeierstrassPoint<Fp2>,\n isComp: boolean\n ): TRet<Uint8Array> => g2.point.encode(point, isComp) as TRet<Uint8Array>,\n // https://eprint.iacr.org/2021/1130.pdf\n // Older version: https://eprint.iacr.org/2019/814.pdf\n isTorsionFree: (c, P): boolean => {\n return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P)\n },\n // clear_cofactor_bls12381_g2 from RFC 9380.\n // https://eprint.iacr.org/2017/419.pdf\n // prettier-ignore\n clearCofactor: (c, P) => {\n const x = BLS_X;\n let t1 = P.multiplyUnsafe(x).negate(); // [-x]P\n let t2 = G2psi(c, P); // Ψ(P)\n let t3 = P.double(); // 2P\n t3 = G2psi2(c, t3); // Ψ²(2P)\n t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P)\n t2 = t1.add(t2); // [-x]P + Ψ(P)\n t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P)\n t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P)\n t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P\n const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P\n return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P)\n },\n});\n\nconst bls12_hasher_opts = {\n mapToG1: mapToG1,\n mapToG2: mapToG2,\n hasherOpts: hasher_opts,\n // RFC 9380 Appendix J defines distinct G1/G2 RO and NU suite IDs, and\n // draft-irtf-cfrg-bls-signature-06 §4.2.1 gives separate G1/G2 `_NUL_` DSTs.\n // Keep G1 encode-to-curve on the G1 domain instead of inheriting G2's `encodeDST`.\n hasherOptsG1: {\n ...hasher_opts,\n m: 1,\n DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_',\n encodeDST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_',\n },\n hasherOptsG2: { ...hasher_opts },\n} as const;\n\nconst bls12_params = {\n ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381\n xNegative: true,\n twistType: 'multiplicative' as const,\n randomBytes: randomBytes,\n};\n\n/**\n * bls12-381 pairing-friendly curve construction.\n * Provides both longSignatures and shortSignatures.\n * @example\n * bls12-381 pairing-friendly curve construction.\n *\n * ```ts\n * const bls = bls12_381.longSignatures;\n * const { secretKey, publicKey } = bls.keygen();\n * const msg = bls.hash(new TextEncoder().encode('hello noble'));\n * const sig = bls.sign(msg, secretKey);\n * const isValid = bls.verify(sig, msg, publicKey);\n * ```\n */\nexport const bls12_381: BlsCurvePairWithSignatures = bls(\n fields,\n G1_Point,\n G2_Point,\n bls12_params,\n bls12_hasher_opts,\n signatureCoders\n);\n\n// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3\n// Coefficients stay in ascending `k_(?,0)`..`k_(?,d)` order; isogenyMap()\n// reverses them internally for Horner evaluation.\nconst isogenyMapG2 = isogenyMap(\n Fp2,\n [\n // xNum\n [\n [\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6',\n ],\n [\n '0x0',\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d',\n ],\n [\n '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1',\n '0x0',\n ],\n ],\n // xDen\n [\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63',\n ],\n [\n '0xc',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n // yNum\n [\n [\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706',\n ],\n [\n '0x0',\n '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be',\n ],\n [\n '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c',\n '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f',\n ],\n [\n '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10',\n '0x0',\n ],\n ],\n // yDen\n [\n [\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb',\n ],\n [\n '0x0',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3',\n ],\n [\n '0x12',\n '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99',\n ],\n ['0x1', '0x0'], // LAST 1\n ],\n ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt) as BigintTuple))) as [\n Fp2[],\n Fp2[],\n Fp2[],\n Fp2[],\n ]\n);\n// 11-isogeny map from E' to E. Coefficients stay in ascending\n// `k_(?,0)`..`k_(?,d)` order; isogenyMap() reverses them for Horner evaluation.\nconst isogenyMapG1 = isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7',\n '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb',\n '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0',\n '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861',\n '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9',\n '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983',\n '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84',\n '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e',\n '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317',\n '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e',\n '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b',\n '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229',\n ],\n // xDen\n [\n '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c',\n '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff',\n '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19',\n '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8',\n '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e',\n '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5',\n '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a',\n '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e',\n '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641',\n '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33',\n '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696',\n '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6',\n '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb',\n '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb',\n '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0',\n '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2',\n '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29',\n '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587',\n '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30',\n '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132',\n '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e',\n '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8',\n '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133',\n '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b',\n '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604',\n ],\n // yDen\n [\n '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1',\n '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d',\n '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2',\n '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416',\n '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d',\n '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac',\n '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c',\n '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9',\n '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a',\n '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55',\n '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8',\n '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092',\n '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc',\n '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7',\n '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f',\n '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]]\n);\n\nlet G1_SWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nlet G2_SWU: ((u: Fp2) => { x: Fp2; y: Fp2 }) | undefined;\n// SWU setup validates the pre-isogeny curve parameters and builds sqrt-ratio helpers.\n// Doing that eagerly adds about 10ms to `bls12-381.js` import here, so keep it lazy; after the\n// first map call the cached mapper is reused directly.\nconst getG1_SWU = () =>\n G1_SWU ||\n (G1_SWU = mapToCurveSimpleSWU(Fp, {\n A: Fp.create(\n BigInt(\n '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d'\n )\n ),\n B: Fp.create(\n BigInt(\n '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0'\n )\n ),\n Z: Fp.create(BigInt(11)),\n }));\nconst getG2_SWU = () =>\n G2_SWU ||\n (G2_SWU = mapToCurveSimpleSWU(Fp2, {\n // SWU map for the RFC 9380 §8.8.2 pre-isogeny G2 curve E':\n // y² = x³ + 240i * x + 1012 + 1012i\n A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I\n B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I)\n Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I)\n }));\n\n// Internal hash-to-curve step: G1 uses `m = 1`, so only `scalars[0]` is read,\n// and the result is the isogeny image on E before the subgroup clear.\nfunction mapToG1(scalars: bigint[]) {\n const { x, y } = getG1_SWU()(Fp.create(scalars[0]));\n return isogenyMapG1(x, y);\n}\n// Internal hash-to-curve step: G2 expects the RFC `m = 2` pair, and the result\n// is the isogeny image on E before the subgroup clear.\nfunction mapToG2(scalars: bigint[]) {\n const { x, y } = getG2_SWU()(Fp2.fromBigTuple(scalars as BigintTuple));\n return isogenyMapG2(x, y);\n}\n","import { bls12_381 } from '@noble/curves/bls12-381.js';\n\n// ETH2 BLS uses G1 public keys (48 bytes) and G2 signatures (96 bytes) — longSignatures mode.\n// The Ethereum consensus spec uses the POP (Proof of Possession) DST, not the noble/curves NUL default.\nconst { longSignatures: ls } = bls12_381;\nconst ETH2_DST = 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_';\n\nexport function blsVerify(\n pubkey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(signature, ls.hash(message, ETH2_DST), pubkey);\n } catch {\n return false;\n }\n}\n\nexport function blsAggregatePublicKeys(pubkeys: Uint8Array[]): Uint8Array {\n if (pubkeys.length === 0) {\n throw new Error('cannot aggregate empty pubkey set');\n }\n return ls.aggregatePublicKeys(pubkeys).toBytes() as Uint8Array;\n}\n\nexport function blsVerifyAggregate(\n pubkeys: Uint8Array[],\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(\n signature,\n ls.hash(message, ETH2_DST),\n ls.aggregatePublicKeys(pubkeys),\n );\n } catch {\n return false;\n }\n}\n\n/** Verify when the pubkey set is already aggregated to a single G1 key. */\nexport function blsVerifyWithAggregatedPubkey(\n aggregatedPubkey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n): boolean {\n try {\n return ls.verify(signature, ls.hash(message, ETH2_DST), aggregatedPubkey);\n } catch {\n return false;\n }\n}\n\nexport function blsVerifyMultiple(\n pubkeys: Uint8Array[],\n messages: Uint8Array[],\n signature: Uint8Array,\n): boolean {\n try {\n if (pubkeys.length !== messages.length) return false;\n const items = messages.map((msg, i) => ({\n message: ls.hash(msg, ETH2_DST),\n publicKey: pubkeys[i],\n }));\n return ls.verifyBatch(signature, items);\n } catch {\n return false;\n }\n}\n\nexport function blsAggregateSignatures(signatures: Uint8Array[]): Uint8Array {\n return ls.Signature.toBytes(ls.aggregateSignatures(signatures)) as Uint8Array;\n}\n\nfunction lagrangeCoeffAtZero(shareIndex: bigint, indices: bigint[]): bigint {\n const { Fr } = bls12_381.fields;\n let num = BigInt(1);\n let den = BigInt(1);\n for (const j of indices) {\n if (j === shareIndex) continue;\n num = Fr.mul(num, Fr.neg(j));\n den = Fr.mul(den, Fr.sub(shareIndex, j));\n }\n return Fr.mul(num, Fr.inv(den));\n}\n\nfunction blsRecoverWithIndices(\n shares: Uint8Array[],\n indices: bigint[],\n): Uint8Array | null {\n try {\n let recovered = bls12_381.G1.Point.ZERO;\n for (let i = 0; i < shares.length; i++) {\n const point = bls12_381.G1.Point.fromBytes(shares[i]);\n const coeff = lagrangeCoeffAtZero(indices[i], indices);\n recovered = recovered.add(point.multiply(coeff));\n }\n return recovered.toBytes() as Uint8Array;\n } catch {\n return null;\n }\n}\n\n// Recover validator distributed pubkey from threshold public shares using\n// Lagrange interpolation in G1 at x=0. Shares are assumed to be at 1-based\n// consecutive positions (index 1, 2, ..., threshold).\nexport function blsRecoverDistributedPubkeyFromShares(\n pubshares: Uint8Array[],\n threshold: number,\n): Uint8Array | null {\n if (threshold <= 0 || pubshares.length < threshold) return null;\n const selected = pubshares.slice(0, threshold);\n const indices = selected.map((_, i) => BigInt(i + 1));\n return blsRecoverWithIndices(selected, indices);\n}\n\n// Verify that every share beyond the first threshold lies on the same\n// polynomial as the first threshold shares. Replaces the last share of the\n// threshold subset with the extra share (keeping its real 1-based index) and\n// checks the reconstruction still produces the same distributed key.\nexport function blsVerifyExtraShares(\n pubshares: Uint8Array[],\n threshold: number,\n distributedPubkey: Uint8Array,\n): boolean {\n // Don't trust the caller — refuse to vacuously pass when there aren't\n // enough shares to even form a threshold-sized subset.\n if (threshold <= 0 || pubshares.length < threshold) return false;\n try {\n const baseShares = pubshares.slice(0, threshold - 1);\n const baseIndices = baseShares.map((_, i) => BigInt(i + 1));\n for (let i = threshold; i < pubshares.length; i++) {\n const shares = [...baseShares, pubshares[i]];\n const indices = [...baseIndices, BigInt(i + 1)];\n const recovered = blsRecoverWithIndices(shares, indices);\n // Length guard before .every() — Uint8Array#every only iterates the\n // shorter array's indices, so a shorter `recovered` would pass\n // vacuously without this check.\n if (\n !recovered ||\n recovered.length !== distributedPubkey.length ||\n !recovered.every((b, j) => b === distributedPubkey[j])\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Thrown when attempting to create a resource that already exists\n * (e.g. posting a duplicate cluster definition, or accepting already-accepted terms).\n */\nexport class ConflictError extends Error {\n name = 'ConflictError';\n\n constructor() {\n super('This Cluster has been already posted.');\n Object.setPrototypeOf(this, ConflictError.prototype);\n }\n}\n\n/**\n * Thrown when a method that requires an ethers `Signer` is called on a\n * client that was constructed without one.\n *\n * To fix: pass a `Wallet` or `JsonRpcSigner` as the second argument to\n * `new Client(config, signer)`.\n */\nexport class SignerRequiredError extends Error {\n name = 'SignerRequiredError';\n\n constructor(method: string) {\n super(`Signer is required in ${method}`);\n Object.setPrototypeOf(this, SignerRequiredError.prototype);\n }\n}\n\n/**\n * Thrown when an operation is attempted on a chain ID that does not support it\n * (e.g. deploying splitters on a chain without factory contracts).\n */\nexport class UnsupportedChainError extends Error {\n name = 'UnsupportedChainError';\n\n constructor(chainId: number, operation: string) {\n super(`${operation} is not supported on chain ${chainId}`);\n Object.setPrototypeOf(this, UnsupportedChainError.prototype);\n }\n}\n\n/**\n * Thrown when {@link Client} is constructed with a baseUrl that is not an\n * allowed Obol API base URL (see {@link ALLOWED_OBOL_API_BASE_URLS}).\n */\nexport class InvalidBaseUrlError extends Error {\n name = 'InvalidBaseUrlError';\n\n constructor(message: string) {\n super(message);\n Object.setPrototypeOf(this, InvalidBaseUrlError.prototype);\n }\n}\n\n/**\n * Thrown when lock validation exceeds a worker time limit (large clusters).\n * HTTP gateways should respond with **504**; distinct from crypto failure\n * (`validateClusterLock` returning **false** → **400**).\n */\nexport class ClusterLockValidationTimeoutError extends Error {\n name = 'ClusterLockValidationTimeoutError';\n\n /**\n * @param timeoutMs - Worker deadline that was exceeded (`VALIDATION_WORKER_TIMEOUT_MS`\n * for the whole-lock worker, `WORKER_TIMEOUT_MS` for per-chunk BLS workers).\n */\n constructor(public readonly timeoutMs: number) {\n super(\n `Cluster lock validation exceeded worker time limit (${timeoutMs} ms). Retry later; this does not imply invalid lock data.`,\n );\n Object.setPrototypeOf(this, ClusterLockValidationTimeoutError.prototype);\n }\n}\n\n/**\n * Thrown when too many `validateClusterLock` calls are already in flight.\n * HTTP gateways should respond with **503**; clients should retry with backoff.\n */\nexport class ClusterLockValidationBusyError extends Error {\n name = 'ClusterLockValidationBusyError';\n\n constructor(public readonly maxConcurrent: number) {\n super(\n `Too many cluster lock validations in progress (limit: ${maxConcurrent}). Retry later.`,\n );\n Object.setPrototypeOf(this, ClusterLockValidationBusyError.prototype);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,iBAA8B;;;AC0GxB,SAAU,QAAQ,GAAU;AAKhC,SACE,a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EAAE,OAAM;AACjB,SAAK,OAAO,GAAG,EAAE;AACjB,SAAK,GAAG,SAAS,EAAE;AACnB,SAAK,GAAG,IAAI,EAAE;AACd,SAAK,GAAG,eAAe,CAAC,EAAE,OAAM;AAChC,SAAK,GAAG,IAAI,EAAE;AACd,SAAK,GAAG,SAAS,EAAE;AACnB,UAAM,IAAI,GAAG,SAAS,CAAC;AACvB,WAAO;EACT;CACD;AAED,IAAM,oBAAoB;EACxB;EACA;EACA,YAAY;;;;EAIZ,cAAc,iCACT,cADS;IAEZ,GAAG;IACH,KAAK;IACL,WAAW;;EAEb,cAAc,mBAAK;;AAGrB,IAAM,eAAe;EACnB,aAAa;;EACb,WAAW;EACX,WAAW;EACX,aAAaC;;AAiBR,IAAM,YAAwC,IACnD,QACA,UACA,UACA,cACA,mBACA,eAAe;AAMjB,IAAM,eAAe,WACnB,KACA;;EAEE;IACE;MACE;MACA;;IAEF;MACE;MACA;;IAEF;MACE;MACA;;IAEF;MACE;MACA;;;;EAIJ;IACE;MACE;MACA;;IAEF;MACE;MACA;;IAEF,CAAC,OAAO,KAAK;;;;EAGf;IACE;MACE;MACA;;IAEF;MACE;MACA;;IAEF;MACE;MACA;;IAEF;MACE;MACA;;;;EAIJ;IACE;MACE;MACA;;IAEF;MACE;MACA;;IAEF;MACE;MACA;;IAEF,CAAC,OAAO,KAAK;;;EAEf,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,IAAI,aAAa,KAAK,IAAI,MAAM,CAAgB,CAAC,CAAC,CAK9E;AAIH,IAAM,eAAe,WACnB,IACA;;EAEE;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;EAGF;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;;EAGF;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;;;EAGF;IACE;IACA;IACA;IACA;IACA;IACA;IACA;IAC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AAI,QAAS;AACb,kBAAU;AACV,qBAAa,KAAK;AAClB,aAAK,OAAO,UAAU;AACtB;AAAA,UACE,IAAI,kCAAkC,4BAA4B;AAAA,QACpE;AAAA,MACF,GAAG,4BAA4B;AAC/B,YAAM,SAAS,CAAC,WAAiC;AAC/C,YAAI,QAAS;AACb,kBAAU;AACV,qBAAa,KAAK;AAElB,eAAO,UAAU;AACjB,gBAAQ,MAAM;AAAA,MAChB;AACA,aAAO,KAAK,WAAW,CAAC,QAAiB;AACvC,YAAI,yBAAyB,GAAG,GAAG;AACjC,cAAI,QAAS;AACb,oBAAU;AACV,uBAAa,KAAK;AAElB,iBAAO,UAAU;AACjB,iBAAO,IAAI,kCAAkC,IAAI,mBAAmB,CAAC;AACrE;AAAA,QACF;AACA,eAAO,QAAQ,IAAI;AAAA,MACrB,CAAC;AACD,aAAO,KAAK,SAAS,MAAM;AACzB,eAAO,IAAI;AAAA,MACb,CAAC;AACD,aAAO,KAAK,QAAQ,UAAQ;AAC1B,YAAI,SAAS,EAAG,QAAO,IAAI;AAAA,MAC7B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAAA;","names":["abytes","anumber","bytesToHex","concatBytes","hexToBytes","isBytes","randomBytes","abytes","fields","_0n","_1n","_0n","_1n","Fp","_1n","Fp","_0n","Fp","_1n","anumber","_0n","abytes","_1n","abytes","_0n","_1n","_1n","_0n","_1n","_0n","Fp","isBytes","abytes","concatBytes","createHasher","_2n","_0n","_1n","abytes","_0n","_1n","_2n","_3n","_4n","Fp","concatBytes","hexToBytes","endo","bytesToHex","tv5","c1","c2","x","_0n","_1n","_2n","_3n","fields","Fp2","Fp12","g1","g2","randomBytes","abytes","msg","G1_Point","G2_Point","Fp","Fp6","createHasher","signatureCoders","_0n","_1n","_2n","_3n","Fp","Fp","Fp2","_1n","_3n","_2n","G2psi","G2psi2","_0n","abytes","concatBytes","frob","Fp6","Fp12","_0n","_1n","_2n","_3n","_4n","concatBytes","Fp","abytes","b","hexToBytes","bytesToHex","randomBytes"]}