@smartledger/keys 3.1.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -13
- package/dist/cjs/sdk.d.ts +25 -4
- package/dist/cjs/sdk.d.ts.map +1 -1
- package/dist/cjs/sdk.js +40 -20
- package/dist/cjs/sdk.js.map +1 -1
- package/dist/cjs/types.d.ts +13 -0
- package/dist/cjs/types.d.ts.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/esm/sdk.d.ts +25 -4
- package/dist/esm/sdk.d.ts.map +1 -1
- package/dist/esm/sdk.js +39 -19
- package/dist/esm/sdk.js.map +1 -1
- package/dist/esm/types.d.ts +13 -0
- package/dist/esm/types.d.ts.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/lumen-keys.js +56 -24
- package/dist/lumen-keys.min.js +3 -3
- package/dist/lumen-keys.min.js.map +3 -3
- package/package.json +5 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../node_modules/@noble/hashes/utils.js", "../../../node_modules/@noble/hashes/_u64.js", "../../../node_modules/@noble/hashes/sha3.js", "../../../node_modules/@noble/curves/utils.js", "../../../node_modules/@noble/curves/abstract/modular.js", "../../../node_modules/@noble/curves/abstract/fft.js", "../../../node_modules/@noble/post-quantum/utils.js", "../../../node_modules/@noble/post-quantum/_crystals.js", "../../../node_modules/@noble/post-quantum/ml-dsa.js", "../src/browser.ts", "../../crypto/node_modules/@noble/secp256k1/index.js", "../../../node_modules/@noble/hashes/hmac.js", "../../../node_modules/@noble/hashes/_md.js", "../../../node_modules/@noble/hashes/sha2.js", "../../crypto/src/utils.ts", "../../../node_modules/@noble/curves/abstract/curve.js", "../../../node_modules/@noble/curves/secp256k1.js", "../../../node_modules/@noble/curves/abstract/weierstrass.js", "../../../node_modules/@noble/curves/abstract/der.js", "../../../node_modules/@noble/hashes/legacy.js", "../../../node_modules/@scure/bip32/index.js", "../../../node_modules/@scure/base/index.js", "../../../node_modules/@noble/hashes/pbkdf2.js", "../../../node_modules/@scure/bip39/index.js", "../../../node_modules/@scure/bip39/wordlists/english.js", "../../crypto/src/derivation/bip32.ts", "../../crypto/src/derivation/wif.ts", "../../crypto/src/suites/bsv-ecdsa.ts", "../../crypto/src/suites/ml-dsa.ts", "../../crypto/src/registry.ts", "../../crypto/src/errors.ts", "../../crypto/src/key-registry.ts", "../src/sdk.ts"],
|
|
4
|
-
"sourcesContent": ["/**\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) {\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 (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// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\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, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\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(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\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) {\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));\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) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash 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 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\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, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\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, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\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) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\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) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\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) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\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) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\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, shift) {\n return (word << (32 - shift)) | (word >>> shift);\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, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\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) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\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 = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\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) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\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 = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\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) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n 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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\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) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n 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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\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 () => { };\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 * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\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(iters, tick, cb) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick();\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts += diff;\n }\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) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\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, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\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) {\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/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\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(defaults, opts, title = 'opts') {\n aobject(defaults, 'defaults');\n if (opts !== undefined)\n aobject(opts, title);\n const merged = Object.assign(defaults, opts);\n return merged;\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 * @throws On wrong argument types. {@link TypeError}\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(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(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) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\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) {\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.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.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 * 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) => ({\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", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { split } from \"./_u64.js\";\n// prettier-ignore\nimport { abool, abytes, aexists, anumber, aoutput, checkOpts, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can\n// inline them into keccakP \u2014 the import path costs ~24% on sha3_256. SHA3 is the only\n// consumer of left-rotates; other hashes use right-rotates from _u64.\n// Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.\n// keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.\nconst B = new Uint32Array(5 * 2);\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s, rounds = 24) {\n if (!(s instanceof Uint32Array))\n throw new TypeError('\"s\" expected Uint32Array(50), got type=' + typeof s);\n if (s.length !== 50)\n throw new RangeError('\"s\" expected Uint32Array(50), got length=' + s.length);\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24)\n throw new Error('\"rounds\" expected integer 1..24');\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta \u03B8\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (\u03C1) and Pi (\u03C0)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (\u03C7)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (\u03B9)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n canXOF;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n anumber(blockLen, 'blockLen');\n anumber(suffix, 'suffix');\n anumber(rounds, 'rounds');\n abool(enableXOF, 'enableXOF');\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('\"blockLen\" must be 1..199');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state, state32 } = this;\n const len = data.length;\n // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.\n // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.\n const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;\n const blockLen32 = blockLen / 4;\n const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;\n for (let pos = 0; pos < len;) {\n if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {\n for (let i = 0, o = pos / 4; i < blockLen32; i++)\n state32[i] ^= data32[o + i];\n pos += blockLen;\n // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,\n // so it must reflect the fully-absorbed block before the permutation fires.\n this.pos = blockLen;\n this.keccak();\n continue;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF)\n throw new Error('XOF is not enabled');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n // Sponge padding and XOF output are positional, so both offsets are part of the clone state.\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);\n}, info);\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\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 = (value, length, title) => abytes_(value, length, title);\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 * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\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 = 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) => concatBytes_(...arrays);\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) => hexToBytes_(hex);\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 = 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) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\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, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\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(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return 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, title = '') {\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 * 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) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\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) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\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) {\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) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\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 * @throws If a documented runtime validation or state check fails. {@link Error}\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, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\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 > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\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 * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\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) {\n return hexToBytes_(numberToHexUnpadded(abignumber(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, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\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) {\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));\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) {\n if (typeof ascii !== 'string')\n 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(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return 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, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\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, n, min, max) {\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// Bit operations\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) {\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)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\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, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\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, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\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 * 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) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\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 hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\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 = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = 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) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = 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)\n 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)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\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, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\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 * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\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(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\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 = () => {\n throw new Error('not implemented');\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 { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\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 _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\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, b) {\n if (b <= _0n)\n 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, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` \u2014 invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\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, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n 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 * 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 - Modulus greater than 1.\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, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the B\u00E9zout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) \u2261 a\u207B\u00B9 (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time \u2014 JS bigint\n * multiplication/reduction is still value-dependent \u2014 and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 \u2261 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions \u2014 (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 \u2014 truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\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// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\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 ((Fp, n) => {\n const F = Fp;\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 });\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) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\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 // 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)\n 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)\n return sqrt3mod4;\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(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\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 // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) \u2261 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)\n throw new Error('Cannot find square root');\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 // 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 };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 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) {\n aoddModulus(P, 'Fp.sqrt');\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\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, modulo) => (mod(num, modulo) & _1n) === _1n;\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];\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(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\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)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\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(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first \u2014 same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\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))\n 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))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\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(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\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) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@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(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\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)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\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(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\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, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n 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 nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\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();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\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)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = 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')\n _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')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n 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 create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\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) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\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)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\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, 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('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\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)\n 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) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\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, b, condition) {\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/**\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, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\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(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n 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 * @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(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n 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 * 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) {\n if (typeof fieldOrder !== 'bigint')\n 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)\n 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 * 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) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\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(key, fieldOrder, isLE = false) {\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 // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.\n * API may change at any time. The code has not been audited. Feature requests are welcome.\n * @module\n */\nimport { aarray, validateObject } from \"../utils.js\";\nimport { validateField } from \"./modular.js\";\nfunction checkU32(n, title = 'n') {\n // 0xff_ff_ff_ff\n if (typeof n !== 'number')\n throw new TypeError(`wrong u32 integer \"${title}\": expected number, got type=${typeof n}`);\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new RangeError(`wrong u32 integer \"${title}\": expected 0..4294967295, got ${n}`);\n return n;\n}\n/**\n * Checks if integer is in form of `1 << X`.\n * @param x - Integer to inspect.\n * @returns `true` when the value is a power of two.\n * @example\n * Validate that an FFT size is a power of two.\n *\n * ```ts\n * isPowerOfTwo(8);\n * ```\n */\nexport function isPowerOfTwo(x) {\n checkU32(x, 'x');\n return (x & (x - 1)) === 0 && x !== 0;\n}\n/**\n * @param n - Input value.\n * @returns Next power of two within the u32/array-length domain.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Round an integer up to the FFT size it needs.\n *\n * ```ts\n * nextPowerOfTwo(9);\n * ```\n */\nexport function nextPowerOfTwo(n) {\n checkU32(n);\n if (n <= 1)\n return 1;\n // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:\n // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.\n if (n > 0x8000_0000)\n throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\n/**\n * @param n - Value to reverse.\n * @param bits - Number of bits to use.\n * @returns Bit-reversed integer.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Reverse the low `bits` bits of one index.\n *\n * ```ts\n * reverseBits(3, 3);\n * ```\n */\nexport function reverseBits(n, bits) {\n checkU32(n);\n if (typeof bits !== 'number')\n throw new TypeError('\"bits\" expected number, got type=' + typeof bits);\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);\n let reversed = 0;\n for (let i = 0; i < bits; i++, n >>>= 1)\n reversed = (reversed << 1) | (n & 1);\n // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.\n return reversed >>> 0;\n}\n/**\n * Similar to `bitLen(x)-1` but much faster for small integers, like indices.\n * @param n - Input value.\n * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.\n * @example\n * Compute the radix-2 stage count for one transform size.\n *\n * ```ts\n * log2(8);\n * ```\n */\nexport function log2(n) {\n checkU32(n);\n return 31 - Math.clz32(n);\n}\n/**\n * Moves lowest bit to highest position, which at first step splits\n * array on even and odd indices, then it applied again to each part,\n * which is core of fft\n * @param values - Mutable coefficient array.\n * @returns Mutated input array.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Reorder coefficients into bit-reversed order in place.\n *\n * ```ts\n * const values = Uint8Array.from([0, 1, 2, 3]);\n * bitReversalInplace(values);\n * ```\n */\nexport function bitReversalInplace(values) {\n if (!values ||\n typeof values !== 'object' ||\n typeof values.length !== 'number')\n throw new TypeError('\"values\" expected array-like, got type=' + typeof values);\n const n = values.length;\n // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.\n if (!isPowerOfTwo(n))\n throw new Error('expected positive power-of-two length, got ' + n);\n const bits = log2(n);\n for (let i = 0; i < n; i++) {\n const j = reverseBits(i, bits);\n if (i < j) {\n const tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n }\n return values;\n}\n/**\n * @param values - Input values.\n * @returns Reordered copy.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Return a reordered copy instead of mutating the input in place.\n *\n * ```ts\n * const reordered = bitReversalPermutation([0, 1, 2, 3]);\n * ```\n */\nexport function bitReversalPermutation(values) {\n aarray(values, 'values');\n return bitReversalInplace(values.slice());\n}\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)\n ;\n return G;\n}\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomial should be rare.\n * @param field - Field implementation.\n * @param generator - Optional trusted non-quadratic-residue override for callers that already know the field.\n * @returns Roots-of-unity cache.\n * @example\n * Cache roots once, then ask for the omega table of one FFT size.\n *\n * ```ts\n * import { rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const roots = rootsOfUnity(Field(17n));\n * const omega = roots.omega(4);\n * ```\n */\nexport function rootsOfUnity(field, generator) {\n validateField(field);\n if (generator !== undefined && typeof generator !== 'bigint')\n throw new TypeError('\"generator\" expected bigint, got type=' + typeof generator);\n // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo\n let oddFactor = field.ORDER - _1n;\n let powerOfTwo = 0;\n for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)\n ;\n // Find non quadratic residue\n let G = generator !== undefined ? BigInt(generator) : findGenerator(field);\n // Powers of generator\n const omegas = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--)\n omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache = [];\n const checkBits = (bits) => {\n checkU32(bits, 'bits');\n if (bits > 31 || bits > powerOfTwo)\n throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);\n return bits;\n };\n const precomputeRoots = (maxPower) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power])\n continue; // Skip if we've already computed roots for this power\n const above = rootsCache[power + 1];\n const rootsAtPower = [];\n if (above) {\n // \u03C9_{2^p} = \u03C9_{2^{p+1}}\u00B2, so the smaller table is the even-index stride of the bigger\n // one: only the largest requested power pays for the multiplication chain.\n for (let j = 0; j < 2 ** power; j++)\n rootsAtPower.push(above[2 * j]);\n }\n else {\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\n }\n rootsCache[power] = rootsAtPower;\n }\n return rootsCache[maxPower];\n };\n const brpCache = new Map();\n const inverseCache = new Map();\n // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not necessarily isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits) => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits) {\n const b = checkBits(bits);\n if (brpCache.has(b))\n return brpCache.get(b);\n else {\n const res = bitReversalPermutation(this.roots(b));\n brpCache.set(b, res);\n return res;\n }\n },\n inverse(bits) {\n const b = checkBits(bits);\n if (inverseCache.has(b))\n return inverseCache.get(b);\n else {\n // \u03C9\u1D3A = 1, so inv(\u03C9\u1D4F) = \u03C9\u1D3A\u207B\u1D4F: the inverse table is the reversed roots table.\n // Value-identical to field.invertBatch(roots), but skips its 3N muls + inversion.\n const r = this.roots(b);\n const res = [r[0]].concat(r.slice(1).reverse());\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits) => omegas[checkBits(bits)],\n clear: () => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n/**\n * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:\n *\n * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cooley-Tukey\n * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande\n *\n * DIT takes brp input, returns natural output.\n * DIF takes natural input, returns brp output.\n *\n * The output is actually identical. Time / frequence distinction is not meaningful\n * for Polynomial multiplication in fields.\n * Which means if protocol supports/needs brp output/inputs, then we can skip this step.\n *\n * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega\n * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa\n *\n * `invertButterflies` indexes roots by a per-butterfly-group counter (`grp`): forward\n * (`dit: false`) reads `roots[grp]` with grp = 1..; inverse (`dit: true`) reads `roots[N - grp]`\n * with grp restarting at 1. With `skipStages: 0` one table serves both directions (\u03C9\u1D3A = 1 makes\n * the reversed walk self-inverse). With `skipStages > 0` the inverse walk starts at `N - 1`\n * instead of continuing where the skipped stages would have left off, so the caller must supply\n * a table shaped for that (ML-KEM: `\u03B6^BitRev7(i)` over all N=256 indices, whose aliased upper\n * half is exactly the FIPS 203 inverse walk).\n * @param F - Field operations.\n * @param coreOpts - FFT configuration. See {@link FFTCoreOpts}:\n * - `N`: Transform size. Must be a power of two.\n * - `roots`: Stage roots for the selected transform size.\n * - `dit`: Whether to run the DIT variant instead of DIF.\n * - `invertButterflies` (optional): Whether to invert butterfly placement.\n * - `skipStages` (optional): Number of initial stages to skip.\n * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.\n * @returns Low-level FFT loop.\n * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}\n * @example\n * Constructs different flavors of FFT.\n *\n * ```ts\n * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const roots = rootsOfUnity(Fp).roots(2);\n * const loop = FFTCore(Fp, { N: 4, roots, dit: true });\n * const values = loop([1n, 2n, 3n, 4n]);\n * ```\n */\nexport const FFTCore = (F, coreOpts) => {\n validateObject(coreOpts, { N: 'number', roots: 'object', dit: 'boolean' }, { invertButterflies: 'boolean', skipStages: 'number', brp: 'boolean' }, 'coreOpts');\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n checkU32(N, 'coreOpts.N');\n const bits = log2(N);\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n checkU32(skipStages, 'coreOpts.skipStages');\n const maxSkipStages = bits === 0 ? 0 : bits - 1;\n // Skipping every stage leaves only boundary layout changes, not a valid FFT loop shape.\n if (skipStages > maxSkipStages)\n throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);\n // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.\n if (roots.length !== N)\n throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);\n const isDit = dit !== invertButterflies;\n return (values) => {\n if (values.length !== N)\n throw new Error('FFT: wrong Polynomial length');\n if (dit && brp)\n bitReversalInplace(values);\n for (let i = 0, g = 1; i < bits - skipStages; i++) {\n // For each stage s (sub-FFT length m = 2^s)\n const s = dit ? i + 1 + skipStages : bits - i;\n const m = 1 << s;\n const m2 = m >> 1;\n const stride = N >> s;\n // Loop over each subarray of length m\n for (let k = 0; k < N; k += m) {\n // Loop over each butterfly within the subarray\n for (let j = 0, grp = g++; j < m2; j++) {\n const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;\n const i0 = k + j;\n const i1 = k + j + m2;\n const omega = roots[rootPos];\n const b = values[i1];\n const a = values[i0];\n // Inlining gives us 10% perf in kyber vs functions\n if (isDit) {\n const t = F.mul(b, omega); // Standard DIT butterfly\n values[i0] = F.add(a, t);\n values[i1] = F.sub(a, t);\n }\n else if (invertButterflies) {\n values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)\n values[i1] = F.mul(F.sub(b, a), omega);\n }\n else {\n values[i0] = F.add(a, b); // Standard DIF butterfly\n values[i1] = F.mul(F.sub(a, b), omega);\n }\n }\n }\n }\n if (!dit && brp)\n bitReversalInplace(values);\n return values;\n };\n};\n/**\n * NTT aka FFT over finite field (NOT over complex numbers).\n * Naming mirrors other libraries.\n * @param roots - Roots-of-unity cache.\n * @param opts - Field operations. See {@link FFTOpts}.\n * @returns Forward and inverse FFT helpers.\n * @example\n * NTT aka FFT over finite field (NOT over complex numbers).\n *\n * ```ts\n * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const fft = FFT(rootsOfUnity(Fp), Fp);\n * const values = fft.direct([1n, 2n, 3n, 4n]);\n * ```\n */\nexport function FFT(roots, opts) {\n // Loops are cached per (size, direction, brp flags): FFTCore construction validates options\n // and allocates closures, which costs more than a small transform itself. The cached loop\n // closes over the root table active at first use; `roots.clear()` rebuilds value-identical\n // tables, so a stale reference stays correct.\n const loops = new Map();\n const getLoop = (N, rootsTable, key) => {\n const cached = loops.get(key);\n if (cached)\n return cached;\n const brpInput = !!(key & 2);\n const brpOutput = !!(key & 1);\n let loop;\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n const core = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n loop = (values) => core(bitReversalInplace(values));\n }\n else if (brpInput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: false });\n else if (brpOutput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n else\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: true }); // all natural\n loops.set(key, loop);\n return loop;\n };\n const loopKey = (bits, isInverse, brpInput, brpOutput) => (bits << 3) | (isInverse ? 4 : 0) | (brpInput ? 2 : 0) | (brpOutput ? 1 : 0);\n return {\n direct(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, false, brpInput, brpOutput);\n return getLoop(N, roots.roots(bits), key)(values.slice());\n },\n inverse(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, true, brpInput, brpOutput);\n const res = getLoop(N, roots.inverse(bits), key)(values.slice());\n const ivm = opts.inv(BigInt(values.length)); // scale\n // we can get brp output if we use dif instead of dit!\n for (let i = 0; i < res.length; i++)\n res[i] = opts.mul(res[i], ivm);\n // Allows to re-use non-inverted roots, but is VERY fragile\n // return [res[0]].concat(res.slice(1).reverse());\n // inverse calculated as pow(-1), which transforms into \u03C9^{-kn} (-> reverses indices)\n return res;\n },\n };\n}\nexport function poly(field, roots, create, fft, length) {\n validateField(field);\n const F = field;\n const _create = create ||\n ((len, elm) => new Array(len).fill(elm ?? F.ZERO));\n // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted\n // polynomial containers concrete instead of trying to support arbitrary wrappers.\n const isPoly = (x) => {\n if (Array.isArray(x))\n return true;\n if (!ArrayBuffer.isView(x))\n return false;\n const v = x;\n return (typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function');\n };\n const checkPoly = (title, value) => {\n if (!isPoly(value))\n throw new TypeError(`\"${title}\" expected polynomial, got type=${typeof value}`);\n };\n const checkLength = (a, b) => {\n checkPoly('a', a);\n const L = a.length;\n if (b !== undefined) {\n checkPoly('b', b);\n if (b.length !== L)\n throw new Error(`poly: mismatched lengths ${L} vs ${b.length}`);\n }\n if (length !== undefined && L !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${L}`);\n return L;\n };\n function findOmegaIndex(x, n, brp = false, weights) {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n // Explicit weights define the interpolation domain, including the Kronecker-\u03B4 shortcut.\n const omega = weights || (brp ? roots.brp(log2(n)) : roots.roots(log2(n)));\n for (let i = 0; i < n; i++)\n if (F.eql(x, omega[i]))\n return i;\n return -1;\n }\n // TODO: mutating versions for mlkem/mldsa\n return {\n roots,\n create: _create,\n length,\n extend: (a, len) => {\n checkLength(a);\n const out = _create(len, F.ZERO);\n // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep\n // `extend()` consistent with typed arrays and with its documented truncate behavior.\n for (let i = 0; i < Math.min(a.length, len); i++)\n out[i] = a[i];\n return out;\n },\n degree: (a) => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--)\n if (!F.is0(a[i]))\n return i;\n return -1;\n },\n add: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a, b) => {\n if (isPoly(b)) {\n const len = checkLength(a, b);\n if (fft) {\n const A = fft.direct(a, false, true);\n const B = fft.direct(b, false, true);\n for (let i = 0; i < A.length; i++)\n A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false);\n }\n else {\n // NOTE: this is quadratic and mostly for compat tests with FFT\n const res = _create(len);\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n const k = (i + j) % len; // wrap mod length\n res[k] = F.add(res[k], F.mul(a[i], b[j]));\n }\n }\n return res;\n }\n }\n else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++)\n out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a, b) {\n checkPoly('a', a);\n checkPoly('b', b);\n const len = nextPowerOfTwo(a.length + b.length - 1);\n return this.mul(this.extend(a, len), this.extend(b, len));\n },\n shift(p, factor) {\n checkPoly('p', p);\n const out = _create(p.length);\n if (length !== undefined && p.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${p.length}`);\n if (!p.length)\n return out;\n out[0] = p[0];\n for (let i = 1, power = F.ONE; i < p.length; i++) {\n power = F.mul(power, factor);\n out[i] = F.mul(p[i], power);\n }\n return out;\n },\n clone: (a) => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++)\n out[i] = a[i];\n return out;\n },\n eval: (a, basis) => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x, n) => {\n const out = _create(n);\n let pow = F.ONE;\n for (let i = 0; i < n; i++) {\n out[i] = pow;\n pow = F.mul(pow, x);\n }\n return out;\n },\n eval: (a, x) => {\n checkLength(a);\n // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way\n let acc = F.ZERO;\n for (let i = a.length - 1; i >= 0; i--)\n acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x, n, brp = false, weights) => {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n const bits = log2(n);\n const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [\u03C9\u2070, \u03C9\u00B9, ..., \u03C9\u207F\u207B\u00B9]\n const out = _create(n);\n // Fast Kronecker-\u03B4 shortcut\n const idx = findOmegaIndex(x, n, brp, weights);\n if (idx !== -1) {\n out[idx] = F.ONE;\n return out;\n }\n const tm = F.pow(x, BigInt(n));\n const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (x\u207F - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++)\n denom[i] = F.sub(x, cache[i]);\n const inv = F.invertBatch(denom);\n for (let i = 0; i < n; i++)\n out[i] = F.mul(c, F.mul(cache[i], inv[i]));\n return out;\n },\n eval(a, x, brp = false) {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1)\n return a[idx]; // fast path\n const L = this.basis(x, a.length, brp); // L\u1D62(x)\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n if (!F.is0(a[i]))\n acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots) {\n checkPoly('roots', roots);\n if (length !== undefined && roots.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${roots.length}`);\n const out = _create(roots.length + 1, F.ZERO);\n out[0] = F.ONE;\n for (const r of roots) {\n const neg = F.neg(r);\n for (let j = out.length - 1; j > 0; j--)\n out[j] = F.add(F.mul(out[j], neg), out[j - 1]);\n out[0] = F.mul(out[0], neg);\n }\n return out;\n },\n };\n}\n", "/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abytes, abytes as abytes_, ahash as ahash_, anumber, concatBytes, isBytes, isLE, randomBytes as randb, } from '@noble/hashes/utils.js';\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes = randb;\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Inputs are validated as byte arrays; unequal lengths return `false` immediately.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\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));\n}\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64(arr) {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If = isLE\n ? (arr) => arr\n : byteSwap64;\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts) {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (isBytes(opts))\n throw new TypeError('\"opts\" expected object, got Uint8Array');\n aobject(opts, 'opts');\n}\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts) {\n validateOpts(opts);\n if (opts.context !== undefined)\n abytes(opts.context, undefined, 'opts.context');\n}\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts) {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder(label, ...lengths) {\n const getLength = (c) => typeof c === 'number' ? c : c.bytesLen;\n const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number')\n b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res;\n },\n };\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder(c, vecLen) {\n const coder = c;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u) => {\n const uArr = aarray(u, 'u');\n if (uArr.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < uArr.length; i++) {\n const b = coder.encode(uArr[i]);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res;\n },\n decode: (a) => {\n abytes_(a, bytesLen);\n const r = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r;\n },\n };\n}\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list) {\n for (const t of list) {\n if (Array.isArray(t))\n for (const b of t)\n b.fill(0);\n else\n t.fill(0);\n }\n}\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits) {\n anumber(bits, 'bits');\n if (bits > 32)\n throw new RangeError('\"bits\" expected <= 32, got ' + bits);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n/** Shared empty byte array used as the default context. */\nexport const EMPTY = /* @__PURE__ */ Uint8Array.of();\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg, ctx = EMPTY) {\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash, requiredStrength = 0) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new TypeError('\"hash\" expected hash function, got type=' + typeof hash);\n ahash_(hash);\n anumber(requiredStrength, 'requiredStrength');\n const oid = hash.oid;\n abytes_(oid, undefined, 'hash.oid');\n if (!equalBytes(oid.subarray(0, 10), oidNistP))\n throw new Error('\"hash.oid\" is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error('Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength);\n }\n}\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(hash, msg, ctx = EMPTY) {\n checkHash(hash);\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);\n}\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n", "/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport { cleanBytes, getMask, } from \"./utils.js\";\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = (opts) => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 \u00A72.3 / FIPS 204 \u00A72.3 before downstream mod-q arithmetic.\n const mod = (a, modulo = Q) => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 \u00A77.4 uses the centered `mod \u00B1` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a, modulo = Q) => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 \u00A77.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n const inv = (_a) => {\n throw new Error('not implemented');\n };\n // ML-KEM (Kyber) polynomials always enter the transform reduced to [0, Q), so add/sub only\n // need one conditional correction instead of `%`; measured ~20% faster NTT there.\n // ML-DSA keeps the generic mod() path on purpose: its first forward stage sees centered\n // (negative) coefficients, and `sub(a, t)` can drop below -Q (t is a mul output in [0, Q)),\n // so a single correction is not enough. A guarded fast path with mod() fallback was measured\n // slower than plain `%` for the 23-bit Q (V8 int32 modulo is one div; the branches lose).\n const field = isKyber\n ? {\n add: (a, b) => {\n const r = (a + b) | 0;\n return r >= Q ? (r - Q) | 0 : r;\n },\n sub: (a, b) => {\n const r = (a - b) | 0;\n return r < 0 ? (r + Q) | 0 : r;\n },\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n }\n : {\n add: (a, b) => mod((a | 0) + (b | 0)) | 0,\n sub: (a, b) => mod((a | 0) - (b | 0)) | 0,\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n };\n const nttOpts = {\n N,\n roots: nttZetas,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r) => {\n return dif(r);\n },\n decode: (r) => {\n dit(r);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++)\n r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d, c) => {\n // Validate the carry shape once: JS bitwise operations silently truncate wider accumulators.\n for (let i = 0, bufLen = 0; i < N; i++) {\n bufLen += d;\n if (bufLen > 32)\n getMask(bufLen);\n bufLen %= 8;\n }\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_) => {\n const poly = poly_;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n // Take the low byte directly: `& 0xff` matches the previous getMask(bufLen) result\n // after Uint8Array truncation, without a validated function call per output byte.\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8)\n r[pos++] = buf & 0xff;\n }\n return r;\n },\n decode: (bytes) => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d)\n r[pos++] = c.decode(buf & mask);\n }\n return r;\n },\n };\n };\n return {\n mod,\n smod,\n nttZetas: nttZetas,\n NTT: {\n encode: (r) => NTT.encode(r),\n decode: (r) => NTT.decode(r),\n },\n bitsCoder: bitsCoder,\n };\n};\nconst createXofShake = (shake) => (seed, blockLen) => {\n if (!blockLen)\n blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x, y) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf);\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n};\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128 = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256 = /* @__PURE__ */ createXofShake(shake256);\n", "/**\n * ML-DSA: Module Lattice-based Digital Signature Algorithm from\n * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.\n *\n * Has similar internals to ML-KEM, but their keys and params are different.\n * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),\n * [repo](https://github.com/pq-crystals/dilithium).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abool } from '@noble/curves/utils.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport { genCrystals, XOF128, XOF256 } from \"./_crystals.js\";\nimport { abytes, checkHash, cleanBytes, equalBytes, getMessage, getMessagePrehash, randomBytes, splitCoder, validateOpts, validateSigOpts, validateVerOpts, vecCoder, } from \"./utils.js\";\nfunction validateInternalOpts(opts) {\n validateOpts(opts);\n if (opts.externalMu !== undefined)\n abool(opts.externalMu, 'opts.externalMu');\n}\n// Constants\n// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients.\nconst N = 256;\n// 2**23 \u2212 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints\nconst Q = 8380417;\n// FIPS 204 \u00A72.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT.\nconst ROOT_OF_UNITY = 1753;\n// f = 256**\u22121 mod q, pow(256, -1, q) = 8347681 (python3)\nconst F = 8347681;\n// FIPS 204 Table 1 / \u00A77.4 fixes d = 13 dropped low bits for Power2Round on t.\nconst D = 13;\n// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87;\n// \u00A77.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint.\n// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.\nconst GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;\nconst GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;\n/** Internal params for different versions of ML-DSA */\n// prettier-ignore\n/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5`\n * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`.\n * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later,\n * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers.\n */\nexport const PARAMS = /* @__PURE__ */ (() => Object.freeze({\n 2: Object.freeze({\n K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80\n }),\n 3: Object.freeze({\n K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55\n }),\n 5: Object.freeze({\n K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75\n }),\n}))();\nconst newPoly = (n) => new Int32Array(n);\n// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal,\n// and Int32Array polys because ordinary-form coefficients can be negative / centered.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly,\n isKyber: false,\n brvBits: 8,\n});\nconst id = (n) => n;\n// compress()/verify() must be compatible in both directions:\n// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps.\n// malformed-input rejection only happens through the optional verify hook.\nconst polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, {\n encode: (i) => compress(verify(i)),\n decode: (i) => verify(compress(i)),\n});\n// Mutates `a` in place; callers must pass same-length polynomials.\n// NOTE: conditional-reduction variants (as in ml-kem) were measured performance-neutral here \u2014\n// int32 `%` with 23-bit Q is already cheap \u2014 so the simpler mod() form is kept for audit.\nconst polyAdd = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] + b[i]);\n return a;\n};\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polySub = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] - b[i]);\n return a;\n};\n// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.\nconst polyShiftl = (p_) => {\n const p = p_;\n for (let i = 0; i < N; i++)\n p[i] <<= D;\n return p;\n};\nconst polyChknorm = (p_, B) => {\n const p = p_;\n // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.\n for (let i = 0; i < N; i++)\n if (Math.abs(crystals.smod(p[i])) >= B)\n return true;\n return false;\n};\n// Both inputs must already be in NTT / `T_q` form.\nconst MultiplyNTTs = (a_, b_) => {\n const a = a_;\n const b = b_;\n // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,\n // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,\n // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).\n // Barrett reduction is slower than mod :(\n const c = newPoly(N);\n for (let i = 0; i < a.length; i++)\n c[i] = crystals.mod(a[i] * b[i]);\n return c;\n};\n// Return poly in NTT representation\nfunction RejNTTPoly(xof_) {\n const xof = xof_;\n // Samples a polynomial \u2208 Tq. xof() must return byte lengths divisible by 3.\n const r = newPoly(N);\n // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(\n for (let j = 0; j < N;) {\n const b = xof();\n if (b.length % 3)\n throw new Error('RejNTTPoly: unaligned block');\n for (let i = 0; j < N && i <= b.length - 3; i += 3) {\n // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate.\n const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes\n if (t < Q)\n r[j++] = t;\n }\n }\n return r;\n}\n// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the\n// Table 2 byte lengths / hash-width choices used by the public wrappers below.\nfunction getDilithium(opts_) {\n const opts = opts_;\n const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;\n const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;\n if (![2, 4].includes(ETA))\n throw new Error('Wrong ETA');\n if (![1 << 17, 1 << 19].includes(GAMMA1))\n throw new Error('Wrong GAMMA1');\n if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))\n throw new Error('Wrong GAMMA2');\n const BETA = TAU * ETA;\n const decompose = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1(2\u03B32) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;\n // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`.\n if (rPlus - r0 === Q - 1)\n return { r1: 0 | 0, r0: (r0 - 1) | 0 };\n const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;\n return { r1, r0 }; // r1 = HighBits, r0 = LowBits\n };\n const HighBits = (r) => decompose(r).r1;\n const LowBits = (r) => decompose(r).r0;\n const MakeHint = (z, r) => {\n // Compute hint bit indicating whether adding z to r alters the high bits of r.\n // FIPS 204 \u00A76.2 also permits the Section 5.1 alternative from [6], which uses the\n // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally.\n // This optimized predicate only applies to those transformed Section 5.1 inputs; it is\n // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs.\n // From dilithium code\n const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;\n // from FIPS204:\n // // const r1 = HighBits(r);\n // // const v1 = HighBits(r + z);\n // // const res1 = +(r1 !== v1);\n // But they return different results! However, decompose is same.\n // So, either there is a bug in Dilithium ref implementation or in FIPS204.\n // For now, lets use dilithium one, so test vectors can be passed.\n // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after\n // `r0 += ct0`.\n // See dilithium-py README section \"Optimising decomposition and making hints\".\n return res0;\n };\n // m = (q-1)/(2\u03B32): 44 for ML-DSA-44, 16 for 65/87. Hoisted out of UseHint, which runs\n // per coefficient during verification.\n const HINT_M = Math.floor((Q - 1) / (2 * GAMMA2));\n const UseHint = (h, r) => {\n // Returns the high bits of r adjusted according to hint h\n const { r1, r0 } = decompose(r);\n // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m\n // 4: if h = 1 and r0 \u2264 0 return (r1 \u2212 1) mod m\n if (h === 1)\n return r0 > 0 ? crystals.mod(r1 + 1, HINT_M) | 0 : crystals.mod(r1 - 1, HINT_M) | 0;\n return r1 | 0;\n };\n const Power2Round = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1*(2**d) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 ** D) | 0;\n return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };\n };\n const hintCoder = {\n bytesLen: OMEGA + K,\n encode: (h_) => {\n const h = h_;\n if (h === false)\n throw new Error('hint.encode: hint is false'); // should never happen\n const res = new Uint8Array(OMEGA + K);\n for (let i = 0, k = 0; i < K; i++) {\n for (let j = 0; j < N; j++)\n if (h[i][j] !== 0)\n res[k++] = j;\n res[OMEGA + i] = k;\n }\n return res;\n },\n decode: (buf) => {\n const h = [];\n let k = 0;\n for (let i = 0; i < K; i++) {\n const hi = newPoly(N);\n if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)\n return false;\n for (let j = k; j < buf[OMEGA + i]; j++) {\n if (j > k && buf[j] <= buf[j - 1])\n return false;\n hi[buf[j]] = 1;\n }\n k = buf[OMEGA + i];\n h.push(hi);\n }\n for (let j = k; j < OMEGA; j++)\n if (buf[j] !== 0)\n return false;\n return h;\n },\n };\n const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {\n if (!(-ETA <= i && i <= ETA))\n throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);\n return i;\n });\n const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i);\n const T1Coder = polyCoder(10);\n // Requires smod. Need to fix!\n const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));\n const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);\n const W1Vec = vecCoder(W1Coder, K);\n // Main structures\n const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));\n const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));\n const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);\n const CoefFromHalfByte = ETA === 2\n ? (n) => (n < 15 ? 2 - (n % 5) : false)\n : (n) => (n < 9 ? 4 - n : false);\n // Return poly in ordinary representation.\n // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply\n // `NTT.encode()` later when needed.\n function RejBoundedPoly(xof_) {\n const xof = xof_;\n // Samples an element a \u2208 Rq with coeffcients in [\u2212\u03B7, \u03B7] computed via rejection sampling from \u03C1.\n const r = newPoly(N);\n for (let j = 0; j < N;) {\n const b = xof();\n for (let i = 0; j < N && i < b.length; i += 1) {\n // half byte. Should be superfast with vector instructions. But very slow with js :(\n const d1 = CoefFromHalfByte(b[i] & 0x0f);\n const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);\n if (d1 !== false)\n r[j++] = d1;\n if (j < N && d2 !== false)\n r[j++] = d2;\n }\n }\n return r;\n }\n const SampleInBall = (seed) => {\n // Samples a polynomial c \u2208 Rq with coeffcients from {\u22121, 0, 1} and Hamming weight \u03C4\n const pre = newPoly(N);\n const s = shake256.create({}).update(seed);\n const buf = new Uint8Array(shake256.blockLen);\n s.xofInto(buf);\n // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`,\n // then rejection-samples coefficient positions from the remaining XOF stream.\n const masks = buf.slice(0, 8);\n for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {\n let b = i + 1;\n for (; b > i;) {\n b = buf[pos++];\n if (pos < shake256.blockLen)\n continue;\n s.xofInto(buf);\n pos = 0;\n }\n pre[i] = pre[b];\n pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);\n if (maskBit >= 8) {\n maskPos++;\n maskBit = 0;\n }\n }\n return pre;\n };\n const polyPowerRound = (p_) => {\n const p = p_;\n const res0 = newPoly(N);\n const res1 = newPoly(N);\n for (let i = 0; i < p.length; i++) {\n const { r0, r1 } = Power2Round(p[i]);\n res0[i] = r0;\n res1[i] = r1;\n }\n return { r0: res0, r1: res1 };\n };\n const polyUseHint = (u_, h_) => {\n const u = u_;\n const h = h_;\n // In-place on `u`: verification only needs the recovered high bits, so reuse the\n // temporary `wApprox` buffer instead of allocating another polynomial.\n for (let i = 0; i < N; i++)\n u[i] = UseHint(h[i], u[i]);\n return u;\n };\n const polyMakeHint = (a_, b_) => {\n const a = a_;\n const b = b_;\n const v = newPoly(N);\n let cnt = 0;\n for (let i = 0; i < N; i++) {\n const h = MakeHint(a[i], b[i]);\n v[i] = h;\n cnt += h;\n }\n return { v, cnt };\n };\n const signRandBytes = 32;\n const seedCoder = splitCoder('seed', 32, 64, 32);\n // API & argument positions are exactly as in FIPS204.\n const internal = Object.freeze({\n info: Object.freeze({ type: 'internal-ml-dsa' }),\n lengths: Object.freeze({\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n seed: 32,\n signature: sigCoder.bytesLen,\n signRand: signRandBytes,\n }),\n keygen: (seed) => {\n // H(\uD835\uDF09||IntegerToBytes(\uD835\uDC58, 1)||IntegerToBytes(\u2113, 1), 128) 2: \u25B7 expand seed\n const seedDst = new Uint8Array(32 + 2);\n const randSeed = seed === undefined;\n if (randSeed)\n seed = randomBytes(32);\n abytes(seed, 32, 'seed');\n seedDst.set(seed);\n if (randSeed)\n cleanBytes(seed);\n seedDst[32] = K;\n seedDst[33] = L;\n const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));\n const xofPrime = XOF256(rhoPrime);\n const s1 = [];\n for (let i = 0; i < L; i++)\n s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s2 = [];\n for (let i = L; i < L + K; i++)\n s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));\n const t0 = [];\n const t1 = [];\n const xof = XOF128(rho);\n const t = newPoly(N);\n for (let i = 0; i < K; i++) {\n // t \u2190 NTT\u22121(A*NTT(s1)) + s2\n cleanBytes(t); // don't-reallocate\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // super slow!\n polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));\n }\n crystals.NTT.decode(t);\n const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) \u2190 Power2Round(t, d)\n t0.push(r0);\n t1.push(r1);\n }\n const publicKey = publicCoder.encode([rho, t1]); // pk \u2190 pkEncode(\u03C1, t1)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr \u2190 H(BytesToBits(pk), 512)\n // sk \u2190 skEncode(\u03C1, K,tr, s1, s2, t0)\n const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);\n xof.clean();\n xofPrime.clean();\n // STATS\n // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 },\n // Kyber1024: { calls: 16, xofs: 48 }\n // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 },\n // DSA87: { calls: 71, xofs: 71 }\n cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);\n return {\n publicKey: publicKey,\n secretKey: secretKey,\n };\n },\n getPublicKey: (secretKey) => {\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);\n const xof = XOF128(rho);\n const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));\n const t1 = [];\n const tmp = newPoly(N);\n for (let i = 0; i < K; i++) {\n tmp.fill(0);\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT\n polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j\n }\n crystals.NTT.decode(tmp); // NTT\u207B\u00B9\n polyAdd(tmp, s2[i]); // t_i = A\u00B7s1 + s2\n const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 \u2248 t0\n t1.push(r1);\n }\n xof.clean();\n cleanBytes(tmp, s1Hat, _t0, s1, s2);\n return publicCoder.encode([rho, t1]);\n },\n // NOTE: random is optional.\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n validateInternalOpts(opts);\n const { extraEntropy: random, externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // Prepare entropy before touching decoded secrets: randomBytes() may throw, and an RNG\n // failure must not leave expanded secret-polynomial copies behind.\n const ownRnd = random === false || random === undefined;\n const rnd = random === false\n ? new Uint8Array(32)\n : random === undefined\n ? randomBytes(signRandBytes)\n : random;\n abytes(rnd, 32, 'extraEntropy');\n // This part can be pre-cached per secretKey, but there is only minor performance improvement,\n // since we re-use a lot of variables to computation.\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const decoded = (() => {\n try {\n return secretCoder.decode(secretKey);\n }\n catch (error) {\n // A malformed key must not strand entropy owned by the library.\n if (ownRnd)\n cleanBytes(rnd);\n throw error;\n }\n })();\n const [rho, _K, tr, s1, s2, t0] = decoded;\n // Cache matrix to avoid re-compute later\n const A = []; // A \u2190 ExpandA(\u03C1)\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const pv = [];\n for (let j = 0; j < L; j++)\n pv.push(RejNTTPoly(xof.get(j, i)));\n A.push(pv);\n }\n xof.clean();\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(s1[i]); // s\u02C61 \u2190 NTT(s1)\n for (let i = 0; i < K; i++) {\n crystals.NTT.encode(s2[i]); // s\u02C62 \u2190 NTT(s2)\n crystals.NTT.encode(t0[i]); // t\u02C60 \u2190 NTT(t0)\n }\n // This part is per msg\n const mu = externalMu\n ? msg\n : // 6: \u00B5 \u2190 H(tr||M, 512)\n // \u25B7 Compute message representative \u00B5\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n const rhoprime = shake256\n .create({ dkLen: CRH_BYTES })\n .update(_K)\n .update(rnd)\n .update(mu)\n .digest(); // \u03C1\u2032\u2190 H(K||rnd||\u00B5, 512)\n // Only wipe entropy we generated; caller-provided extraEntropy stays caller-owned.\n if (ownRnd)\n cleanBytes(rnd);\n abytes(rhoprime, CRH_BYTES);\n const x256 = XOF256(rhoprime, ZCoder.bytesLen);\n // Rejection sampling loop\n main_loop: for (let kappa = 0;;) {\n const y = [];\n // y \u2190 ExpandMask(\u03C1 , \u03BA)\n for (let i = 0; i < L; i++, kappa++)\n y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));\n const z = y.map((i) => crystals.NTT.encode(i.slice()));\n const w = [];\n for (let i = 0; i < K; i++) {\n // w \u2190 NTT\u22121(A \u25E6 NTT(y))\n const wi = newPoly(N);\n for (let j = 0; j < L; j++)\n polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));\n crystals.NTT.decode(wi);\n w.push(wi);\n }\n const w1 = w.map((j) => j.map(HighBits)); // w1 \u2190 HighBits(w)\n // Commitment hash: c\u02DC \u2208{0, 1 2\u03BB } \u2190 H(\u00B5||w1Encode(w1), 2\u03BB)\n const cTilde = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(w1))\n .digest();\n // Verifer\u2019s challenge\n // c \u2190 SampleInBall(c\u02DC1); c\u02C6 \u2190 NTT(c)\n const cHat = crystals.NTT.encode(SampleInBall(cTilde));\n // \u27E8\u27E8cs1\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C61)\n const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));\n for (let i = 0; i < L; i++) {\n polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z \u2190 y + \u27E8\u27E8cs1\u27E9\u27E9\n if (polyChknorm(cs1[i], GAMMA1 - BETA))\n continue main_loop; // ||z||\u221E \u2265 \u03B31 \u2212 \u03B2\n }\n // cs1 is now z (\u25B7 Signer\u2019s response)\n let cnt = 0;\n const h = [];\n for (let i = 0; i < K; i++) {\n const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // \u27E8\u27E8cs2\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C62)\n const r0 = polySub(w[i], cs2).map(LowBits); // r0 \u2190 LowBits(w \u2212 \u27E8\u27E8cs2\u27E9\u27E9)\n if (polyChknorm(r0, GAMMA2 - BETA))\n continue main_loop; // ||r0||\u221E \u2265 \u03B32 \u2212 \u03B2\n const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // \u27E8\u27E8ct0\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 t\u02C60)\n if (polyChknorm(ct0, GAMMA2))\n continue main_loop;\n polyAdd(r0, ct0);\n // \u25B7 Signer\u2019s hint\n const hint = polyMakeHint(r0, w1[i]); // h \u2190 MakeHint(\u2212\u27E8\u27E8ct0\u27E9\u27E9, w\u2212 \u27E8\u27E8cs2\u27E9\u27E9 + \u27E8\u27E8ct0\u27E9\u27E9)\n h.push(hint.v);\n cnt += hint.cnt;\n }\n if (cnt > OMEGA)\n continue; // the number of 1\u2019s in h is greater than \u03C9\n x256.clean();\n const res = sigCoder.encode([cTilde, cs1, h]); // \u03C3 \u2190 sigEncode(c\u02DC, z mod\u00B1q, h)\n // rho, _K, tr is subarray of secretKey, cannot clean.\n cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);\n // `externalMu` hands ownership of `mu` to the caller,\n // so only wipe the internally derived digest form here;\n // zeroizing caller memory would break the caller's own reuse / verify path.\n if (!externalMu)\n cleanBytes(mu);\n return res;\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateInternalOpts(opts);\n const { externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // ML-DSA.Verify(pk, M, \u03C3): Verifes a signature \u03C3 for a message M.\n const [rho, t1] = publicCoder.decode(publicKey); // (\u03C1, t1) \u2190 pkDecode(pk)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr \u2190 H(BytesToBits(pk), 512)\n if (sig.length !== sigCoder.bytesLen)\n return false; // return false instead of exception\n // (c\u02DC, z, h) \u2190 sigDecode(\u03C3)\n // \u25B7 Signer\u2019s commitment hash c \u02DC, response z and hint\n const [cTilde, z, h] = sigCoder.decode(sig);\n if (h === false)\n return false; // if h = \u22A5 then return false\n for (let i = 0; i < L; i++)\n if (polyChknorm(z[i], GAMMA1 - BETA))\n return false;\n const mu = externalMu\n ? msg\n : // 7: \u00B5 \u2190 H(tr||M, 512)\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n // Compute verifer\u2019s challenge from c\u02DC\n const c = crystals.NTT.encode(SampleInBall(cTilde)); // c \u2190 SampleInBall(c\u02DC1)\n const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(zNtt[i]);\n const wTick1 = [];\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)\n const Az = newPoly(N); // // A * z\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace\n polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));\n }\n // wApprox = A*z - c*t1 * (2**d)\n const wApprox = crystals.NTT.decode(polySub(Az, ct12d));\n // Reconstruction of signer\u2019s commitment\n wTick1.push(polyUseHint(wApprox, h[i])); // w \u2032 \u2190 UseHint(h, w'approx )\n }\n xof.clean();\n // c\u02DC\u2032\u2190 H (\u00B5||w1Encode(w\u20321), 2\u03BB), Hash it; this should match c\u02DC\n const c2 = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(wTick1))\n .digest();\n // Additional checks in FIPS-204:\n // [[ ||z||\u221E < \u03B31 \u2212 \u03B2 ]] and [[c \u02DC = c\u02DC\u2032]] and [[number of 1\u2019s in h is \u2264 \u03C9]]\n for (const t of h) {\n const sum = t.reduce((acc, i) => acc + i, 0);\n if (!(sum <= OMEGA))\n return false;\n }\n for (const t of z)\n if (polyChknorm(t, GAMMA1 - BETA))\n return false;\n return equalBytes(cTilde, c2);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-dsa' }),\n internal,\n securityLevel: securityLevel,\n keygen: internal.keygen,\n lengths: internal.lengths,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash) => {\n checkHash(hash, securityLevel);\n const rawHash = hash;\n return Object.freeze({\n info: Object.freeze({ type: 'hashml-dsa' }),\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n const M = getMessagePrehash(rawHash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n/**\n * ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD.\n * @example\n * Generate deterministic ML-DSA-44 keys, sign one message, and verify the signature.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const seed = new Uint8Array(ml_dsa44.lengths.seed!);\n * const { secretKey, publicKey } = ml_dsa44.keygen(seed);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ml_dsa44.sign(msg, secretKey);\n * const isValid = ml_dsa44.verify(sig, msg, publicKey);\n * const recovered = ml_dsa44.getPublicKey(secretKey);\n * const context = new Uint8Array([1, 2, 3]);\n * const prehash = ml_dsa44.prehash(sha256);\n * const preSig = prehash.sign(msg, secretKey, { context });\n * const preValid = prehash.verify(preSig, msg, publicKey, { context });\n * const internalSig = ml_dsa44.internal.sign(msg, secretKey);\n * ```\n */\nexport const ml_dsa44 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[2],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 32,\n XOF128,\n XOF256,\n securityLevel: 128,\n}))();\n/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa65 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[3],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 48,\n XOF128,\n XOF256,\n securityLevel: 192,\n}))();\n/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */\nexport const ml_dsa87 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[5],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 64,\n XOF128,\n XOF256,\n securityLevel: 256,\n}))();\n", "/**\n * Entry point of the browser <script> bundle (dist/lumen-keys(.min).js),\n * which exposes `window.LumenKeys`.\n *\n * Bundlers and Node should import '@smartledger/keys' itself: the ESM build\n * runs unchanged in browsers. This file exists for the script-tag build only.\n */\n\nimport { DefaultKeySDK } from './sdk.js';\nimport { \n InMemoryKeyStorage, \n KeyRegistry,\n globalRegistry,\n} from '@smartledger/crypto';\nimport type { KeySDK } from './types.js';\n\n// Re-export all types for browser usage\nexport * from './types.js';\nexport { InMemoryKeyStorage, KeyRegistry } from '@smartledger/crypto';\n\n/**\n * Creates a new KeySDK instance for browser usage.\n *\n * Async for backward compatibility with earlier bundles; nothing is awaited\n * (the cryptography is pure JavaScript, there is no WASM to initialise).\n * \n * All signature suites (ECDSA, ML-DSA-44, ML-DSA-65, ML-DSA-87) are\n * auto-registered in globalRegistry when @smartledger/crypto loads.\n *\n * Keys live in memory only and are gone when the page unloads.\n */\nexport async function createKeySDK(config?: { keyRegistry?: KeyRegistry }): Promise<KeySDK> {\n const keyRegistry = config?.keyRegistry ?? new KeyRegistry(new InMemoryKeyStorage());\n \n // Use the global registry with auto-registered suites\n // (BsvEcdsaSuite, MlDsa44Suite, MlDsa65Suite, MlDsa87Suite)\n const sdk = new DefaultKeySDK({\n keyRegistry,\n suiteRegistry: globalRegistry,\n });\n \n \n return sdk;\n}\n\n/**\n * Browser-ready default export\n */\nexport default {\n createKeySDK,\n};\n\n// Global export for CDN usage\nif (typeof window !== 'undefined') {\n (window as any).LumenKeys = {\n createKeySDK,\n };\n}\n", "/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 5KB JS implementation of secp256k1 ECDSA / Schnorr signatures & ECDH.\n * Compliant with RFC6979 & BIP340.\n * @module\n */\n/**\n * Curve params from SEC 2 v2 \u00A72.4.1.\n * secp256k1 is a short Weierstrass / Koblitz curve with equation\n * `y\u00B2 == x\u00B3 + ax + b`.\n * * P = `2n**256n - 2n**32n - 977n` // field over which calculations are done\n * * N = `2n**256n - 0x14551231950b75fc4402da1732fc9bebfn` // group order, amount of curve points\n * * h = `1n` // cofactor\n * * a = `0n` // equation param\n * * b = `7n` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n */\n// Mirror noble-curves: Point.CURVE() returns shared params, but those params must stay frozen so\n// callers cannot mutate them out from under the arithmetic constants captured below.\nconst secp256k1_CURVE = Object.freeze({\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,\n n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,\n Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,\n});\nconst { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;\n// 32-byte field / scalar width, and the SHA-256 / HMAC-DRBG output width used\n// by the RFC6979 paths here.\nconst L = 32;\nconst L2 = 64; // 64-byte compact signatures, and 64 hex chars for zero-padded 32-byte scalars\nconst lengths = {\n publicKey: L + 1,\n publicKeyUncompressed: L2 + 1,\n signature: L2,\n // 48-byte keygen seed floor: 384 bits exceeds FIPS 186-5 Table A.2's\n // 352-bit recommendation for 256-bit prime curves.\n seed: L + L / 2,\n};\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\nconst err = (message = '', E = Error) => {\n const e = new E(message);\n const { captureStackTrace } = Error;\n if (typeof captureStackTrace === 'function')\n captureStackTrace(e, err);\n throw e;\n};\n// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n// fallback still requires a real ArrayBuffer view so plain JSON-deserialized `{ constructor: ... }`\n// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\nconst isBytes = (a) => a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n a.BYTES_PER_ELEMENT === 1);\n/** Asserts something is Bytes. */\nconst abytes = (value, length, title = '') => {\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 msg = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n return bytes ? err(msg, RangeError) : err(msg, TypeError);\n }\n return value;\n};\n/** create Uint8Array */\nconst u8n = (len) => new Uint8Array(len);\n// Callers keep values non-negative and within the requested width; padStart() won't truncate over-wide inputs.\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\n/** Render bytes as lowercase hex. */\nconst bytesToHex = (b) => {\n let hex = '';\n for (const e of abytes(b))\n hex += padh(e, 2);\n return hex;\n};\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// prettier-ignore\nconst _ch = (ch) => ch >= C._0 && ch <= C._9 ? ch - C._0 // '2' => 50-48\n : ch >= C.A && ch <= C.F ? ch - (C.A - 10) // 'B' => 66-(65-10)\n : ch >= C.a && ch <= C.f ? ch - (C.a - 10) // 'b' => 98-(97-10)\n : undefined;\nconst hexToBytes = (hex) => {\n const e = 'hex invalid'; // Strict ASCII hex only, with one generic error for type and parse failures.\n if (typeof hex !== 'string')\n return err(e);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n return err(e);\n const array = u8n(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n // treat each char as ASCII\n const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined)\n return err(e);\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n};\n// WebCrypto is available in all modern environments\nconst subtle = () => globalThis?.crypto?.subtle ?? err('crypto.subtle must be defined, consider polyfill');\n// prettier-ignore\nconst concatBytes = (...arrs) => {\n let len = 0;\n for (const a of arrs)\n len += abytes(a).length; // validate every input and sum lengths before copying\n const r = u8n(len);\n let pad = 0; // walk through each array,\n for (const a of arrs)\n r.set(a, pad), pad += a.length; // ensure they have proper type\n return r;\n};\n/**\n * WebCrypto OS-level CSPRNG (random number generator).\n * Will throw when not available; large-request ceilings are delegated to getRandomValues().\n */\nconst randomBytes = (len = L) => (globalThis?.crypto).getRandomValues(u8n(len));\nconst big = BigInt;\nconst arange = (n, min, max, msg = 'bad number: out of range') => {\n if (typeof n !== 'bigint')\n return err(msg, TypeError);\n if (min <= n && n < max)\n return n;\n return err(msg, RangeError);\n};\n/** Canonical modular reduction. Callers must provide a positive modulus. */\nconst M = (a, b = P) => {\n const r = a % b;\n return r >= 0n ? r : b + r;\n};\nconst modN = (a) => M(a, N);\n/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */\n// prettier-ignore\nconst invert = (num, md) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md);\n let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) {\n const q = b / a, r = b % a;\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst callHash = (name) => {\n // @ts-ignore\n const fn = hashes[name];\n if (typeof fn !== 'function')\n err('hashes.' + name + ' not set');\n return fn;\n};\n// All exported provider slots are caller-configurable and may be unset or return arbitrary values,\n// so wrapper helpers must enforce the exact 32-byte digest contract instead of trusting providers.\nconst gh = (name, a, b) => abytes(callHash(name)(a, b), L, 'digest');\nconst gha = (name, a, b) => Promise.resolve(callHash(name)(a, b)).then((r) => abytes(r, L, 'digest'));\n/**\n * SHA-256 helper used by the synchronous API.\n * @param msg - message bytes to hash\n * @returns 32-byte SHA-256 digest.\n * @example\n * Hash message bytes after wiring the synchronous SHA-256 implementation.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * const digest = secp.hash(new Uint8Array([1, 2, 3]));\n * ```\n */\n// Public helper validates the message boundary explicitly; the configured provider is still looked\n// up dynamically and its output is checked with `gh(...)`.\nconst hash = (msg) => gh('sha256', abytes(msg, undefined, 'message'));\n// also rejects structurally similar Point values from other realms / bundled copies\nconst apoint = (p) => (p instanceof Point ? p : err('Point expected'));\n// ## End of Helpers\n// -----------------\n/**\n * secp256k1 formula. Koblitz curves are subclass of weierstrass curves with a=0,\n * making it x\u00B3+b; callers validate x first.\n */\nconst koblitz = (x) => M(M(x * x) * x + _b);\n/** assert is element of field mod P (incl. 0 for projective infinity coordinates) */\nconst FpIsValid = (n) => arange(n, 0n, P);\n/** assert is element of field mod P (excl. 0 where current callers need a non-zero coordinate) */\nconst FpIsValidNot0 = (n) => arange(n, 1n, P);\n/** assert is element of field mod N (excl. 0), matching the shared BIP340 scalar-failure rule used here */\nconst FnIsValidNot0 = (n) => arange(n, 1n, N);\n// Shared parity primitive for BIP340 even-y checks and SEC 1 compressed prefixes.\nconst isEven = (y) => !(y & 1n);\n/** create Uint8Array of byte n */\nconst u8of = (n) => Uint8Array.of(n);\n/** SEC 1 compressed-prefix helper. Parity only: callers validate y before asking for the prefix byte. */\nconst getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);\n/** lift_x from BIP340 returns the unique even square root for x\u00B3+7.\n * SEC 1 callers still flip it for the odd-prefix branch. */\nconst lift_x = (x) => {\n // Let c = x\u00B3 + 7 mod p. Fail if x \u2265 p. (also fail if x < 1)\n const c = koblitz(FpIsValidNot0(x));\n // r = \u221Ac candidate\n // r = c^((p+1)/4) mod p\n // This formula works for fields p = 3 mod 4 -- a special, fast case.\n // Paper: \"Square Roots from 1;24,51,10 to Dan Shanks\".\n let r = 1n;\n for (let num = c, e = (P + 1n) / 4n; e > 0n; e >>= 1n) {\n // powMod: modular exponentiation.\n if (e & 1n)\n r = (r * num) % P; // Uses exponentiation by squaring.\n num = (num * num) % P; // Not constant-time.\n }\n if (M(r * r) !== c)\n err('sqrt invalid'); // check if result is valid\n return isEven(r) ? r : M(-r);\n};\nexport const __TEST = /* @__PURE__ */ Object.freeze({\n // Shared tests expect the BIP340 helper to expose the canonical even-y point, not just the root.\n lift_x: (x) => Point.fromAffine({ x, y: lift_x(x) }),\n extractK: (rand) => extractK(rand),\n});\n/**\n * Point in 3d xyz projective coordinates. 3d takes less inversions than 2d.\n * @param X - X coordinate.\n * @param Y - Y coordinate.\n * @param Z - projective Z coordinate.\n * @example\n * Do point arithmetic with the base point and encode the result as hex.\n * ```ts\n * import { Point } from '@noble/secp256k1';\n * const hex = Point.BASE.double().toHex();\n * ```\n */\nclass Point {\n static BASE;\n static ZERO;\n X;\n Y;\n Z;\n constructor(X, Y, Z) {\n this.X = FpIsValid(X);\n this.Y = FpIsValidNot0(Y); // Y can't be 0 in Projective\n this.Z = FpIsValid(Z);\n Object.freeze(this);\n }\n /** Returns the shared curve metadata object by reference.\n * It is readonly only at type level, and mutating it won't retarget arithmetic,\n * which already uses module-load snapshots. */\n static CURVE() {\n return secp256k1_CURVE;\n }\n /** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */\n static fromAffine(ap) {\n const { x, y } = ap;\n return x === 0n && y === 0n ? I : new Point(x, y, 1n);\n }\n /** Convert Uint8Array or hex string to Point. */\n static fromBytes(bytes) {\n abytes(bytes);\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n let p = undefined;\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n const x = sliceBytesNumBE(tail, 0, L);\n // SEC 1 defines the rare infinity encoding 0x00, but SEC 1 public-key validation rejects\n // infinity. We keep 0x00 rejected here because this parser is reused by verify(), ECDH,\n // and public-key validation helpers, so strict handling applies to all callers by default.\n // Local secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n // Parse SEC 1 compressed/uncompressed encodings, then finish with assertValidity() before returning.\n if (length === comp && (head === 0x02 || head === 0x03)) {\n // Equation is y\u00B2 == x\u00B3 + ax + b. We calculate y from x.\n // lift_x() returns the even root; SEC 1 0x03 still needs the odd root.\n let y = lift_x(x);\n if (head === 0x03)\n y = M(-y);\n p = new Point(x, y, 1n);\n }\n // Uncompressed 65-byte point, 0x04 prefix\n if (length === uncomp && head === 0x04)\n p = new Point(x, sliceBytesNumBE(tail, L, L2), 1n);\n // Validate point\n return p ? p.assertValidity() : err('bad point: not on curve');\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality\n const X1Z2 = M(X1 * Z2);\n const X2Z1 = M(X2 * Z1);\n const Y1Z2 = M(Y1 * Z2);\n const Y2Z1 = M(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(this.X, M(-this.Y), this.Z);\n }\n /** Point doubling: P+P, complete formula. */\n double() {\n return this.add(this);\n }\n /**\n * Point addition: P+Q, complete, exception-free formula\n * (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).\n * Cost: `12M + 0S + 3*a + 3*b3 + 23add`.\n */\n // prettier-ignore\n add(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other);\n const a = 0n;\n const b = _b;\n let X3 = 0n, Y3 = 0n, Z3 = 0n;\n const b3 = M(b * 3n);\n let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1\n let t4 = M(X2 + Y2); // step 5\n t3 = M(t3 * t4);\n t4 = M(t0 + t1);\n t3 = M(t3 - t4);\n t4 = M(X1 + Z1);\n let t5 = M(X2 + Z2); // step 10\n t4 = M(t4 * t5);\n t5 = M(t0 + t2);\n t4 = M(t4 - t5);\n t5 = M(Y1 + Z1);\n X3 = M(Y2 + Z2); // step 15\n t5 = M(t5 * X3);\n X3 = M(t1 + t2);\n t5 = M(t5 - X3);\n Z3 = M(a * t4);\n X3 = M(b3 * t2); // step 20\n Z3 = M(X3 + Z3);\n X3 = M(t1 - Z3);\n Z3 = M(t1 + Z3);\n Y3 = M(X3 * Z3);\n t1 = M(t0 + t0); // step 25\n t1 = M(t1 + t0);\n t2 = M(a * t2);\n t4 = M(b3 * t4);\n t1 = M(t1 + t2);\n t2 = M(t0 - t2); // step 30\n t2 = M(a * t2);\n t4 = M(t4 + t2);\n t0 = M(t1 * t4);\n Y3 = M(Y3 + t0);\n t0 = M(t5 * t4); // step 35\n X3 = M(t3 * X3);\n X3 = M(X3 - t0);\n t0 = M(t3 * t1);\n Z3 = M(t5 * Z3);\n Z3 = M(Z3 + t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(apoint(other).negate());\n }\n /**\n * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate leakage shape in JS, not as a hard constant-time guarantee.\n * @param n scalar by which point is multiplied\n * @param safe safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n // Unsafe internal callers may legitimately need 0*P = O during double-scalar multiplication.\n if (!safe && n === 0n)\n return I;\n FnIsValidNot0(n);\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n }\n return p;\n }\n multiplyUnsafe(scalar) {\n return this.multiply(scalar, false);\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) \u220B (x=X/Z, y=Y/Z) */\n toAffine() {\n const { X: x, Y: y, Z: z } = this;\n // fast-paths for ZERO point OR Z=1\n if (this.equals(I))\n return { x: 0n, y: 0n };\n if (z === 1n)\n return { x, y };\n const iz = invert(z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (M(z * iz) !== 1n)\n err('inverse invalid');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: M(x * iz), y: M(y * iz) };\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const { x, y } = this.toAffine(); // convert to 2d xy affine point.\n FpIsValidNot0(x); // must be in range 1 <= x,y < P\n FpIsValidNot0(y);\n // y\u00B2 == x\u00B3 + ax + b, equation sides must be equal\n return M(y * y) === koblitz(x) ? this : err('bad point: not on curve');\n }\n /** Converts point to 33/65-byte Uint8Array. */\n toBytes(isCompressed = true) {\n // Same policy as fromBytes(): SEC 1 has the rare infinity encoding 0x00, but we keep ZERO\n // out of this byte surface because callers treat these encodings as public keys by default.\n const { x, y } = this.assertValidity().toAffine();\n const x32b = numTo32b(x);\n if (isCompressed)\n return concatBytes(getPrefix(y), x32b);\n return concatBytes(u8of(0x04), x32b, numTo32b(y));\n }\n toHex(isCompressed) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n);\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\n/** `Q = u1\u22C5G + u2\u22C5R`. Verifies Q is not ZERO. Unsafe: non-CT. */\nconst doubleScalarMulUns = (R, u1, u2) => {\n return G.multiply(u1, false)\n .add(R.multiply(u2, false))\n .assertValidity();\n};\n// Inherits byte validation from bytesToHex(); the || '0' fallback keeps empty input mapped to 0n.\nconst bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));\n// Callers provide monotone slice bounds; subarray() would otherwise clamp or reinterpret them silently.\nconst sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));\nconst B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x\u00B3 + ax + b.\n/** Generic 32-byte big-endian encoder. Must be 0 <= num < B256; call sites need not be field/scalar elements. */\nconst numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));\n/** Normalize private key to scalar (bigint). Verifies scalar is in range 1 <= d < N. */\nconst secretKeyToScalar = (secretKey) => {\n const num = bytesToNumBE(abytes(secretKey, L, 'secret key'));\n return arange(num, 1n, N, 'invalid secret key: outside of range');\n};\n/** For signature malleability, checks the strict upper-half predicate s > floor(N/2). */\nconst highS = (n) => n > N >> 1n;\n/**\n * Creates a SEC 1 public key from a 32-byte private key.\n * @param privKey - 32-byte secret key.\n * @param isCompressed - return 33-byte compressed SEC 1 encoding when `true`, otherwise 65-byte uncompressed.\n * @returns serialized secp256k1 public key in SEC 1 encoding.\n * @example\n * Derive the serialized public key for a secp256k1 secret key.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const publicKey = secp.getPublicKey(secretKey);\n * ```\n */\nconst getPublicKey = (privKey, isCompressed = true) => {\n return G.multiply(secretKeyToScalar(privKey)).toBytes(isCompressed);\n};\nconst isValidSecretKey = (secretKey) => {\n try {\n return !!secretKeyToScalar(secretKey);\n }\n catch (error) {\n return false;\n }\n};\nconst isValidPublicKey = (publicKey, isCompressed) => {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n};\nconst assertRecoveryBit = (recovery) => [0, 1, 2, 3].includes(recovery) ? recovery : err('invalid recovery id');\nconst assertSigFormat = (format) => {\n if (format === SIG_DER)\n err('Signature format \"der\" is not supported: switch to noble-curves');\n if (format != null && format !== SIG_COMPACT && format !== SIG_RECOVERED)\n err('Signature format must be one of: compact, recovered, der');\n};\nconst assertSigLength = (sig, format = SIG_COMPACT) => {\n assertSigFormat(format);\n const len = lengths.signature + Number(format === SIG_RECOVERED);\n if (sig.length !== len)\n err(`Signature format \"${format}\" expects Uint8Array with length ${len}`);\n};\n/**\n * ECDSA Signature class. Supports only compact 64-byte representation, not DER.\n * @param r - signature `r` scalar.\n * @param s - signature `s` scalar.\n * @param recovery - optional recovery id.\n * @example\n * Build a recovered-format signature object and serialize it.\n * ```ts\n * import { Signature } from '@noble/secp256k1';\n * const bytes = new Signature(1n, 2n, 0).toBytes('recovered');\n * ```\n */\nclass Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = FnIsValidNot0(r); // 1 <= r < N\n this.s = FnIsValidNot0(s); // 1 <= s < N\n // Keep recovered Signature objects internally consistent across all construction paths.\n if (recovery != null)\n this.recovery = assertRecoveryBit(recovery);\n Object.freeze(this);\n }\n static fromBytes(b, format = SIG_COMPACT) {\n assertSigLength(b, format);\n let rec;\n if (format === SIG_RECOVERED) {\n rec = b[0];\n b = b.subarray(1);\n }\n const r = sliceBytesNumBE(b, 0, L);\n const s = sliceBytesNumBE(b, L, L2);\n return new Signature(r, s, rec);\n }\n addRecoveryBit(bit) {\n return new Signature(this.r, this.s, bit);\n }\n hasHighS() {\n return highS(this.s);\n }\n toBytes(format = SIG_COMPACT) {\n // Standalone noble-secp256k1 does not implement DER; reject here so direct Signature users\n // don't silently get compact bytes for an unsupported format.\n assertSigFormat(format);\n const { r, s, recovery } = this;\n const res = concatBytes(numTo32b(r), numTo32b(s));\n if (format === SIG_RECOVERED) {\n return concatBytes(u8of(assertRecoveryBit(recovery)), res);\n }\n return res;\n }\n}\n/**\n * RFC6979: ensure ECDSA msg is X bytes, convert to BigInt.\n * RFC 6979 \u00A72.3.2 says bits2int keeps the leftmost qlen bits and discards the rest.\n * FIPS 186-4 4.6 gives the same leftmost-bit truncation rule. bits2int can produce res>N.\n */\nconst bits2int = (bytes) => {\n // The 8 KiB cap is only a local DoS guard. Longer ordinary prehashes must still follow\n // RFC 6979 \u00A72.3.2 truncation instead of being rejected just because blen > qlen.\n if (bytes.length > 8192)\n err('input is too large');\n const delta = bytes.length * 8 - 256;\n const num = bytesToNumBE(bytes);\n return delta > 0 ? num >> big(delta) : num;\n};\n/** int2octets can't be used; pads small msgs with 0: BAD for truncation as per RFC vectors */\nconst bits2int_modN = (bytes) => modN(bits2int(abytes(bytes)));\n// todo: better name\nconst SIG_COMPACT = 'compact';\nconst SIG_RECOVERED = 'recovered';\nconst SIG_DER = 'der';\nconst _sha = 'SHA-256';\n/**\n * Hash implementations used by the synchronous and async ECDSA / Schnorr helpers.\n * All slots are configurable API surface; wrapper helpers revalidate that SHA-256 and HMAC-SHA256\n * providers still return exact 32-byte Uint8Array digests.\n * @example\n * Provide sync hash helpers before calling the synchronous signing API.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const sig = secp.sign(new Uint8Array([1, 2, 3]), secretKey);\n * ```\n */\nconst hashes = {\n hmacSha256Async: async (key, message) => {\n const s = subtle();\n const name = 'HMAC';\n const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);\n return u8n(await s.sign(name, k, message));\n },\n hmacSha256: undefined,\n sha256Async: async (msg) => u8n(await subtle().digest(_sha, msg)),\n sha256: undefined,\n};\n// prehash=false means the caller already supplies the digest bytes\n// used by sign/verify/recover, and this helper returns the same reference unchanged.\nconst prepMsg = (msg, opts, async_) => {\n const message = abytes(msg, undefined, 'message');\n if (!opts.prehash)\n return message;\n return async_ ? gha('sha256Async', message) : gh('sha256', message);\n};\nconst NULL = /* @__PURE__ */ u8n(0);\nconst byte0 = /* @__PURE__ */ u8of(0x00);\nconst byte1 = /* @__PURE__ */ u8of(0x01);\nconst _maxDrbgIters = 1000;\nconst _drbgErr = 'drbg: tried max amount of iterations';\n// HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.\nconst hmacDrbg = (seed, pred) => {\n let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen\n let k = u8n(L); // In our case, it's always equal to L\n let i = 0; // Iterations counter, will throw when over max\n const reset = () => {\n v.fill(1);\n k.fill(0);\n };\n // h = hmac(K || V || ...). The configured provider is still checked on every call because the\n // exported slot can be replaced or unset at runtime.\n const h = (...b) => gh('hmacSha256', k, concatBytes(v, ...b));\n const reseed = (seed = 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)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n // HMAC-DRBG generate() function\n const gen = () => {\n if (i++ >= _maxDrbgIters)\n err(_drbgErr);\n v = h(); // v = hmac(k || v)\n return v; // One block is enough here because secp256k1 qlen and SHA-256 hlen are both 32 bytes.\n };\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n // `pred` receives the live V buffer from gen(); it must treat that input as read-only and\n // return independent bytes, because reset() scrubs the DRBG state before hmacDrbg returns.\n while (!(res = pred(gen())))\n reseed(); // test predicate until it returns ok\n reset();\n return res;\n};\n// Identical to hmacDrbg, but async: uses built-in WebCrypto\nconst hmacDrbgAsync = async (seed, pred) => {\n let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen\n let k = u8n(L); // In our case, it's always equal to L\n let i = 0; // Iterations counter, will throw when over max\n const reset = () => {\n v.fill(1);\n k.fill(0);\n };\n // h = hmac(K || V || ...). Async provider lookup still goes through `callHash(...)` because the\n // exported slot can be replaced or unset at runtime.\n const h = (...b) => gha('hmacSha256Async', k, concatBytes(v, ...b));\n const reseed = async (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = await h(byte0, seed); // k = hmac(K || V || 0x00 || seed)\n v = await h(); // v = hmac(K || V)\n if (seed.length === 0)\n return;\n k = await h(byte1, seed); // k = hmac(K || V || 0x01 || seed)\n v = await h(); // v = hmac(K || V)\n };\n // HMAC-DRBG generate() function\n const gen = async () => {\n if (i++ >= _maxDrbgIters)\n err(_drbgErr);\n v = await h(); // v = hmac(K || V)\n return v; // Same one-block shortcut: secp256k1 qlen and SHA-256 hlen are both 32 bytes here.\n };\n reset();\n await reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n // Same contract as sync hmacDrbg(): pred sees the live V buffer and must not mutate or return it.\n while (!(res = pred(await gen())))\n await reseed(); // test predicate until it returns ok\n reset();\n return res;\n};\n// RFC6979 signature generation, preparation step.\n// Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.3 & RFC6979.\nconst _sign = (messageHash, secretKey, opts, hmacDrbg) => {\n let { lowS, extraEntropy } = opts; // generates low-s sigs by default\n // RFC6979 3.2: we skip step A\n const int2octets = numTo32b; // int to octets\n const h1i = bits2int_modN(messageHash); // msg bigint\n const h1o = int2octets(h1i); // msg octets\n const d = secretKeyToScalar(secretKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), h1o]; // Step D of RFC6979 3.2\n /** RFC6979 3.6: additional k' (optional). See {@link ECDSAExtraEntropy}. */\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(L) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs);\n const m = h1i; // convert msg to bigint\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k\u22C5G\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 \u2208 [1,q\u22121] 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 const k2sig = (kBytes) => {\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);\n if (!(1n <= k && k < N))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = invert(k, N); // k^-1 mod n\n const q = G.multiply(k).toAffine(); // q = k\u22C5G\n const r = modN(q.x); // r = q.x mod n\n // RFC 6979 \u00A72.4 step 3 / \u00A73.4 only spell out retry for r = 0.\n // FIPS 186-5 \u00A76.4.1 step 11 says deterministic ECDSA should fail on r = 0 or s = 0, but\n // that restart-from-scratch note does not apply here: hmacDrbg() keeps advancing through one\n // RFC6979 stream until k2sig() accepts a candidate, instead of restarting from the same seed.\n if (r === 0n)\n return;\n const s = modN(ik * modN(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === 0n)\n 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; // normalized S\n if (lowS && highS(s)) {\n // if lowS was passed, ensure s is always\n normS = modN(-s); // in the bottom half of CURVE.n\n recovery ^= 1;\n }\n const sig = new Signature(r, normS, recovery); // use normS, not s\n return sig.toBytes(opts.format);\n };\n return hmacDrbg(seed, k2sig);\n};\n// Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.4.\nconst _verify = (sig, messageHash, publicKey, opts = {}) => {\n const { lowS, format } = opts;\n if (sig instanceof Signature)\n err('Signature must be in Uint8Array, use .toBytes()');\n assertSigLength(sig, format);\n abytes(publicKey, undefined, 'publicKey');\n try {\n const { r, s } = Signature.fromBytes(sig, format);\n const h = bits2int_modN(messageHash); // Truncate hash\n const P = Point.fromBytes(publicKey); // Validate public key\n if (lowS && highS(s))\n return false; // lowS bans sig.s >= CURVE.n/2\n const is = invert(s, N); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = doubleScalarMulUns(P, u1, u2).toAffine(); // R = u1\u22C5G + u2\u22C5P\n // Stop if R is identity / zero point. Check is done inside `doubleScalarMulUns`\n const v = modN(R.x); // R.x must be in N's field, not P's\n return v === r; // mod(R.x, n) == r\n }\n catch (error) {\n return false;\n }\n};\nconst setDefaults = (opts) => {\n // Inline defaults keep the same returned keys/values while avoiding the extra defaults object.\n return {\n lowS: opts.lowS ?? true,\n prehash: opts.prehash ?? true,\n format: opts.format ?? SIG_COMPACT,\n extraEntropy: opts.extraEntropy ?? false,\n };\n};\n/**\n * Sign a message using secp256k1. Sync: uses `hashes.sha256` and `hashes.hmacSha256`.\n * Prehashes message with sha256, disable using `prehash: false`.\n * @param message - message bytes to sign.\n * @param secretKey - 32-byte secret key.\n * @param opts - See {@link ECDSASignOpts} for details. Enabling {@link ECDSAExtraEntropy} improves security.\n * @returns ECDSA signature encoded according to `opts.format`.\n * @example\n * Sign a message using secp256k1.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * secp.sign(msg, secretKey);\n * secp.sign(msg, secretKey, { extraEntropy: true });\n * secp.sign(msg, secretKey, { format: 'recovered' });\n * ```\n */\nconst sign = (message, secretKey, opts = {}) => {\n opts = setDefaults(opts);\n assertSigFormat(opts.format);\n const msg = prepMsg(message, opts, false);\n return _sign(msg, secretKey, opts, hmacDrbg);\n};\n/**\n * Sign a message using secp256k1. Async: uses built-in WebCrypto hashes.\n * Prehashes message with sha256, disable using `prehash: false`.\n * @param message - message bytes to sign.\n * @param secretKey - 32-byte secret key.\n * @param opts - See {@link ECDSASignOpts} for details. Enabling {@link ECDSAExtraEntropy} improves security.\n * @returns ECDSA signature encoded according to `opts.format`.\n * @example\n * Sign a message using secp256k1 with the async WebCrypto path.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * await secp.signAsync(msg, secretKey);\n * await secp.signAsync(keccak_256(msg), secretKey, { prehash: false });\n * await secp.signAsync(msg, secretKey, { extraEntropy: true });\n * await secp.signAsync(msg, secretKey, { format: 'recovered' });\n * ```\n */\nconst signAsync = async (message, secretKey, opts = {}) => {\n opts = setDefaults(opts);\n assertSigFormat(opts.format);\n const msg = (await prepMsg(message, opts, true));\n return _sign(msg, secretKey, opts, hmacDrbgAsync);\n};\n/**\n * Verify a signature using secp256k1. Sync: uses `hashes.sha256` and `hashes.hmacSha256`.\n * @param signature - default is 64-byte `compact` format; also see {@link ECDSASignatureFormat}.\n * @param message - message which was signed. Keep in mind `prehash` from opts.\n * @param publicKey - public key that should verify the signature.\n * @param opts - See {@link ECDSAVerifyOpts} for details.\n * @returns `true` when the signature is valid. Unsupported format configuration still\n * throws instead of returning `false`.\n * @example\n * Verify a signature using secp256k1.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * const publicKey = secp.getPublicKey(secretKey);\n * const sig = secp.sign(msg, secretKey);\n * const sigr = secp.sign(msg, secretKey, { format: 'recovered' });\n * secp.verify(sig, msg, publicKey);\n * secp.verify(sig, keccak_256(msg), publicKey, { prehash: false });\n * secp.verify(sig, msg, publicKey, { lowS: false });\n * secp.verify(sigr, msg, publicKey, { format: 'recovered' });\n * ```\n */\nconst verify = (signature, message, publicKey, opts = {}) => {\n opts = setDefaults(opts);\n const msg = prepMsg(message, opts, false);\n return _verify(signature, msg, publicKey, opts);\n};\n/**\n * Verify a signature using secp256k1. Async: uses built-in WebCrypto hashes.\n * @param sig - default is 64-byte `compact` format; also see {@link ECDSASignatureFormat}.\n * @param message - message which was signed. Keep in mind `prehash` from opts.\n * @param publicKey - public key that should verify the signature.\n * @param opts - See {@link ECDSAVerifyOpts} for details.\n * @returns `true` when the signature is valid. Unsupported format configuration still\n * throws instead of returning `false`.\n * @example\n * Verify a signature using secp256k1 with the async WebCrypto path.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * const publicKey = secp.getPublicKey(secretKey);\n * const sig = await secp.signAsync(msg, secretKey);\n * const sigr = await secp.signAsync(msg, secretKey, { format: 'recovered' });\n * await secp.verifyAsync(sig, msg, publicKey);\n * await secp.verifyAsync(sigr, msg, publicKey, { format: 'recovered' });\n * await secp.verifyAsync(sig, keccak_256(msg), publicKey, { prehash: false });\n * ```\n */\nconst verifyAsync = async (sig, message, publicKey, opts = {}) => {\n opts = setDefaults(opts);\n const msg = (await prepMsg(message, opts, true));\n return _verify(sig, msg, publicKey, opts);\n};\nconst _recover = (signature, messageHash) => {\n const sig = Signature.fromBytes(signature, 'recovered');\n const { r, s, recovery } = sig;\n // 0 or 1 recovery id determines sign of \"y\" coordinate.\n // 2 or 3 means q.x was >N.\n assertRecoveryBit(recovery);\n // SEC 1 recovery derives e through the same truncation path as verification, so prehash:false\n // must accept long digests here too instead of hard-requiring 32-byte SHA-256 input.\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const radj = recovery === 2 || recovery === 3 ? r + N : r;\n FpIsValidNot0(radj); // ensure q.x is still a field element\n const head = getPrefix(big(recovery)); // head is 0x02 or 0x03\n const Rb = concatBytes(head, numTo32b(radj)); // concat head + r\n const R = Point.fromBytes(Rb);\n const ir = invert(radj, N); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const point = doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n return point.toBytes();\n};\n/**\n * ECDSA public key recovery. Requires msg hash and recovery id.\n * Follows {@link https://secg.org/sec1-v2.pdf | SEC1} 4.1.6.\n * @param signature - recovered-format signature from `sign(..., { format: 'recovered' })`.\n * @param message - signed message bytes.\n * @param opts - See {@link ECDSARecoverOpts} for details.\n * @returns recovered public key bytes.\n * @example\n * Recover a secp256k1 public key from a recovered-format signature.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = secp.sign(message, secretKey, { format: 'recovered' });\n * secp.recoverPublicKey(sig, message);\n * ```\n */\nconst recoverPublicKey = (signature, message, opts = {}) => {\n const msg = prepMsg(message, setDefaults(opts), false);\n return _recover(signature, msg);\n};\n/**\n * Async ECDSA public key recovery. Requires msg hash and recovery id.\n * @param signature - recovered-format signature from `signAsync(..., { format: 'recovered' })`.\n * @param message - signed message bytes.\n * @param opts - See {@link ECDSARecoverOpts} for details.\n * @returns recovered public key bytes.\n * @example\n * Recover a secp256k1 public key from a recovered-format signature with the async API.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = await secp.signAsync(message, secretKey, { format: 'recovered' });\n * await secp.recoverPublicKeyAsync(sig, message);\n * ```\n */\nconst recoverPublicKeyAsync = async (signature, message, opts = {}) => {\n const msg = (await prepMsg(message, setDefaults(opts), true));\n return _recover(signature, msg);\n};\n/**\n * Elliptic Curve Diffie-Hellman (ECDH) on secp256k1.\n * Result is **NOT hashed** and returns the serialized shared point (compressed by default),\n * not the SEC 1 x-only primitive `z = x_P`.\n * secp256k1 has cofactor `h = 1`, so there is no separate cofactor-ECDH distinction here.\n * @param secretKeyA - local 32-byte secret key.\n * @param publicKeyB - peer public key.\n * @param isCompressed - return 33-byte compressed output when `true`.\n * @returns shared secret point bytes.\n * @example\n * Derive a shared secp256k1 secret with ECDH.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const alice = secp.utils.randomSecretKey();\n * const bob = secp.utils.randomSecretKey();\n * const shared = secp.getSharedSecret(alice, secp.getPublicKey(bob));\n * ```\n */\nconst getSharedSecret = (secretKeyA, publicKeyB, isCompressed = true) => {\n return Point.fromBytes(publicKeyB).multiply(secretKeyToScalar(secretKeyA)).toBytes(isCompressed);\n};\n// FIPS 186-5 Appendix A.4.1 style key generation reduces a wide random integer mod (n - 1) and adds 1.\n// The 48-byte minimum keeps the secp256k1 bias bound below the appendix's epsilon <= 2^-64 target.\nconst randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n abytes(seed);\n // Keep the public range text aligned with the enforced 48-byte FIPS floor.\n if (seed.length < lengths.seed || seed.length > 1024)\n return err('expected 48-1024b', RangeError);\n const num = M(bytesToNumBE(seed), N - 1n);\n return numTo32b(num + 1n);\n};\nconst createKeygen = (getPublicKey) => (seed) => {\n const secretKey = randomSecretKey(seed);\n return {\n secretKey,\n publicKey: getPublicKey(secretKey),\n };\n};\n/**\n * Generates a secp256k1 keypair.\n * @param seed - optional entropy seed.\n * @returns keypair with `secretKey` and `publicKey`.\n * @example\n * Generate a secp256k1 keypair for sync signing.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const { secretKey, publicKey } = secp.keygen();\n * ```\n */\nconst keygen = /* @__PURE__ */ createKeygen(getPublicKey);\n/**\n * Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves.\n * @example\n * Convert bytes to a hex string with the low-level helper namespace.\n * ```ts\n * import { etc } from '@noble/secp256k1';\n * const hex = etc.bytesToHex(new Uint8Array([1, 2, 3]));\n * ```\n */\nconst etc = /* @__PURE__ */ Object.freeze({\n hexToBytes,\n bytesToHex,\n concatBytes,\n bytesToNumberBE: bytesToNumBE,\n numberToBytesBE: numTo32b,\n mod: M,\n invert: invert, // math utilities; keep public alias type aligned with runtime\n randomBytes,\n secretKeyToScalar: secretKeyToScalar,\n abytes: abytes,\n});\n/**\n * Curve-specific key utilities.\n * @example\n * Generate a fresh secret key and derive its public key.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const publicKey = secp.getPublicKey(secretKey);\n * ```\n */\nconst utils = /* @__PURE__ */ Object.freeze({\n isValidSecretKey: isValidSecretKey,\n isValidPublicKey: isValidPublicKey,\n randomSecretKey: randomSecretKey, // preserve the optional seeded call\n});\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n// Internal BIP340 tag names are ASCII-only here, so charCodeAt() is enough; this is not a general UTF-8 encoder.\nconst getTag = (tag) => Uint8Array.from('BIP0340/' + tag, (c) => c.charCodeAt(0));\nconst T_AUX = 'aux';\nconst T_NONCE = 'nonce';\nconst T_CHALLENGE = 'challenge';\n// Both SHA-256 provider slots are configurable, so tag hashing still goes through the checked\n// wrappers even though the built-in defaults are deterministic and the tag bytes are ASCII-only.\nconst taggedHash = (tag, ...messages) => {\n const tagH = gh('sha256', getTag(tag));\n return gh('sha256', concatBytes(tagH, tagH, ...messages));\n};\n// Async twin of taggedHash with the same checked provider boundary.\nconst taggedHashAsync = (tag, ...messages) => gha('sha256Async', getTag(tag)).then((tagH) => gha('sha256Async', concatBytes(tagH, tagH, ...messages)));\n// BIP340 PubKey(sk) = bytes(d'\u22C5G), where bytes(P) is bytes(x(P)); signing also normalizes\n// d to the equivalent scalar whose point has even y so the x-only public key stays canonical.\nconst extpubSchnorr = (priv) => {\n const d_ = secretKeyToScalar(priv);\n const p = G.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const { x, y } = p.assertValidity().toAffine(); // validate Point is not at infinity\n const d = isEven(y) ? d_ : modN(-d_);\n const px = numTo32b(x);\n return { d, px };\n};\nconst bytesModN = (bytes) => modN(bytesToNumBE(bytes));\nconst challenge = (...args) => bytesModN(taggedHash(T_CHALLENGE, ...args));\nconst challengeAsync = async (...args) => bytesModN(await taggedHashAsync(T_CHALLENGE, ...args));\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nconst pubSchnorr = (secretKey) => {\n return extpubSchnorr(secretKey).px; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n};\nconst keygenSchnorr = /* @__PURE__ */ createKeygen(pubSchnorr);\n// Common preparation fn for both sync and async signing\nconst prepSigSchnorr = (message, secretKey, auxRand) => {\n const { px, d } = extpubSchnorr(secretKey);\n return { m: abytes(message), px, d, a: abytes(auxRand, L) };\n};\nconst extractK = (rand) => {\n const k_ = bytesModN(rand); // Let k' = int(rand) mod n\n if (k_ === 0n)\n err('sign failed: k is zero'); // Fail if k' = 0.\n const { px, d } = extpubSchnorr(numTo32b(k_)); // Let R = k'\u22C5G.\n return { rx: px, k: d };\n};\n// Common signature creation helper\nconst createSigSchnorr = (k, px, e, d) => {\n return concatBytes(px, numTo32b(modN(k + e * d)));\n};\nconst E_INVSIG = 'invalid signature produced';\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and defaults to fresh 32-byte randomness; it is not the sole source of\n * k generation, so bad CSPRNG won't be the only entropy source.\n */\nconst signSchnorr = (message, secretKey, auxRand = randomBytes(L)) => {\n const { m, px, d, a } = prepSigSchnorr(message, secretKey, auxRand);\n const aux = taggedHash(T_AUX, a);\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const t = numTo32b(d ^ bytesToNumBE(aux));\n // Let rand = hash/nonce(t || bytes(P) || m)\n const rand = taggedHash(T_NONCE, t, px, m);\n const { rx, k } = extractK(rand);\n // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const e = challenge(rx, px, m);\n const sig = createSigSchnorr(k, rx, e, d);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!verifySchnorr(sig, m, px))\n err(E_INVSIG);\n return sig;\n};\nconst signSchnorrAsync = async (message, secretKey, auxRand = randomBytes(L)) => {\n const { m, px, d, a } = prepSigSchnorr(message, secretKey, auxRand);\n const aux = await taggedHashAsync(T_AUX, a);\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const t = numTo32b(d ^ bytesToNumBE(aux));\n // Let rand = hash/nonce(t || bytes(P) || m)\n const rand = await taggedHashAsync(T_NONCE, t, px, m);\n const { rx, k } = extractK(rand);\n // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const e = await challengeAsync(rx, px, m);\n const sig = createSigSchnorr(k, rx, e, d);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!(await verifySchnorrAsync(sig, m, px)))\n err(E_INVSIG);\n return sig;\n};\nconst callSyncAsyncFn = (res, later) => {\n return res instanceof Promise ? res.then(later) : later(res);\n};\nconst _verifSchnorr = (signature, message, publicKey, challengeFn) => {\n const sig = abytes(signature, L2, 'signature');\n const msg = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, L, 'publicKey');\n try {\n // lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n // Fail if x \u2265 p. Let c = x\u00B3 + 7 mod p.\n const x = bytesToNumBE(pub);\n const y = lift_x(x); // lift_x already returns the unique even root required by BIP340.\n const P_ = new Point(x, y, 1n).assertValidity();\n const px = numTo32b(P_.toAffine().x);\n // P = lift_x(int(pk)); fail if that fails\n const r = sliceBytesNumBE(sig, 0, L); // Let r = int(sig[0:32]); fail if r \u2265 p.\n arange(r, 1n, P);\n const s = sliceBytesNumBE(sig, L, L2); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n arange(s, 1n, N);\n const i = concatBytes(numTo32b(r), px, msg);\n // int(challenge(bytes(r)||bytes(P)||m))%n\n return callSyncAsyncFn(challengeFn(i), (e) => {\n const { x, y } = doubleScalarMulUns(P_, s, modN(-e)).toAffine(); // R = s\u22C5G - e\u22C5P\n if (!isEven(y) || x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n });\n }\n catch (error) {\n return false;\n }\n};\n/** Verifies Schnorr signature. Sync wrapper returns false for post-validation failures\n * after the initial byte checks. */\nconst verifySchnorr = (s, m, p) => _verifSchnorr(s, m, p, challenge);\n/** Async Schnorr verification. Curve/encoding failures after the initial byte checks still\n * become false, but async backend failures reject the promise. Missing crypto.subtle is a\n * runtime/backend error, not an \"invalid signature\" result, so we surface it instead of\n * turning it into false. */\nconst verifySchnorrAsync = async (s, m, p) => _verifSchnorr(s, m, p, challengeAsync);\n/**\n * BIP340 Schnorr helpers over secp256k1.\n * @example\n * Sign and verify a BIP340 Schnorr signature.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = secp.schnorr.sign(message, secretKey);\n * const publicKey = secp.schnorr.getPublicKey(secretKey);\n * const isValid = secp.schnorr.verify(sig, message, publicKey);\n * ```\n */\nconst schnorr = /* @__PURE__ */ Object.freeze({\n keygen: keygenSchnorr,\n getPublicKey: pubSchnorr,\n sign: signSchnorr,\n verify: verifySchnorr,\n signAsync: signSchnorrAsync,\n verifyAsync: verifySchnorrAsync,\n});\n// ## Precomputes\n// --------------\nconst W = 8; // W is window size\nconst scalarBits = 256;\nconst pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8, NOT 32 - see wNAF loop\nconst pwindowSize = 2 ** (W - 1); // 128 for W=8\nconst precompute = () => {\n const points = [];\n let p = G;\n let b = p;\n for (let w = 0; w < pwindows; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < pwindowSize; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // precomputes for base point G\n// Branch-shaped negate helper for wNAF; not a hard constant-time primitive in JavaScript.\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n const pow_2_w = 2 ** W; // 256 for W=8\n const maxNum = pow_2_w; // 256 for W=8\n const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111\n const shiftBy = big(W); // 8 for W=8\n for (let w = 0; w < pwindows; w++) {\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n // We use negative indexes to reduce size of precomputed table by 2x.\n // Instead of needing precomputes 0..256, we only calculate them for 0..128.\n // If an index > 128 is found, we do (256-index) - where 256 is next window.\n // Naive: index +127 => 127, +224 => 224\n // Optimized: index +127 => 127, +224 => 256-32\n if (wbits > pwindowSize) {\n wbits -= maxNum;\n n += 1n;\n }\n const off = w * pwindowSize;\n const offF = off; // offsets, evaluate both\n const offP = off + Math.abs(wbits) - 1;\n const isEven = w % 2 !== 0; // conditions, evaluate both\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // off == I: can't add it. Adding random offF instead.\n f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n if (n !== 0n)\n err('invalid wnaf');\n return { p, f }; // return both real and fake points for JIT/leakage-shape symmetry\n};\n// !! Remove the export below to easily use in REPL / browser console\nexport { etc, getPublicKey, getSharedSecret, hash, hashes, keygen, Point, recoverPublicKey, recoverPublicKeyAsync, schnorr, sign, signAsync, Signature, utils, verify, verifyAsync, };\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\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, b, c) {\n return (a & b) ^ (~a & c);\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, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\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 class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\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) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\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)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, 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 buffer.fill(0);\n }\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 (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : 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 const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\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;\n }\n _cloneIntoMeta(to) {\n const { 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 (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\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/** Initial SHA256 state from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.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 = /* @__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.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\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/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.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// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\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 // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\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/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\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/** 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/** 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/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * Utility functions for cryptographic operations\n */\n\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { sha3_256 } from '@noble/hashes/sha3.js';\n\nfunction isDroppable(v: unknown): boolean {\n return v === undefined || typeof v === 'function' || typeof v === 'symbol';\n}\n\nfunction compareCodeUnits(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Canonicalize a value to its RFC 8785 (JSON Canonicalization Scheme) string.\n *\n * The result is the canonical form of exactly what `JSON.stringify` would put\n * on the wire, so a signer canonicalizing an in-memory object and a verifier\n * canonicalizing the parsed JSON get the same bytes:\n * - object keys are escaped as JSON strings and sorted by UTF-16 code unit;\n * - `undefined`, functions and symbols are dropped from objects and become\n * `null` in arrays;\n * - `toJSON()` is honoured (a Date becomes its ISO string);\n * - non-finite numbers, bigints and circular references throw.\n *\n * Earlier versions interpolated keys unescaped, so `{'a\":1,\"b': 2}` and\n * `{a: 1, b: 2}` produced the same string, and emitted the bare word\n * `undefined`. Output is unchanged for every value that did not hit either\n * defect.\n */\nexport function canonicalizeJson(obj: any): string {\n return serializeCanonical(obj, new Set(), true);\n}\n\nfunction serializeCanonical(input: unknown, seen: Set<object>, top: boolean): string {\n let value = input;\n if (value !== null && typeof value === 'object' && typeof (value as any).toJSON === 'function') {\n value = (value as any).toJSON();\n }\n\n if (value === null) return 'null';\n\n const t = typeof value;\n if (t === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonicalizeJson: non-finite number ${String(value)} has no JSON representation`);\n }\n return JSON.stringify(value);\n }\n if (t === 'boolean' || t === 'string') return JSON.stringify(value);\n if (t === 'bigint') {\n throw new TypeError('canonicalizeJson: bigint has no JSON representation; carry it as a string');\n }\n if (isDroppable(value)) {\n if (top) throw new TypeError(`canonicalizeJson: ${t} is not serializable`);\n return 'null';\n }\n\n const obj = value as object;\n if (seen.has(obj)) throw new TypeError('canonicalizeJson: circular reference');\n seen.add(obj);\n let out: string;\n if (Array.isArray(obj)) {\n out = '[' + obj.map(v => serializeCanonical(v, seen, false)).join(',') + ']';\n } else {\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter(k => !isDroppable(record[k]))\n .sort(compareCodeUnits);\n out =\n '{' +\n keys.map(k => JSON.stringify(k) + ':' + serializeCanonical(record[k], seen, false)).join(',') +\n '}';\n }\n seen.delete(obj);\n return out;\n}\n\n/**\n * Convert string to UTF-8 bytes\n */\nexport function stringToBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert bytes to UTF-8 string\n */\nexport function bytesToString(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert bytes to hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to bytes\n *\n * @throws if the string has odd length or contains a non-hex character.\n * Non-hex input used to decode silently to zero bytes.\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') {\n throw new Error('Hex input must be a string');\n }\n if (hex.length % 2 !== 0) {\n throw new Error('Hex string must have even length');\n }\n if (!/^[0-9a-fA-F]*$/.test(hex)) {\n throw new Error('Hex string contains a non-hex character');\n }\n \n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert bytes to base64url (URL-safe base64 without padding)\n */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '');\n}\n\n/**\n * Convert base64url to bytes\n *\n * @throws if the string is not valid unpadded-or-padded base64url\n */\nexport function base64UrlToBytes(base64url: string): Uint8Array {\n if (typeof base64url !== 'string' || !/^[A-Za-z0-9_-]*={0,2}$/.test(base64url)) {\n throw new Error('Invalid base64url string');\n }\n const unpadded = base64url.replace(/=+$/, '');\n if (unpadded.length % 4 === 1) {\n throw new Error('Invalid base64url string length');\n }\n let base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const padding = base64.length % 4;\n if (padding) {\n base64 += '='.repeat(4 - padding);\n }\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Secure constant-time comparison of two byte arrays\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n \n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n/**\n * Zero out a byte array (for secure key cleanup)\n */\nexport function zeroBytes(bytes: Uint8Array): void {\n bytes.fill(0);\n}\n\n/**\n * Create a hash of the given bytes using the specified algorithm\n *\n * Implemented with @noble/hashes so it behaves identically in Node, browsers\n * and workers; it previously imported Node's `crypto` and needed a shim to\n * bundle.\n */\nexport async function hashBytes(\n bytes: Uint8Array,\n algorithm: string\n): Promise<Uint8Array> {\n if (algorithm === 'sha256') {\n return sha256(bytes);\n } else if (algorithm === 'sha512') {\n return sha512(bytes);\n } else if (algorithm === 'sha3-256') {\n return sha3_256(bytes);\n }\n \n throw new Error(`Unsupported hash algorithm: ${algorithm}`);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\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(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\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(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable \u2014\n * throws or returns malformed bytes \u2014 so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade \u2014 a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2\u22C5size\u22121)P]; width-W wNAF uses size = 2^(W\u22122). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W\u22121); nonzero density ~1/(W+1) (a nonzero digit is followed by W\u22121 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w \u2261 0 mod 2^W: next W\u22121 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = \u03A3 digits[w]\u22C52^(w\u22C5W)` with\n * digits in `[\u22122^(W\u22121)+1, 2^(W\u22121)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P` \u2014 all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44\u22C532 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44\u22C532 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2\u22C5(2^(W\u22121)\u22C5base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window \u2014 zero digits feed\n * the fake accumulator \u2014 and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 \u2014 never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator \u2014 its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 \u2014\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `\u03A3 scalars[i]\u22C5points[i]` via interleaved width-4 wNAF\n * (Strauss\u2013Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L\u22C5bits/5` additions instead of `L\u22C5bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1\u22C5G + u2\u22C5P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER\u22C5P \u225F O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss\u2013Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2\u22C5G + 3\u22C5(2\u22C5G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\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 * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 \u2014 but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\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(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\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)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n 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)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W\u22121)\u22121)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) \u2014 one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) \u2014 the\n * \"interleaving\" method of M\u00F6ller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L\u22C52^(W\u22122)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\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)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\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. See {@link FpFn}:\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(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && 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 = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\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 };\n}\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(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createFROST, } from \"./abstract/frost.js\";\nimport { createHasher, isogenyMap, mapToCurveSimpleSWU, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = Object.create(null);\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst affineXToBytes = ({ x }) => Fpk1.toBytes(x);\nconst hasEven = (y) => !Fpk1.isOdd(y);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(abytes(priv, 32, 'secretKey'));\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const affine = p.toAffine();\n const scalar = hasEven(affine.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: affineXToBytes(affine) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.sqr(x);\n const c = Fp.add(Fp.mulN(xx, x), BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn, BASE } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n if (k_ === _0n)\n throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const affine = p.toAffine();\n const k = hasEven(affine.y) ? k_ : Fn.neg(k_);\n const rx = affineXToBytes(affine);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const rBytes = sig.subarray(0, 32);\n const r = num(rBytes); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!Fp.isValidNot0(r))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s))\n return false;\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(rBytes, pointToBytes(P), m);\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.mulAddUnsafe(s, P, Fn.neg(e)); // s\u22C5G + (-e)\u22C5P, joint Strauss\u2013Shamir\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || !Fp.eql(x, r))\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\nexport const __TEST = /* @__PURE__ */ Object.freeze({ lift_x, frostTweakPublic, frostTweakSecret });\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(abytes(seed, seedLength, 'seed'), secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU;\nconst getMapSWU = () => mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n}))();\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point, merkleRoot) {\n if (merkleRoot === undefined)\n return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t))\n throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y))\n return pub;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])),\n };\n}\nfunction frostSecretToEvenY(s, pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y))\n return s;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n };\n}\nfunction frostNoncesToEvenY(groupCommitment, nonces) {\n if (hasEven(groupCommitment.y))\n return nonces;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n };\n}\nfunction frostTweakSecret(s, pub, merkleRoot) {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n };\n}\nfunction frostTweakPublic(pub, merkleRoot) {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n // Disabled TapTweak (t=0): return the even-Y-normalized package as-is. multiply() rejects\n // zero scalars, and adding [0]G would be a no-op anyway.\n if (t === _0n)\n return PKPackage;\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());\n const verifyingShares = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n };\n}\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32)\n return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33)\n return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1),\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx),\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n}))();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + 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 { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\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, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\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 \u2261 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)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. 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}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\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)) {\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)\n validateSigFormat(optsn.format);\n return optsn;\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 * 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(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\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 const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endo) {\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 const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // SEC 1 v2.0 \u00A72.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())\n return Uint8Array.of(0);\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);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\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)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.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))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n }\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)\n y = Fp.neg(y);\n return { x, y };\n }\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))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\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\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 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)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and \u03C8(P) = (\u03B2\u22C5x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached \u2014 invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\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 static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n 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))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\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 if (validityCache.has(p))\n return;\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))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { 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 = mulA(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 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(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 // 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) {\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 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 = mulA(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 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(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 subtract(other) {\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 is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\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))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\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) {\n const p = this;\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))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a\u22C5this + b\u22C5other` (Strauss\u2013Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1\u22C5G + u2\u22C5P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n 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)\n 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)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\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() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\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 isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\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 toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\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 * 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(Point, ecdhOpts = {}) {\n validatePointCons(Point);\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 function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\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) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\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, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\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) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n 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)\n return undefined;\n return isPub;\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(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n 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 const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\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(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\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 function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\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 assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\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, format) {\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 * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\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))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\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 static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\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) {\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))\n 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.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\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);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\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 = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n 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 : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\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) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\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(message, secretKey, opts) {\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))\n throw new Error('invalid private key');\n const seedArgs = [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); // 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\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b \u2208 [1,n\u22121], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b\u00B7k \u2014 uniformly\n // random, independent of k \u2014 so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\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))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // 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 * 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 \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(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 * 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\u22C5G + u2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\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())\n 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.mulAddUnsafe(u1, P, u2); // u1\u22C5G + u2\u22C5P, joint Strauss\u2013Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\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 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 });\n}\n", "/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\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// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, '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)\n 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)\n 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, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n 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)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\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) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n 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)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n 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) {\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)\n 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)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\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};\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 = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA-1 state from RFC 3174 \u00A76.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\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 }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\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);\n clean(this.buffer);\n }\n}\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n// RFC 1321 \u00A73.4 per-round rotate amounts, flattened to 64 entries so the round loop\n// avoids allocating a 4-element array literal every round (measured ~5% of md5).\nconst MD5_SHIFTS = /* @__PURE__ */ (() => {\n const S = [\n [7, 12, 17, 22],\n [5, 9, 14, 20],\n [4, 11, 16, 23],\n [6, 10, 15, 21],\n ];\n return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);\n})();\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n }\n else if (i < 32) {\n // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, MD5_SHIFTS[i]);\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 this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\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);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n", "/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const base58key = root.privateExtendedKey;\n * const restored = HDKey.fromExtendedKey(base58key);\n * const fromJson = HDKey.fromJSON({ xpriv: base58key });\n * const child = fromJson.derive(\"m/0/2147483647'/1\");\n * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));\n *\n * // props\n * [root.depth, root.index, root.chainCode];\n * [restored.privateKey, restored.publicKey];\n * const sig = child.sign(msgHash);\n * child.verify(msgHash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\nconst Point = /* @__PURE__ */ (() => secp.Point)();\nconst Fn = /* @__PURE__ */ (() => Point.Fn)();\nconst base58check = /* @__PURE__ */ createBase58check(sha256);\nconst MASTER_SECRET = /* @__PURE__ */ (() => {\n return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n})();\nconst BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened child index offset from BIP32. */\nexport const HARDENED_OFFSET = 0x80000000;\nconst hash160 = (data) => ripemd160(sha256(data));\nconst fromU32 = (data) => createView(data).getUint32(0, false);\nconst toU32 = (n, title = 'number') => {\n if (typeof n !== 'number')\n throw new TypeError(`\"${title}\" expected number, got type=${typeof n}`);\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)\n throw new RangeError(`\"${title}\" expected integer in range 0..2**32-1, got ${n}`);\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\nconst validateVersions = (versions, title = 'versions') => {\n if (!(typeof versions === 'object' && versions !== null))\n throw new Error('versions must be an object');\n toU32(versions.private, `${title}.private`);\n toU32(versions.public, `${title}.public`);\n return versions;\n};\n/**\n * HDKey from BIP32\n * @param opt - Node fields used to construct one HDKey instance.\n * @example\n * ```js\n * import { HDKey } from '@scure/bip32';\n * import { randomBytes } from '@noble/hashes/utils.js';\n *\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const account0 = root.derive(\"m/0/1'\");\n * account0.publicKey;\n * ```\n */\nexport class HDKey {\n get fingerprint() {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier() {\n return this.pubHash;\n }\n get pubKeyHash() {\n return this.pubHash;\n }\n // Returns the live private key buffer for this instance.\n // Copy it first if you need an immutable snapshot.\n get privateKey() {\n return this._privateKey || null;\n }\n get publicKey() {\n return this._publicKey || null;\n }\n get privateExtendedKey() {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv)));\n }\n get publicExtendedKey() {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {\n abytes(seed);\n versions = validateVersions(versions);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new RangeError('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length);\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {\n versions = validateVersions(versions);\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n }\n else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n static fromJSON(json) {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n versions;\n depth = 0;\n index = 0;\n chainCode = null;\n parentFingerprint = 0;\n _privateKey;\n _publicKey;\n pubHash;\n constructor(opt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions ? validateVersions(opt.versions) : BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey))\n throw new Error('Invalid private key');\n // Don't alias caller-owned secret buffers.\n this._privateKey = Uint8Array.from(opt.privateKey);\n this._publicKey = secp.getPublicKey(this._privateKey, true);\n }\n else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n }\n else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n derive(path) {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n /**\n * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.\n */\n deriveChild(index, _I) {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index, 'index');\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n }\n else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const out = _I || hmac(sha512, this.chainCode, data);\n abytes(out, 64);\n const childTweak = out.slice(0, 32);\n const chainCode = out.slice(32);\n const opt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n // Fail early instead of re-trying different index\n if (opt.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n try {\n const ctweak = Fn.fromBytes(childTweak);\n // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.\n // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.\n // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n }\n else {\n const point = Point.fromBytes(this._publicKey);\n const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n }\n catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n sign(hash) {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n verify(hash, signature) {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n wipePrivateData() {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON() {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n serialize(version, key) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(toU32(version, 'version'), new Uint8Array([this.depth]), toU32(this.parentFingerprint, 'parentFingerprint'), toU32(this.index, 'index'), this.chainCode, key);\n }\n}\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n deriveChildWithI(key, index, I) {\n // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.\n return key.deriveChild(index, I);\n },\n});\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Freeze the result of a thunk. `/* @__PURE__ */ freeze(() => expr)` keeps the whole\n// initializer tree-shakable: the annotated call's only argument is a function literal,\n// so bundlers drop everything (inner chain()/alphabet() calls included) when unused.\nconst freeze = (fn) => Object.freeze(fn());\nfunction isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n // fallback on byte-oriented views.\n return (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/** Asserts something is Uint8Array. */\nfunction abytes(b) {\n if (!isBytes(b))\n throw new TypeError('Uint8Array expected');\n}\nfunction isArrayOf(isString, arr) {\n if (!Array.isArray(arr))\n return false;\n if (arr.length === 0)\n return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n }\n else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\nfunction afn(input) {\n if (typeof input !== 'function')\n throw new TypeError('function expected');\n return true;\n}\nfunction astr(label, input) {\n if (typeof input !== 'string')\n throw new TypeError(`${label}: string expected`);\n return true;\n}\nfunction anumber(n, title = 'number') {\n if (typeof n !== 'number')\n throw new TypeError(`${title}: expected number, got ${typeof n}`);\n if (!Number.isSafeInteger(n))\n throw new RangeError(`${title}: expected safe integer, got ${n}`);\n}\nfunction anumArr(label, input) {\n if (!isArrayOf(false, input))\n throw new TypeError(`${label}: array of numbers expected`);\n}\nfunction chain(...args) {\n const id = (a) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a, b) => (c) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\nfunction normalize(fn) {\n afn(fn);\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nconst powers = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++)\n res.push(2 ** i);\n return res;\n})();\n// Indexed copy loops instead of Array.from / Uint8Array.from: those go through the\n// iterator protocol on typed arrays, which is ~10x slower and would swamp the fast\n// links' gains on the conversion boundaries.\nfunction u8ToNumArr(u8, len = u8.length) {\n const res = new Array(len);\n for (let i = 0; i < len; i++)\n res[i] = u8[i];\n return res;\n}\n// UTF-8 TextDecoder builds a string from ASCII codes 2x faster than `TextDecoder('latin1')`\n// (4x on freshly allocated, our exact case).\n// All codes here are < 128 (range is validated elsewhere): UTF-8 agrees with ASCII byte-for-byte.\n// UTF-8 needs no ICU, so the probe only guards runtimes without TextDecoder at all (Hermes).\nconst asciiDecoder = /* @__PURE__ */ (() => {\n try {\n const decoder = new TextDecoder();\n // Self-check on the domain we use (codes < 128): reject broken polyfills at\n // probe time instead of producing corrupted codec output later.\n return decoder.decode(Uint8Array.of(0x41, 0x30, 0x2b, 0x7f)) === 'A0+\\x7f'\n ? decoder\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n})();\nconst B2S_CHUNK = 8192; // char codes per String.fromCharCode call, avoids arg-count limits\nfunction charcodesToString(codes) {\n const len = codes.length;\n // Measured crossover: the TextDecoder's per-call setup dominates below ~12 chars,\n // where String.fromCharCode wins (bech32 checksums, base58xmr blocks).\n if (asciiDecoder !== undefined && len >= 12)\n return asciiDecoder.decode(codes);\n if (len <= B2S_CHUNK)\n return String.fromCharCode.apply(null, codes);\n let res = '';\n for (let i = 0; i < len; i += B2S_CHUNK)\n res += String.fromCharCode.apply(null, codes.subarray(i, i + B2S_CHUNK));\n return res;\n}\n/**\n * Linear 8 <-> bits regrouping (radix2Slow semantics), with Uint8Array digits and\n * preallocated output.\n */\nfunction radix2(bits) {\n anumber(bits);\n if (bits <= 0 || bits > 8)\n throw new RangeError('radix2: bits should be in (0..8]');\n const mask = powers[bits] - 1;\n return {\n encode: (bytes) => {\n abytes(bytes);\n const len = bytes.length;\n // 8->bits with zero-bit padding of the last digit, like convertRadix2(padding=true)\n const res = new Uint8Array(Math.ceil((len * 8) / bits));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len;) {\n // At most 7 residual bits plus 24 new bits fit in the signed 32-bit carry.\n if (i + 2 < len) {\n carry = (carry << 24) | (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n pos += 24;\n i += 3;\n }\n else {\n // Constant mask instead of convertRadix2's exact powers[pos]-1 cleanup: with\n // bits <= 8 the residual is pos <= 7 bits, so carry needs at most pos + 8 <= 15\n // meaningful bits. Stale bits in [pos, 16) shift to >= bits on extraction and\n // are removed by `& mask` there and in the tail below.\n carry = ((carry << 8) | bytes[i]) & 0xffff;\n pos += 8;\n i++;\n }\n // Each input adds at least `bits`, so the first extraction is unconditional.\n for (;;) {\n pos -= bits;\n res[j++] = (carry >> pos) & mask;\n if (pos < bits)\n break;\n }\n }\n if (pos > 0)\n res[j] = (carry << (bits - pos)) & mask;\n return res;\n },\n decode: (digits) => {\n // bits->8, strict canonical form, like convertRadix2(padding=false):\n // rejects leftover whole input words and non-zero pad bits.\n const len = digits.length;\n const res = new Uint8Array(Math.floor((len * bits) / 8));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // Same constant-mask carry bound as encode: pos <= 7 residual plus bits <= 8\n // incoming keeps meaningful carry within 15 bits; stale bits above pos are\n // masked out on extraction and in the tail check below.\n carry = ((carry << bits) | digits[i]) & 0xffff;\n pos += bits;\n for (; pos >= 8; pos -= 8)\n res[j++] = (carry >> (pos - 8)) & 0xff;\n }\n carry = (carry << (8 - pos)) & 0xff;\n if (pos >= bits)\n throw new Error('Excess padding');\n if (carry > 0)\n throw new Error(`Non-zero padding: ${carry}`);\n return res;\n },\n };\n}\n/**\n * Digit <-> letter mapping fused with string join (chain(alphabetSlow(letters), join(''))\n * semantics), via char-code lookup tables.\n */\nfunction alphabet(letters, aliases) {\n const len = letters.length;\n // Larger indexes would wrap in the Int8Array reverse table and decode to wrong digits.\n if (len > 128)\n throw new Error('alphabet: max 128 letters');\n const encTable = new Uint8Array(len);\n const decTable = new Int8Array(128).fill(-1);\n for (let i = 0; i < len; i++) {\n const code = letters.charCodeAt(i);\n if (letters.codePointAt(i) !== code || code > 127)\n throw new Error('alphabet: single-char ASCII letters only');\n encTable[i] = code;\n decTable[code] = i;\n }\n // Aliases decode like their canonical letter (e.g. hex case-folding), without a\n // separate normalization pass over the input string.\n if (aliases !== undefined) {\n for (const alias of Object.keys(aliases)) {\n const code = alias.charCodeAt(0);\n const target = decTable[aliases[alias].charCodeAt(0)];\n if (alias.length !== 1 || code > 127 || target === undefined || target === -1)\n throw new Error(`alphabet: invalid alias ${alias}`);\n decTable[code] = target;\n }\n }\n return {\n encode: (digits) => {\n const codes = new Uint8Array(digits.length);\n for (let i = 0; i < digits.length; i++) {\n const d = digits[i];\n const code = encTable[d];\n // Reuse the table lookup's bounds result for the required per-digit range check.\n // Chained radix2 always emits digits < 2**bits === len; check anyway so a\n // mismatched chain throws (like alphabetSlow) instead of silently emitting letter 0.\n if (code === undefined)\n throw new Error(`alphabet.encode: invalid digit ${d}`);\n codes[i] = code;\n }\n return charcodesToString(codes);\n },\n decode: (input) => {\n // Uniform label: this is the decode entry link for nopad codecs, padding for padded\n // ones. Keeps \"decode: string expected\" identical across all built-in codecs\n // (released 2.x said \"join.decode: string expected\").\n astr('decode', input);\n const slen = input.length;\n const digits = new Uint8Array(slen);\n for (let i = 0; i < slen; i++) {\n const code = input.charCodeAt(i);\n const digit = code < 128 ? decTable[code] : -1;\n if (digit === -1)\n throw new Error(`Unknown letter \"${input[i]}\". Allowed: ${letters}`);\n digits[i] = digit;\n }\n return digits;\n },\n };\n}\n/**\n * Pad / unpad (paddingSlow semantics), on the joined string.\n */\nfunction padding(bits, chr = '=') {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data) {\n while ((data.length * bits) % 8)\n data += chr;\n return data;\n },\n decode(input) {\n // Uniform label, see alphabet.decode above.\n astr('decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid length');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const byte = (end - 1) * bits;\n if (byte % 8 === 0)\n throw new Error('padding: excess padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction unsafeWrapper(fn) {\n afn(fn);\n return function (...args) {\n // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n // Do not wrap code that needs to preserve exception details.\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n anumber(len);\n // Reject degenerate zero-byte checksums up front so callers don't accidentally\n // build a no-op checksum stage.\n if (len <= 0)\n throw new RangeError(`checksum length must be positive: ${len}`);\n afn(fn);\n const _fn = fn;\n // Uses the first `len` bytes of fn(data) in both directions.\n // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n return {\n encode(data) {\n abytes(data);\n const sum = _fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data) {\n abytes(data);\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = _fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 \u00A78 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = /* @__PURE__ */ freeze(() => chain(radix2(4), alphabet('0123456789ABCDEF')));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 \u00A76 Table 3 uses uppercase letters, and RFC 4648 \u00A73.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 \u00A77 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV')));\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), normalize((s) => {\n astr('base32crockford.decode', s);\n return s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1');\n})));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n typeof Uint8Array.fromBase64 === 'function')();\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 \u00A73.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\nconst decodeBase64Builtin = (s, isUrl) => {\n astr('base64', s);\n const alphabet = isUrl ? 'base64url' : 'base64';\n // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n // And checking just for whitespace makes decoding about 3x faster than a full range check.\n // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n if (s.length > 0 && ASCII_WHITESPACE.test(s))\n throw new Error('invalid base64');\n return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/** base64 from RFC 4648. Padded. Pure JS version */\nconst base64Fallback = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6)));\n/**\n * base64 from RFC 4648. Padded.\n * Alternative variants: `base64nopad`, `base64url`, `base64urlnopad`.\n * Utilizes native `Uint8Array.fromBase64` builtin, otherwise falls back to `base64fallback` when it's unavailable.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : base64Fallback);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6)));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_')));\n// base58 code\n// -----------\n// Base conversion 256 <-> 58 done on 16-bit limbs, five base58 digits (one divmod by\n// 58**5) per pass, ~10x fewer inner-loop iterations than digit-at-a-time conversion.\n// Exactness: every intermediate is a non-negative integer below 2**53, so float64\n// arithmetic (including Math.floor of the quotients) is exact:\n// - encode: carry * 2**16 + limb < 58**5 * 2**16 < 2**46\n// - decode: limb * 58**5 + carry < 2**16 * 58**5 + 2**30 < 2**46\n// Still O(n^2) overall like any positional-base conversion \u2014 see the base58 DoS note.\nconst B58_GROUP = 656356768; // 58**5 < 2**30; literal (not `58 ** 5`) so bundlers can drop it as dead code\nconst radix58 = {\n encode: (bytes) => {\n abytes(bytes);\n const blen = bytes.length;\n if (blen === 0)\n return new Uint8Array(0);\n // Leading zero bytes map 1:1 to leading zero digits (at most blen-1 explicit zeros;\n // an all-zero value still contributes one digit below).\n let zeros = 0;\n while (zeros < blen - 1 && bytes[zeros] === 0)\n zeros++;\n // Pack big-endian 16-bit limbs; odd length makes the top limb a single byte.\n const nlimbs = Math.ceil(blen / 2);\n const limbs = new Uint16Array(nlimbs);\n const odd = blen & 1;\n if (odd)\n limbs[0] = bytes[0];\n for (let i = odd, j = odd; i < blen; i += 2, j++)\n limbs[j] = (bytes[i] << 8) | bytes[i + 1];\n // Repeated divmod by 58**5; each pass emits one 5-digit group, least significant\n // first. No carry-overflow guard like convertRadix had: that one faced arbitrary\n // caller-chosen bases, while these bounds are static and proven exact above.\n const groups = [];\n let pos = 0; // limbs before pos are known zero\n while (pos < nlimbs) {\n let carry = 0;\n for (let i = pos; i < nlimbs; i++) {\n const cur = carry * 0x10000 + limbs[i];\n const q = Math.floor(cur / B58_GROUP);\n carry = cur - q * B58_GROUP;\n limbs[i] = q;\n if (q === 0 && i === pos)\n pos++;\n }\n groups.push(carry);\n }\n // The top group is nonzero unless the whole value is zero, so total significant\n // digit count is 5 per full group plus the top group's own width. (Writing 5 digits\n // per group and trimming via subarray is smaller code, but the offset view slows\n // encode ~25% and base58xmr 2x \u2014 measured.)\n const top = groups.length - 1;\n let sig = top * 5;\n for (let v = groups[top];; v = Math.floor(v / 58)) {\n sig++;\n if (v < 58)\n break;\n }\n const res = new Uint8Array(zeros + sig); // leading zero digits are already 0\n let j = res.length - 1;\n for (let g = 0; g < top; g++) {\n let v = groups[g];\n for (let k = 0; k < 5; k++) {\n res[j--] = v % 58;\n v = Math.floor(v / 58);\n }\n }\n for (let v = groups[top]; j >= zeros; v = Math.floor(v / 58))\n res[j--] = v % 58;\n return res;\n },\n decode: (digits) => {\n abytes(digits);\n const dlen = digits.length;\n if (dlen === 0)\n return new Uint8Array(0);\n if (dlen >= 65536)\n throw new Error('invalid length');\n let zeros = 0;\n while (zeros < dlen - 1 && digits[zeros] === 0)\n zeros++;\n // Multiply-accumulate 16-bit limbs (little-endian, `used` live) group by group,\n // most significant group first; the first group may be shorter than 5 digits, and\n // its 58**group factor falls out of the digit fold.\n const limbs = new Uint16Array(Math.ceil((dlen * 6) / 16) + 1);\n let used = 0;\n let i = 0;\n let group = dlen % 5 || 5;\n while (i < dlen) {\n let gval = 0;\n let factor = 1;\n for (const end = i + group; i < end; i++) {\n const d = digits[i];\n // Unreachable through the public chain (alphabet emits digits < 58); guards\n // internal misuse from silently corrupting output.\n if (d >= 58)\n throw new Error(`invalid integer: ${d}`);\n gval = gval * 58 + d;\n factor *= 58;\n }\n group = 5;\n let carry = gval;\n for (let k = 0; k < used; k++) {\n const cur = limbs[k] * factor + carry;\n carry = Math.floor(cur / 0x10000);\n limbs[k] = cur - carry * 0x10000;\n }\n for (; carry > 0; carry = Math.floor(carry / 0x10000))\n limbs[used++] = carry % 0x10000;\n }\n // used === 0 means the value is zero: it still contributes one byte, like a lone\n // zero digit does.\n const valueBytes = used === 0 ? 1 : used * 2 - (limbs[used - 1] < 256 ? 1 : 0);\n const res = new Uint8Array(zeros + valueBytes); // leading zero bytes are already 0\n let j = res.length - 1;\n for (let k = 0; k < used; k++) {\n const limb = limbs[k];\n res[j--] = limb & 0xff;\n if (j >= zeros)\n res[j--] = limb >> 8;\n }\n return res;\n },\n};\nconst genBase58 = (abc) => chain(radix58, alphabet(abc));\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58 = /* @__PURE__ */ freeze(() => genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr = /* @__PURE__ */ freeze(() => genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp = /* @__PURE__ */ freeze(() => genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n astr('base58xmr.decode', str);\n const strLen = str.length;\n // Only the last block may be short, and only to one of the XMR_BLOCK_LEN widths \u2014\n // so the output length is known up front and blocks write into place. Growing a\n // number[] via concat per block was quadratic; this keeps decode linear like the\n // block encoding always intended.\n const tailChars = strLen % 11;\n const tailBytes = tailChars === 0 ? 0 : XMR_BLOCK_LEN.indexOf(tailChars);\n if (tailBytes === -1)\n throw new Error(`base58xmr: invalid block length ${tailChars}`);\n const res = new Uint8Array(Math.floor(strLen / 11) * 8 + tailBytes);\n let w = 0;\n for (let i = 0; i < strLen; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = slice.length === 11 ? 8 : tailBytes;\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n for (let j = block.length - blockLen; j < block.length; j++)\n res[w++] = block[j];\n }\n return res;\n },\n}));\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256) => {\n // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n afn(sha256);\n const _sha256 = sha256;\n return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);\n};\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check = createBase58check;\n// BIP 173 character table.\n// Callers adapt the public number[] words API to Uint8Array at the edges (wordsToU8 below):\n// feeding number[] into alphabet.encode would work at runtime, but it turns the shared\n// hot loop polymorphic and measurably slows the RFC 4648 codecs using the same literal.\nconst BECH_ALPHABET = /* @__PURE__ */ alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l');\n// Range-checks while packing: a plain copy would silently wrap out-of-range words\n// (256 -> 0 would encode to a valid letter). Same message the old slow alphabet threw.\nfunction wordsToU8(words) {\n const len = words.length;\n const res = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = words[i];\n if (w < 0 || w >= 32)\n throw new Error(`alphabet.encode: invalid digit ${w}`);\n res[i] = w;\n }\n return res;\n}\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n chk ^= encodingConst;\n const sum = new Uint8Array(6);\n for (let i = 0; i < 6; i++)\n sum[i] = (chk >>> (5 * (5 - i))) & 31;\n return BECH_ALPHABET.encode(sum);\n}\nfunction genBech32(encoding) {\n // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n // Public API words are number[], so adapt the fast radix2's Uint8Array protocol at the edge.\n const _words = radix2(5);\n const toWords = (from) => {\n abytes(from);\n // Dedicated 8->5 regrouping (radix2(5).encode semantics) writing the public number[]\n // directly; encode-into-Uint8Array plus a copy loop measurably regressed this hot path.\n const len = from.length;\n const res = new Array(Math.ceil((len * 8) / 5));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // No carry cleanup needed: stale bits sit above pos and every extraction (including\n // the tail below) masks with `& 31`, so they never reach the output. Masking carry\n // here measurably slowed the loop.\n carry = (carry << 8) | from[i];\n pos += 8;\n for (; pos >= 5; pos -= 5)\n res[j++] = (carry >> (pos - 5)) & 31;\n }\n if (pos > 0)\n res[j] = (carry << (5 - pos)) & 31;\n return res;\n };\n const fromWords = (to) => {\n anumArr('radix2.decode', to);\n // Range-check while packing into the byte buffer: a plain copy would silently\n // truncate out-of-range words. Rejecting negatives is a deliberate fix \u2014 the old\n // convertRadix2 path silently corrupted output for them.\n const len = to.length;\n const digits = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = to[i];\n if (w < 0 || w >= 32)\n throw new Error(`convertRadix2: invalid word=${w}`);\n digits[i] = w;\n }\n return _words.decode(digits);\n };\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n astr('bech32.encode prefix', prefix);\n if (limit !== false)\n anumber(limit, 'limit');\n if (isBytes(words))\n words = u8ToNumArr(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0)\n throw new TypeError(`Invalid prefix length ${plen}`);\n // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(wordsToU8(words))}${sum}`;\n }\n function decode(str, limit = 90) {\n astr('bech32.decode input', str);\n if (limit !== false)\n anumber(limit, 'limit');\n const slen = str.length;\n // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length ${slen}, expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`mixed-case string not allowed`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`invalid separator \"1\"`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6)\n throw new Error('invalid data length');\n const digits = BECH_ALPHABET.decode(data);\n const words = u8ToNumArr(digits, digits.length - 6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n const { prefix, words } = decode(str, false);\n return {\n prefix,\n words,\n bytes: fromWords(words),\n };\n }\n function encodeFromBytes(prefix, bytes) {\n // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n return encode(prefix, toWords(bytes));\n }\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32 = /* @__PURE__ */ freeze(() => genBech32('bech32'));\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m = /* @__PURE__ */ freeze(() => genBech32('bech32m'));\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const byte = data[i];\n // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n // Latin-1/UTF-8. Validating up front keeps the error position exact while the\n // string itself is built in bulk (~3x faster at 1KB than per-char concat).\n if (byte > 127)\n throw new RangeError(`non-ASCII byte ${byte} at ${i}`);\n }\n return charcodesToString(data);\n },\n decode(str) {\n if (typeof str !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof str);\n const res = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n // exact error positions.\n const charCode = str.charCodeAt(i);\n if (charCode > 127)\n throw new RangeError(`non-ASCII char \"${str[i]}\" (${charCode}) at ${i}`);\n res[i] = charCode;\n }\n return res;\n },\n}));\nconst _isWellFormedShim = (str) => {\n // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n // isWellFormed on our tests/fuzz corpus.\n try {\n return encodeURI(str) !== null;\n }\n catch {\n return false;\n }\n};\nconst _isWellFormed = /* @__PURE__ */ (() => \n// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\ntypeof ''.isWellFormed === 'function'\n ? (str) => str.isWellFormed()\n : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8err = (i) => new TypeError(`invalid utf8 at byte ${i}`);\nconst utf8Fallback = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length;) {\n const a = data[i++];\n if (a < 0b1000_0000) {\n res += String.fromCharCode(a);\n continue;\n }\n if (a < 0b1100_0010 || i >= data.length)\n throw utf8err(i - 1);\n const b = data[i++];\n if ((b & 0b1100_0000) !== 0b1000_0000)\n throw utf8err(i - 1);\n let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n if (a >= 0b1110_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const c = data[i++];\n if ((c & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1110_0000 && b < 0b1010_0000) ||\n (a === 0xed && b >= 0b1010_0000))\n throw utf8err(i - 1);\n cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n if (a >= 0b1111_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const d = data[i++];\n if (a > 0b1111_0100 ||\n (d & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1111_0000 && b < 0b1001_0000) ||\n (a === 0b1111_0100 && b >= 0b1001_0000))\n throw utf8err(i - 1);\n cp =\n ((a & 7) << 18) |\n ((b & 0b0011_1111) << 12) |\n ((c & 0b0011_1111) << 6) |\n (d & 0b0011_1111);\n }\n }\n if (cp < 0x10000)\n res += String.fromCharCode(cp);\n else {\n cp -= 0x10000;\n res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n }\n }\n return res;\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n // large Node inputs.\n const res = new Uint8Array(str.length * 3);\n let pos = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0b1000_0000) {\n res[pos++] = c;\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n const d = str.charCodeAt(++i);\n c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n }\n if (c >= 0x10000) {\n res[pos++] = (c >> 18) | 0b1111_0000;\n res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n }\n else if (c >= 0x800)\n res[pos++] = (c >> 12) | 0b1110_0000;\n else\n res[pos++] = (c >> 6) | 0b1100_0000;\n if (c >= 0x800)\n res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n }\n return res.subarray(0, pos);\n },\n}));\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n * throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n * lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = /* @__PURE__ */ freeze(() => {\n let _utf8Encoder;\n let _utf8Decoder;\n const utf8Builtin = {\n // ignoreBOM preserves an explicit leading U+FEFF;\n // fatal rejects invalid UTF-8 bytes instead of replacing them.\n encode(data) {\n abytes(data);\n return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n },\n };\n return {\n // Select each direction once at module init, since\n // TextEncoder and TextDecoder can exist independently.\n encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n };\n});\n// Keep internal parity probes behind a test-only export.\nexport const __TESTS = /* @__PURE__ */ freeze(() => ({\n alphabet: alphabet,\n base64Fallback: base64Fallback,\n radix2: radix2,\n radix58: radix58,\n checksum: checksum,\n utf8Fallback: utf8Fallback,\n _isWellFormedShim: _isWellFormedShim,\n}));\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// Require both directions before enabling the native hex path so encode/decode stay symmetric.\ntypeof Uint8Array.from([]).toHex === 'function' &&\n typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n // Keep local type guards so the native path preserves library-level input errors.\n // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n encode(data) { abytes(data); return data.toHex(); },\n // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = /* @__PURE__ */ freeze(() => hasHexBuiltin\n ? hexBuiltin\n : chain(radix2(4), \n // Case-insensitive decode via table aliases instead of a toLowerCase pass.\n alphabet('0123456789abcdef', { A: 'a', B: 'b', C: 'c', D: 'd', E: 'e', F: 'f' }), normalize((s) => {\n // astr first: same non-string message as the native path, and no `s.length`\n // access on null / undefined while building the error.\n astr('hex', s);\n if (s.length % 2 !== 0)\n throw new TypeError(`hex.decode: odd-length string (${s.length})`);\n return s;\n })));\n", "/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\n// prettier-ignore\nimport { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from \"./utils.js\";\n// Common validation and per-call state setup for sync/async functions.\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1)\n throw new Error('\"c\" (iterations) must be >= 1');\n // RFC 8018 \u00A75.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1)\n throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 \u00A75.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen)\n throw new Error('derived key too long');\n const p = kdfInputToBytes(_password, 'password');\n const s = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n const { iHash, oHash, outputLen } = hmac.create(hash, p);\n // Drive keyed hashes directly; the wrapper is only needed to initialize their HMAC midstates.\n const u = new Uint8Array(outputLen);\n const eng = pbkdf2Engine(iHash, oHash, s, u);\n return { c, dkLen, asyncTick, DK, outputLen, eng };\n}\n// Per-call PRF driver writes U1 into both `u` and `Ti`, then later digests into `u`;\n// shared by the sync and async variants.\nfunction pbkdf2Engine(iHash, oHash, salt, u) {\n const counter = new Uint8Array(4);\n const view = createView(counter);\n // Full clones retain tree/config state; absorb salt before async yields without cloning input.\n const salted = iHash._cloneInto().update(salt);\n // u1() overwrites the worker before reading it. Seed from the outer midstate so a long salt\n // cannot pre-populate a tree stack that the first reset would abandon without wiping.\n const work = oHash._cloneInto();\n const iClone = iHash._cloneInto; // Capture before mixed feedback can materialize state tuples.\n const oClone = oHash._cloneInto;\n return {\n u1: (ti, Ti) => {\n view.setInt32(0, ti, false);\n salted._cloneInto(work).update(counter).digestInto(u);\n oHash._cloneInto(work).update(u).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n },\n // Whole `F` inner loop for the sync variant: one optimized function owns the hot loop.\n rounds: (c, Ti) => {\n for (let ui = 1; ui < c; ui++) {\n iClone.call(iHash, work).update(u).digestInto(u);\n oClone.call(oHash, work).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n },\n output: (DK) => {\n // Keyed templates and derived worker states are secret material.\n iHash.destroy();\n oHash.destroy();\n salted.destroy();\n work.destroy();\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n clean(u);\n return DK;\n },\n };\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n // Uc = PRF(Password, Uc\u22121); Ti ^= Uc\n eng.rounds(c, Ti);\n }\n return eng.output(DK);\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n * @example\n * Tune the async PBKDF2 scheduler for short UI tasks.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', {\n * dkLen: 32,\n * c: 32,\n * asyncTick: 1,\n * });\n * ```\n */\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc\u22121)\n eng.rounds(2, Ti); // c=2 runs exactly one PRF iteration per callback.\n });\n }\n return eng.output(DK);\n}\n", "/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\n// Japanese wordlist\n// The canonical BIP-39 Japanese wordlist starts with \u3042\u3044\u3053\u304F\u3057\u3093.\n// Use that sentinel so generated phrases use U+3000 ideographic spaces.\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\n// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.\n// It also applies NFKD to the \"mnemonic\" + passphrase salt.\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\n// BIP-39 mnemonics are consumed in NFKD form.\n// They must contain 12, 15, 18, 21, or 24 words before checksum validation.\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\n// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new RangeError('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist - Imported wordlist for a specific language.\n * @param strength - Mnemonic strength, from 128 to 256 bits.\n * @returns 12-24 word mnemonic phrase.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new English mnemonic.\n * ```ts\n * import { generateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnemonic = generateMnemonic(wordlist, 128);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new RangeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\n// BIP-39 checksum is the first ENT/32 bits of SHA-256(entropy).\n// Returned as a byte with checksum bits on the left and zeroes on the right.\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return (sha256(entropy)[0] >> bitsLeft) << bitsLeft;\n};\nfunction awordlist(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new TypeError('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new TypeError('wordlist: non-string element: ' + i);\n });\n}\n// BIP-39 appends checksum bits to entropy,\n// then splits the bitstream into 11-bit indexes for a 2048-word list.\nfunction encodeWords(entropy, wordlist) {\n awordlist(wordlist);\n const bytes = new Uint8Array(entropy.length + 1); // entropy || checksum byte\n bytes.set(entropy);\n bytes[entropy.length] = calcChecksum(entropy);\n const words = [];\n let carry = 0; // bit accumulator, holds < 19 bits\n let bits = 0;\n for (const byte of bytes) {\n carry = (carry << 8) | byte;\n bits += 8;\n if (bits >= 11) {\n bits -= 11;\n words.push(wordlist[(carry >>> bits) & 0x7ff]);\n carry &= (1 << bits) - 1;\n }\n }\n // Bits still in carry are the zero right bits of the checksum byte; drop them.\n return words;\n}\n// Reverse of encodeWords: repacks 11-bit indexes into bytes and verifies checksum.\nfunction decodeWords(words, wordlist) {\n awordlist(wordlist);\n const entLen = (words.length / 3) * 4; // every 3 words hold 32 entropy bits + 1 checksum bit\n const bytes = new Uint8Array(entLen + 1); // entropy || checksum byte\n let carry = 0; // bit accumulator, holds < 19 bits\n let bits = 0;\n let pos = 0;\n for (const word of words) {\n const index = wordlist.indexOf(word);\n if (index === -1)\n throw new Error('Unknown word: ' + word);\n carry = (carry << 11) | index;\n bits += 11;\n while (bits >= 8) {\n bits -= 8;\n bytes[pos++] = (carry >>> bits) & 0xff;\n }\n carry &= (1 << bits) - 1;\n }\n // Left-align leftover checksum bits, matching calcChecksum output.\n if (bits > 0)\n bytes[pos] = carry << (8 - bits);\n const entropy = bytes.subarray(0, entLen);\n if (bytes[entLen] !== calcChecksum(entropy))\n throw new Error('Invalid checksum');\n return Uint8Array.from(entropy);\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns Raw entropy bytes.\n * @throws If the mnemonic shape or checksum is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode a mnemonic back into its original entropy bytes.\n * ```ts\n * import { mnemonicToEntropy } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const entropy = mnemonicToEntropy(mnem, wordlist);\n * // Produces the original 16-byte entropy payload.\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n * ```\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = decodeWords(words, wordlist);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy - Byte array.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns 12-24 words.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Convert raw entropy into an English mnemonic.\n * ```ts\n * import { entropyToMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * const mnemonic = entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = encodeWords(entropy, wordlist);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns `true` when mnemonic checksum and words are valid.\n * @example\n * Validate one English mnemonic.\n * ```ts\n * import { validateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ok = validateMnemonic(\n * 'legal winner thank year wave sausage worth useful legal winner thank yellow',\n * wordlist\n * );\n * // => true\n * ```\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\n// BIP-39 salts PBKDF2 with the UTF-8 NFKD string \"mnemonic\" + passphrase.\nconst psalt = (passphrase) => {\n if (typeof passphrase !== 'string')\n throw new TypeError('invalid passphrase type: ' + typeof passphrase);\n return nfkd('mnemonic' + passphrase);\n};\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the async PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeed(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\n// BIP-39 seed derivation is independent from mnemonic generation.\n// These helpers normalize the phrase but do not verify checksum or wordlist membership.\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the sync PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = mnemonicToSeedSync(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed with the native WebCrypto PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n", "/** English BIP39 wordlist. */\nexport const wordlist = /* @__PURE__ */ Object.freeze(`abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n'));\n", "/**\n * BIP32 Hierarchical Deterministic (HD) wallet derivation\n * \n * Implements standard Bitcoin wallet derivation (BIP32/BIP44/BIP84)\n * for ECDSA secp256k1 keys.\n * \n * Supports:\n * - BIP39 mnemonic → seed conversion\n * - BIP32 path derivation (e.g., \"m/44'/0'/0'/0/0\")\n * - Standard Bitcoin wallet paths\n * \n * References:\n * - BIP32: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki\n * - BIP39: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki\n * - BIP44: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n */\n\nimport { HDKey } from '@scure/bip32';\nimport {\n mnemonicToSeedSync,\n validateMnemonic,\n generateMnemonic as generateBIP39Mnemonic,\n} from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english.js';\nimport type { DerivationCapability, DerivationContext, Keypair } from '../types.js';\n\n/**\n * BIP32 derivation implementation for HD wallets.\n * \n * Usage:\n * ```typescript\n * const derivation = new BIP32Derivation();\n * \n * // From mnemonic\n * const mnemonic = \"abandon abandon abandon...\";\n * const keypair = await derivation.deriveKeypair({\n * seed: derivation.mnemonicToSeed(mnemonic),\n * path: \"m/44'/0'/0'/0/0\"\n * });\n * \n * // From existing seed\n * const keypair = await derivation.deriveKeypair({\n * seed: myExistingSeed,\n * path: \"m/44'/0'/0'/0/1\"\n * });\n * ```\n */\nexport class BIP32Derivation implements DerivationCapability {\n /**\n * Derive a keypair from BIP32 path.\n * \n * @param context Must include `seed` and `path`\n * @returns Secp256k1 keypair (compressed public key)\n * @throws If seed or path is missing, or path is invalid\n */\n async deriveKeypair(context: DerivationContext): Promise<Keypair> {\n if (!context.seed) {\n throw new Error('BIP32 derivation requires a seed');\n }\n \n if (!context.path) {\n throw new Error('BIP32 derivation requires a path (e.g., \"m/44\\'/0\\'/0\\'/0/0\")');\n }\n \n try {\n // Create HD key from seed\n const masterKey = HDKey.fromMasterSeed(context.seed);\n \n // Derive child key at path\n const childKey = masterKey.derive(context.path);\n \n if (!childKey.privateKey) {\n throw new Error(`Failed to derive private key at path ${context.path}`);\n }\n \n if (!childKey.publicKey) {\n throw new Error(`Failed to derive public key at path ${context.path}`);\n }\n \n return {\n privateKey: childKey.privateKey,\n publicKey: childKey.publicKey, // Already compressed (33 bytes)\n };\n } catch (error) {\n throw new Error(\n `BIP32 derivation failed at path ${context.path}: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n \n /**\n * Convert BIP39 mnemonic to BIP32 seed.\n * \n * @param mnemonic 12, 15, 18, 21, or 24 word mnemonic\n * @param passphrase Optional BIP39 passphrase\n * @returns 64-byte seed suitable for BIP32\n */\n mnemonicToSeed(mnemonic: string, passphrase?: string): Uint8Array {\n // mnemonicToSeedSync does not check the words or the checksum: any string\n // of the right word count yields a seed. A single mistyped word would\n // silently derive a different wallet, so validate first.\n if (typeof mnemonic !== 'string' || !validateMnemonic(mnemonic, wordlist)) {\n throw new Error(\n 'Invalid BIP39 mnemonic: unknown word, wrong word count, or checksum mismatch'\n );\n }\n return mnemonicToSeedSync(mnemonic, passphrase);\n }\n \n /**\n * Generate a new BIP39 mnemonic.\n * \n * @param strength Entropy bits: 128 (12 words), 256 (24 words), etc.\n * @returns Space-separated mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n return generateBIP39Mnemonic(wordlist, strength);\n }\n \n /**\n * Standard BIP44 path for Bitcoin.\n * \n * @param account Account index (default: 0)\n * @param change 0 = external (receive), 1 = internal (change)\n * @param index Address index\n * @returns BIP44 path string\n */\n static bitcoinPath(account = 0, change = 0, index = 0): string {\n return `m/44'/0'/${account}'/${change}/${index}`;\n }\n \n /**\n * BIP44 path for an explicit SLIP-44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type decides which wallets will find the keys again: Bitcoin\n * (BTC) is 0, Bitcoin SV is 236. There is deliberately no default.\n */\n static bip44Path(coinType: number, account = 0, change = 0, index = 0): string {\n for (const [name, v] of Object.entries({ coinType, account, change, index })) {\n if (!Number.isInteger(v) || v < 0 || v > 0x7fffffff) {\n throw new Error(`BIP44 ${name} must be an integer in [0, 2^31 - 1], got ${String(v)}`);\n }\n }\n if (change !== 0 && change !== 1) {\n throw new Error(`BIP44 change must be 0 (external) or 1 (internal), got ${change}`);\n }\n return `m/44'/${coinType}'/${account}'/${change}/${index}`;\n }\n\n /**\n * Standard BIP84 path for Bitcoin SegWit (native).\n * \n * @param account Account index (default: 0)\n * @param change 0 = external (receive), 1 = internal (change)\n * @param index Address index\n * @returns BIP84 path string\n */\n static bitcoinSegWitPath(account = 0, change = 0, index = 0): string {\n return `m/84'/0'/${account}'/${change}/${index}`;\n }\n}\n", "/**\n * Bitcoin WIF (Wallet Import Format) utilities\n * \n * Encodes/decodes private keys in Bitcoin's standard format.\n * Supports both compressed and uncompressed formats.\n * \n * Reference: https://en.bitcoin.it/wiki/Wallet_import_format\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\n// Base58 alphabet (Bitcoin)\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Encode bytes to Base58.\n */\nfunction base58Encode(data: Uint8Array): string {\n let num = 0n;\n for (const byte of data) {\n num = num * 256n + BigInt(byte);\n }\n \n let encoded = '';\n while (num > 0n) {\n const remainder = Number(num % 58n);\n encoded = BASE58_ALPHABET[remainder] + encoded;\n num = num / 58n;\n }\n \n // Preserve leading zeros\n for (const byte of data) {\n if (byte !== 0) break;\n encoded = '1' + encoded;\n }\n \n return encoded;\n}\n\n/**\n * Decode Base58 string to bytes.\n */\nfunction base58Decode(str: string): Uint8Array {\n let num = 0n;\n for (const char of str) {\n const index = BASE58_ALPHABET.indexOf(char);\n if (index === -1) {\n throw new Error(`Invalid Base58 character: ${char}`);\n }\n num = num * 58n + BigInt(index);\n }\n \n // Convert to bytes\n const bytes: number[] = [];\n while (num > 0n) {\n bytes.unshift(Number(num % 256n));\n num = num / 256n;\n }\n \n // Preserve leading zeros\n for (const char of str) {\n if (char !== '1') break;\n bytes.unshift(0);\n }\n \n return new Uint8Array(bytes);\n}\n\n/**\n * Encode a private key to WIF format.\n * \n * @param privateKey 32-byte private key\n * @param compressed Whether to indicate compressed public key (default: true)\n * @param network 'mainnet' or 'testnet' (default: 'mainnet')\n * @returns WIF-encoded private key string\n */\nexport function encodeWIF(\n privateKey: Uint8Array,\n compressed = true,\n network: 'mainnet' | 'testnet' = 'mainnet'\n): string {\n if (privateKey.length !== 32) {\n throw new Error('Private key must be 32 bytes');\n }\n \n // Version byte: 0x80 for mainnet, 0xEF for testnet\n const version = network === 'mainnet' ? 0x80 : 0xEF;\n \n // Build payload: version + key + (optional compression flag)\n const payload = new Uint8Array(compressed ? 34 : 33);\n payload[0] = version;\n payload.set(privateKey, 1);\n if (compressed) {\n payload[33] = 0x01; // Compression flag\n }\n \n // Checksum: first 4 bytes of double SHA256\n const hash1 = sha256(payload);\n const hash2 = sha256(hash1);\n const checksum = hash2.slice(0, 4);\n \n // Combine payload + checksum\n const data = new Uint8Array(payload.length + 4);\n data.set(payload);\n data.set(checksum, payload.length);\n \n return base58Encode(data);\n}\n\n/**\n * Decode a WIF-encoded private key.\n * \n * @param wif WIF string\n * @returns Object with privateKey, compressed flag, and network\n * @throws If WIF is invalid or checksum fails\n */\nexport function decodeWIF(wif: string): {\n privateKey: Uint8Array;\n compressed: boolean;\n network: 'mainnet' | 'testnet';\n} {\n const data = base58Decode(wif);\n \n if (data.length !== 37 && data.length !== 38) {\n throw new Error('Invalid WIF length');\n }\n \n // Extract checksum\n const payload = data.slice(0, -4);\n const checksum = data.slice(-4);\n \n // Verify checksum\n const hash1 = sha256(payload);\n const hash2 = sha256(hash1);\n const expectedChecksum = hash2.slice(0, 4);\n \n if (!checksum.every((byte, i) => byte === expectedChecksum[i])) {\n throw new Error('Invalid WIF checksum');\n }\n \n // Extract version\n const version = payload[0];\n const network = version === 0x80 ? 'mainnet' : version === 0xEF ? 'testnet' : null;\n if (!network) {\n throw new Error(`Invalid WIF version byte: 0x${version.toString(16)}`);\n }\n \n // Extract private key and compression flag\n const compressed = payload.length === 34 && payload[33] === 0x01;\n const privateKey = payload.slice(1, 33);\n \n return {\n privateKey,\n compressed,\n network,\n };\n}\n", "import * as secp256k1 from '@noble/secp256k1';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { SignatureSuite, Keypair } from '../types.js';\nimport { bytesToHex, hexToBytes, bytesToBase64Url, base64UrlToBytes } from '../utils.js';\nimport { BIP32Derivation } from '../derivation/bip32.js';\nimport { encodeWIF, decodeWIF } from '../derivation/wif.js';\n\n// Wire the synchronous hashes @noble/secp256k1 v3 needs. v2 took a single\n// `etc.hmacSha256Sync`; v3 replaced it with a `hashes` object and also requires sha256,\n// because RFC 6979 nonce derivation and the optional message prehash both go through it.\nsecp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg);\nsecp256k1.hashes.hmacSha256 = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n\n/** A secp256k1 secret key must be a scalar in [1, n - 1]. */\nfunction assertValidSecretKey(bytes: Uint8Array): void {\n if (!secp256k1.utils.isValidSecretKey(bytes)) {\n throw new Error('Private key is not a valid secp256k1 scalar');\n }\n}\n\n/**\n * BSV ECDSA signature suite using secp256k1\n * Compatible with Bitcoin SV / smartledger-bsv\n * \n * Supports BIP32 HD wallet derivation for deterministic key generation.\n */\nexport class BsvEcdsaSuite implements SignatureSuite {\n readonly suiteId = 'bsv-ecdsa-secp256k1';\n readonly version = '1.0.0';\n readonly capabilities = {\n derivation: new BIP32Derivation(),\n };\n\n async generateKeypair(): Promise<Keypair> {\n const privateKey = secp256k1.utils.randomSecretKey();\n const publicKey = secp256k1.getPublicKey(privateKey, true); // compressed\n \n return {\n privateKey,\n publicKey,\n };\n }\n\n async sign(privateKey: Uint8Array, message: Uint8Array): Promise<Uint8Array> {\n try {\n // Deterministic signature (RFC 6979).\n //\n // `prehash: false` IS LOAD-BEARING. @noble/secp256k1 v3 hashes the message with\n // SHA-256 by default; v2 did not, and this suite's contract — like the rest of this\n // library and like Bitcoin tooling generally — is that the caller passes the\n // 32-byte DIGEST. Leaving the default on would SHA-256 the digest a second time:\n // every signature would differ from every one issued before, and no previously\n // issued signature would verify. Nothing would throw.\n //\n // v3 also returns compact 64-byte bytes directly (`format` defaults to 'compact'),\n // so the v2 `.toCompactRawBytes()` call is gone rather than renamed.\n return secp256k1.sign(message, privateKey, { prehash: false });\n } catch (error) {\n throw new Error(`BsvEcdsaSuite signing failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async verify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array\n ): Promise<boolean> {\n try {\n // `prehash: false` for the same reason as sign(): the message is already a digest.\n // If sign and verify ever disagree on this, verification silently fails for every\n // signature rather than erroring.\n return secp256k1.verify(signature, message, publicKey, { prehash: false }) === true;\n } catch (error) {\n // Invalid signature format or other errors count as verification failure\n return false;\n }\n }\n\n exportPublicKey(pub: Uint8Array): string {\n // Export as hex (standard format)\n return bytesToHex(pub);\n }\n\n importPublicKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n // Must decode to a point on the curve (33-byte compressed or 65-byte\n // uncompressed). Any hex string used to be accepted here.\n if (!secp256k1.utils.isValidPublicKey(bytes)) {\n throw new Error('Invalid secp256k1 public key');\n }\n return bytes;\n }\n\n exportPrivateKey(priv: Uint8Array): string {\n // Export as Bitcoin WIF format for maximum compatibility\n return encodeWIF(priv, true, 'mainnet');\n }\n\n importPrivateKey(encoded: string): Uint8Array {\n // Support both hex and WIF formats\n if (encoded.length === 64) {\n // Hex format (64 hex chars = 32 bytes)\n const bytes = hexToBytes(encoded);\n if (bytes.length !== 32) {\n throw new Error('Private key must be 32 bytes');\n }\n assertValidSecretKey(bytes);\n return bytes;\n } else {\n // WIF format (starts with '5', 'K', or 'L' for mainnet compressed)\n try {\n const { privateKey } = decodeWIF(encoded);\n assertValidSecretKey(privateKey);\n return privateKey;\n } catch (error) {\n throw new Error(`Invalid private key format: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n}\n", "import { SignatureSuite, Keypair } from '../types.js';\nimport { bytesToHex, hexToBytes } from '../utils.js';\nimport type { DSA } from '@noble/post-quantum/ml-dsa.js';\n\n// Lazy-load the noble ML-DSA implementations\nlet ml_dsa44_lib: DSA | null = null;\nlet ml_dsa65_lib: DSA | null = null;\nlet ml_dsa87_lib: DSA | null = null;\n\nasync function getMlDsa44(): Promise<DSA> {\n if (!ml_dsa44_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa44_lib = module.ml_dsa44;\n }\n return ml_dsa44_lib;\n}\n\nasync function getMlDsa65(): Promise<DSA> {\n if (!ml_dsa65_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa65_lib = module.ml_dsa65;\n }\n return ml_dsa65_lib;\n}\n\nasync function getMlDsa87(): Promise<DSA> {\n if (!ml_dsa87_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa87_lib = module.ml_dsa87;\n }\n return ml_dsa87_lib;\n}\n\n/**\n * Key sizes for each ML-DSA variant (NIST FIPS 204)\n */\ninterface MlDsaSizes {\n publicKey: number;\n privateKey: number;\n signature: number;\n}\n\nconst ML_DSA_SIZES: Record<string, MlDsaSizes> = {\n 'ml-dsa-44': { publicKey: 1312, privateKey: 2560, signature: 2420 },\n 'ml-dsa-65': { publicKey: 1952, privateKey: 4032, signature: 3309 },\n // FIPS 204 Table 2. (4,864 was the round-3 Dilithium5 size, not ML-DSA-87.)\n 'ml-dsa-87': { publicKey: 2592, privateKey: 4896, signature: 4627 },\n};\n\n/**\n * Base ML-DSA implementation using @noble/post-quantum\n * Provides proper FIPS 204 compliant implementations for all three parameter sets\n */\nabstract class BaseMlDsaSuite implements SignatureSuite {\n abstract readonly suiteId: string;\n readonly version = '2.0.0'; // Bumped for proper implementation\n readonly capabilities = {};\n\n protected abstract get sizes(): MlDsaSizes;\n protected abstract getLib(): Promise<DSA>;\n\n async generateKeypair(): Promise<Keypair> {\n try {\n const lib = await this.getLib();\n const keypair = lib.keygen();\n \n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey,\n };\n } catch (error) {\n throw new Error(`${this.suiteId} key generation failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async sign(privateKey: Uint8Array, message: Uint8Array): Promise<Uint8Array> {\n try {\n const lib = await this.getLib();\n return lib.sign(message, privateKey);\n } catch (error) {\n throw new Error(`${this.suiteId} signing failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async verify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array\n ): Promise<boolean> {\n try {\n const lib = await this.getLib();\n // Wrong-length inputs are rejected here rather than left to the library.\n if (publicKey.length !== this.sizes.publicKey || signature.length !== this.sizes.signature) {\n return false;\n }\n return lib.verify(signature, message, publicKey) === true;\n } catch (error) {\n // Verification failures should return false, not throw\n return false;\n }\n }\n\n exportPublicKey(pub: Uint8Array): string {\n return bytesToHex(pub);\n }\n\n importPublicKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n if (bytes.length !== this.sizes.publicKey) {\n throw new Error(`${this.suiteId} public key must be ${this.sizes.publicKey} bytes, got ${bytes.length}`);\n }\n return bytes;\n }\n\n exportPrivateKey(priv: Uint8Array): string {\n return bytesToHex(priv);\n }\n\n importPrivateKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n if (bytes.length !== this.sizes.privateKey) {\n throw new Error(`${this.suiteId} private key must be ${this.sizes.privateKey} bytes, got ${bytes.length}`);\n }\n return bytes;\n }\n}\n\n/**\n * ML-DSA-44 Suite ✅ PROPERLY IMPLEMENTED\n * \n * NIST FIPS 204 ML-DSA-44 Specification:\n * - Security Level: 2 (equivalent to AES-128)\n * - Public key: 1,312 bytes\n * - Private key: 2,560 bytes\n * - Signature: 2,420 bytes\n * \n * Use cases:\n * - IoT devices with limited storage\n * - Mobile applications\n * - High-volume signing scenarios where size matters\n * - Systems requiring fast signing/verification\n * \n * Trade-offs:\n * - Smallest signatures (fastest to transmit)\n * - Lower security level (but still quantum-safe)\n * - Suitable for most applications until 2030\n */\nexport class MlDsa44Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-44';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-44'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa44();\n }\n}\n\n/**\n * ML-DSA-65 Suite ✅ PROPERLY IMPLEMENTED (Recommended default)\n * \n * NIST FIPS 204 ML-DSA-65 Specification:\n * - Security Level: 3 (equivalent to AES-192)\n * - Public key: 1,952 bytes\n * - Private key: 4,032 bytes\n * - Signature: 3,309 bytes\n * \n * This is the **recommended default** for most applications:\n * - Balanced security vs size trade-off\n * - Strong quantum resistance\n * - Reasonable signature sizes\n * - Good performance\n * \n * Use cases:\n * - General-purpose applications\n * - Web services and APIs\n * - Document signing\n * - Most enterprise applications\n * \n * Comparison to ML-DSA-87:\n * - 28% smaller signatures (3.3KB vs 4.6KB)\n * - 25% smaller public keys (1.9KB vs 2.6KB)\n * - Still provides strong quantum resistance\n */\nexport class MlDsa65Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-65';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-65'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa65();\n }\n}\n\n/**\n * ML-DSA-87 Suite ✅ PROPERLY IMPLEMENTED (Maximum security)\n * \n * NIST FIPS 204 ML-DSA-87 Specification:\n * - Security Level: 5 (equivalent to AES-256)\n * - Public key: 2,592 bytes\n * - Private key: 4,896 bytes\n * - Signature: 4,627 bytes\n * \n * Provides the **highest security level** in NIST FIPS 204:\n * - Maximum quantum resistance\n * - Suitable for long-term secrets (decades)\n * - Government/military grade security\n * \n * Use cases:\n * - High-security applications\n * - Long-term data protection\n * - Government/military systems\n * - Financial institutions\n * - Critical infrastructure\n * \n * Trade-offs:\n * - Largest signatures (~4.6KB)\n * - Highest computational cost\n * - Maximum security guarantee\n */\nexport class MlDsa87Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-87';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-87'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa87();\n }\n}\n\n/**\n * Default ML-DSA Suite (alias for ML-DSA-65)\n * \n * Use this for the recommended security level (NIST Level 3).\n * Provides the best balance between security and efficiency.\n */\nexport class MlDsaSuite extends MlDsa65Suite {\n // Inherits everything from MlDsa65Suite\n}\n", "import { SignatureSuite } from './types.js';\n\n/**\n * Registry for managing signature suite implementations\n */\nexport class SignatureSuiteRegistry {\n private suites = new Map<string, SignatureSuite>();\n\n /**\n * Register a signature suite implementation\n */\n register(suite: SignatureSuite): void {\n if (this.suites.has(suite.suiteId)) {\n throw new Error(`Signature suite already registered: ${suite.suiteId}`);\n }\n this.suites.set(suite.suiteId, suite);\n }\n\n /**\n * Get a signature suite by ID\n * @throws Error if suite is not registered\n */\n getSuite(suiteId: string): SignatureSuite {\n const suite = this.suites.get(suiteId);\n if (!suite) {\n throw new Error(`Unknown signature suite: ${suiteId}. Available: ${this.listSuites().join(', ')}`);\n }\n return suite;\n }\n\n /**\n * Check if a suite is registered\n */\n hasSuite(suiteId: string): boolean {\n return this.suites.has(suiteId);\n }\n\n /**\n * List all registered suite IDs\n */\n listSuites(): string[] {\n return [...this.suites.keys()];\n }\n\n /**\n * Get all registered suite objects\n */\n getAllSuites(): SignatureSuite[] {\n return [...this.suites.values()];\n }\n\n /**\n * Unregister a suite (primarily for testing)\n */\n unregister(suiteId: string): boolean {\n return this.suites.delete(suiteId);\n }\n\n /**\n * Clear all registered suites (primarily for testing)\n */\n clear(): void {\n this.suites.clear();\n }\n}\n\n// Global singleton instance\nexport const globalRegistry = new SignatureSuiteRegistry();\n\n// Auto-register default suites\nimport { BsvEcdsaSuite } from './suites/bsv-ecdsa.js';\nimport { MlDsa44Suite, MlDsa65Suite, MlDsa87Suite } from './suites/ml-dsa.js';\n\n// Register all standard suites by default\nglobalRegistry.register(new BsvEcdsaSuite());\nglobalRegistry.register(new MlDsa44Suite());\nglobalRegistry.register(new MlDsa65Suite());\nglobalRegistry.register(new MlDsa87Suite());\n", "/**\n * Explicit error types for SmartLedger cryptographic operations.\n * These errors provide clear, actionable feedback for debugging and auditing.\n */\n\n/**\n * Base class for all SmartLedger crypto errors.\n */\nexport class SmartLedgerCryptoError extends Error {\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Thrown when a requested key cannot be found.\n */\nexport class KeyNotFoundError extends SmartLedgerCryptoError {\n constructor(public readonly keyId: string) {\n super(`Key not found: ${keyId}`, 'KEY_NOT_FOUND');\n }\n}\n\n/**\n * Thrown when registering a key under an ID that is already taken.\n *\n * Registration never overwrites: replacing the keypair behind an existing ID\n * would silently destroy a private key and re-point every reference to it.\n */\nexport class KeyAlreadyExistsError extends SmartLedgerCryptoError {\n constructor(public readonly keyId: string) {\n super(`Key already exists: ${keyId}`, 'KEY_ALREADY_EXISTS');\n }\n}\n\n/**\n * Thrown when attempting to use an expired key.\n */\nexport class KeyExpiredError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId: string,\n public readonly expiresAt: string\n ) {\n super(\n `Key expired: ${keyId} (expired at ${expiresAt})`,\n 'KEY_EXPIRED'\n );\n }\n}\n\n/**\n * Thrown when a key is in an invalid state for the requested operation.\n */\nexport class KeyInvalidStateError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId: string,\n public readonly currentState: string,\n public readonly requiredState: string\n ) {\n super(\n `Key in invalid state: ${keyId} (current: ${currentState}, required: ${requiredState})`,\n 'KEY_INVALID_STATE'\n );\n }\n}\n\n/**\n * Thrown when a suite is not allowed by the active compliance profile.\n */\nexport class SuiteNotAllowedError extends SmartLedgerCryptoError {\n constructor(\n public readonly suiteId: string,\n public readonly profileName?: string\n ) {\n const profileMsg = profileName ? ` in profile ${profileName}` : '';\n super(\n `Suite not allowed: ${suiteId}${profileMsg}`,\n 'SUITE_NOT_ALLOWED'\n );\n }\n}\n\n/**\n * Thrown when a requested suite cannot be found.\n */\nexport class SuiteNotFoundError extends SmartLedgerCryptoError {\n constructor(public readonly suiteId: string) {\n super(`Suite not found: ${suiteId}`, 'SUITE_NOT_FOUND');\n }\n}\n\n/**\n * Thrown when signature verification fails.\n */\nexport class InvalidSignatureError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId?: string,\n message: string = 'Signature verification failed'\n ) {\n super(message, 'INVALID_SIGNATURE');\n }\n}\n\n/**\n * Thrown when a cryptographic operation fails.\n */\nexport class CryptoOperationError extends SmartLedgerCryptoError {\n constructor(\n public readonly operation: string,\n message: string,\n public readonly cause?: Error\n ) {\n super(\n `Cryptographic operation failed (${operation}): ${message}`,\n 'CRYPTO_OPERATION_FAILED'\n );\n }\n}\n\n/**\n * Thrown when key parameters are invalid.\n */\nexport class InvalidKeyParametersError extends SmartLedgerCryptoError {\n constructor(message: string) {\n super(`Invalid key parameters: ${message}`, 'INVALID_KEY_PARAMETERS');\n }\n}\n\n/**\n * Thrown when a compliance profile violation is detected.\n */\nexport class ComplianceViolationError extends SmartLedgerCryptoError {\n constructor(\n public readonly profileName: string,\n public readonly violation: string\n ) {\n super(\n `Compliance violation in profile ${profileName}: ${violation}`,\n 'COMPLIANCE_VIOLATION'\n );\n }\n}\n", "/**\n * Key Registry for managing cryptographic keypairs across signature suites.\n * \n * Handles:\n * - Key lifecycle (creation, rotation, expiration, revocation)\n * - Storage abstraction (the only backend shipped here is in-memory)\n * - Key metadata tracking (suiteId, usage, timestamps)\n */\n\nimport { Keypair, KeyMeta } from './types.js';\nimport {\n KeyAlreadyExistsError,\n KeyExpiredError,\n KeyInvalidStateError,\n KeyNotFoundError,\n InvalidKeyParametersError,\n} from './errors.js';\n\n/**\n * Storage adapter interface for keypair persistence.\n */\nexport interface KeyStorage {\n /**\n * Store a keypair with associated metadata.\n */\n store(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<void>;\n\n /**\n * Store a keypair only if no key exists under `keyId`, as ONE atomic step.\n * Resolves `true` if it stored, `false` if the ID was already taken.\n *\n * Optional for backward compatibility. Without it KeyRegistry falls back to\n * load-then-store, which two writers sharing a backend can interleave; a\n * backend that is shared between processes should implement this.\n */\n storeIfAbsent?(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<boolean>;\n \n /**\n * Retrieve a keypair by ID.\n * Returns null if not found.\n */\n load(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null>;\n \n /**\n * List all key IDs matching optional filter.\n */\n list(filter?: Partial<KeyMeta>): Promise<KeyMeta[]>;\n \n /**\n * Delete a keypair (use with caution).\n */\n delete(keyId: string): Promise<void>;\n \n /**\n * Update metadata without changing keypair.\n */\n updateMeta(keyId: string, meta: Partial<KeyMeta>): Promise<void>;\n}\n\n/**\n * The agent a key ID belongs to: everything before its last ':'.\n *\n * Key IDs are `<agentId>:<local part>`, and the local part never contains a\n * ':'. Ownership is this exact split, not a prefix test — with a prefix test\n * agent `a` also \"owned\" every key of agent `a:b`.\n *\n * @returns the agent ID, or null if `keyId` has no ':' separator\n */\nexport function agentIdOfKey(keyId: string): string | null {\n if (typeof keyId !== 'string') return null;\n const i = keyId.lastIndexOf(':');\n if (i <= 0 || i === keyId.length - 1) return null;\n return keyId.slice(0, i);\n}\n\n/** Copy metadata so a caller cannot reach the stored record through it. */\nexport function cloneKeyMeta(meta: KeyMeta): KeyMeta {\n return {\n ...meta,\n usage: [...meta.usage],\n ...(meta.derivation ? { derivation: { ...meta.derivation } } : {}),\n };\n}\n\nfunction cloneKeypair(keypair: Keypair): Keypair {\n return {\n publicKey: Uint8Array.from(keypair.publicKey),\n privateKey: Uint8Array.from(keypair.privateKey),\n };\n}\n\n/**\n * Whether `meta` may be used to create new signatures at `now`.\n *\n * A key is usable only if its status is active (or absent, for records written\n * before status existed) AND it has not passed `expiresAt`. Status alone is not\n * enough: nothing flips an expired key's status unless `markExpiredKeys()` is\n * run, so the date has to be checked wherever the key is used.\n */\nexport function isKeyUsable(meta: KeyMeta, now: Date = new Date()): boolean {\n if (meta.status && meta.status !== 'active') return false;\n if (meta.expiresAt !== undefined) {\n const expires = new Date(meta.expiresAt).getTime();\n // An unparseable date is treated as expired, never as \"no expiry\".\n if (Number.isNaN(expires) || expires <= now.getTime()) return false;\n }\n return true;\n}\n\n/**\n * Throw unless `meta` may be used to create new signatures at `now`.\n *\n * @throws {KeyInvalidStateError} if the key is rotated, revoked or marked expired\n * @throws {KeyExpiredError} if the key is past `expiresAt`\n */\nexport function assertKeyUsable(meta: KeyMeta, now: Date = new Date()): void {\n if (meta.status && meta.status !== 'active') {\n throw new KeyInvalidStateError(meta.keyId, meta.status, 'active');\n }\n if (!isKeyUsable(meta, now)) {\n throw new KeyExpiredError(meta.keyId, String(meta.expiresAt));\n }\n}\n\nfunction assertValidExpiry(expiresAt: string | undefined): void {\n if (expiresAt === undefined) return;\n if (typeof expiresAt !== 'string' || Number.isNaN(new Date(expiresAt).getTime())) {\n throw new InvalidKeyParametersError(\n `expiresAt must be an ISO 8601 date, got ${JSON.stringify(expiresAt)}`\n );\n }\n}\n\n/**\n * In-memory key storage (for testing/development only).\n *\n * Private keys are held unencrypted and are lost when the process exits.\n *\n * Records are copied on the way in and on the way out. Handing out the stored\n * objects themselves let any caller holding a KeyRecord edit the registry's\n * state in place — setting `meta.status = 'active'` on a revoked key made it\n * sign again.\n */\nexport class InMemoryKeyStorage implements KeyStorage {\n private keys = new Map<string, { keypair: Keypair; meta: KeyMeta }>();\n \n async store(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<void> {\n this.keys.set(keyId, { keypair: cloneKeypair(keypair), meta: cloneKeyMeta(meta) });\n }\n\n async storeIfAbsent(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<boolean> {\n // No await between the check and the set, so this is atomic on one event loop.\n if (this.keys.has(keyId)) return false;\n this.keys.set(keyId, { keypair: cloneKeypair(keypair), meta: cloneKeyMeta(meta) });\n return true;\n }\n \n async load(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null> {\n const found = this.keys.get(keyId);\n if (!found) return null;\n return { keypair: cloneKeypair(found.keypair), meta: cloneKeyMeta(found.meta) };\n }\n \n async list(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n const allMeta = Array.from(this.keys.values()).map(k => cloneKeyMeta(k.meta));\n \n if (!filter) {\n return allMeta;\n }\n \n return allMeta.filter(meta => {\n return Object.entries(filter).every(([key, value]) => {\n if (key === 'usage' && Array.isArray(value)) {\n // Check if any usage matches\n return value.some(u => meta.usage.includes(u));\n }\n return meta[key as keyof KeyMeta] === value;\n });\n });\n }\n \n async delete(keyId: string): Promise<void> {\n const found = this.keys.get(keyId);\n if (found) {\n // The stored copy is ours alone, so it can be wiped before it is dropped.\n found.keypair.privateKey.fill(0);\n }\n this.keys.delete(keyId);\n }\n \n async updateMeta(keyId: string, updates: Partial<KeyMeta>): Promise<void> {\n const existing = this.keys.get(keyId);\n if (!existing) {\n throw new KeyNotFoundError(keyId);\n }\n \n this.keys.set(keyId, {\n keypair: existing.keypair,\n meta: cloneKeyMeta({ ...existing.meta, ...updates }),\n });\n }\n \n /**\n * Clear all keys (testing only).\n */\n clear(): void {\n for (const { keypair } of this.keys.values()) {\n keypair.privateKey.fill(0);\n }\n this.keys.clear();\n }\n}\n\n/** Options accepted by {@link KeyRegistry.registerKey}. */\nexport interface RegisterKeyOptions {\n expiresAt?: string;\n usage?: KeyMeta['usage'];\n cryptoProfileVersion?: string;\n status?: KeyMeta['status'];\n /** ID of the key this one replaces. */\n rotatedFrom?: string;\n /** How the key was derived, if it was (never the seed). */\n derivation?: KeyMeta['derivation'];\n}\n\n/** Options accepted by {@link KeyRegistry.rotateKey}. */\nexport interface RotateKeyOptions {\n /**\n * Expiry of the NEW key.\n * - omitted: the old key's lifetime (`expiresAt - createdAt`) is granted\n * again, counted from now; no expiry if the old key had none.\n * - an ISO 8601 string: that instant.\n * - `null`: the new key does not expire.\n */\n expiresAt?: string | null;\n /** Derivation record for the new key, if it was derived. */\n derivation?: KeyMeta['derivation'];\n}\n\n/**\n * KeyRegistry manages the lifecycle of cryptographic keys.\n * \n * Features:\n * - Register new keypairs with metadata\n * - Retrieve keys by ID or filter\n * - Key rotation with audit trail\n * - Expiration and revocation\n * - Storage backend abstraction\n */\nexport class KeyRegistry {\n constructor(private storage: KeyStorage = new InMemoryKeyStorage()) {}\n \n /**\n * Register a new keypair with metadata.\n *\n * @throws {KeyAlreadyExistsError} if `keyId` is already registered. A key is\n * never overwritten; delete it explicitly first if that is really intended.\n * @throws {InvalidKeyParametersError} if `keyId` is empty or `expiresAt` is\n * not a parseable date\n */\n async registerKey(\n keyId: string,\n keypair: Keypair,\n suiteId: string,\n options: RegisterKeyOptions = {}\n ): Promise<KeyMeta> {\n if (typeof keyId !== 'string' || keyId.length === 0) {\n throw new InvalidKeyParametersError('keyId must be a non-empty string');\n }\n assertValidExpiry(options.expiresAt);\n\n const meta: KeyMeta = {\n keyId,\n suiteId,\n createdAt: new Date().toISOString(),\n expiresAt: options.expiresAt,\n usage: options.usage ? [...options.usage] : ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n status: options.status || 'active',\n ...(options.rotatedFrom !== undefined ? { rotatedFrom: options.rotatedFrom } : {}),\n ...(options.derivation ? { derivation: { ...options.derivation } } : {}),\n };\n\n if (this.storage.storeIfAbsent) {\n const stored = await this.storage.storeIfAbsent(keyId, keypair, meta);\n if (!stored) throw new KeyAlreadyExistsError(keyId);\n } else {\n // Best effort for backends without an atomic primitive.\n if (await this.storage.load(keyId)) throw new KeyAlreadyExistsError(keyId);\n await this.storage.store(keyId, keypair, meta);\n }\n return cloneKeyMeta(meta);\n }\n \n /**\n * Get a keypair and its metadata.\n */\n async getKey(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null> {\n return await this.storage.load(keyId);\n }\n \n /**\n * Get only the public key (no private key).\n */\n async getPublicKey(keyId: string): Promise<{ publicKey: Uint8Array; meta: KeyMeta } | null> {\n const result = await this.storage.load(keyId);\n if (!result) return null;\n \n return {\n // Copied even if the backend did not, so the caller never holds a\n // reference into the stored record.\n publicKey: Uint8Array.from(result.keypair.publicKey),\n meta: cloneKeyMeta(result.meta),\n };\n }\n \n /**\n * List all keys matching optional filter.\n */\n async listKeys(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n return await this.storage.list(filter);\n }\n \n /**\n * List only active, non-expired keys.\n */\n async listActiveKeys(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n const allKeys = await this.storage.list(filter);\n const now = new Date();\n return allKeys.filter(meta => isKeyUsable(meta, now));\n }\n \n /**\n * Rotate a key: register `newKeypair` under `newKeyId` and mark the old key\n * 'rotated'.\n *\n * The new key is registered BEFORE the old one is retired, so a failure\n * (for example a duplicate `newKeyId`) leaves the old key active rather\n * than leaving the owner with no usable key. If retiring the old key then\n * fails, the new key is removed again.\n *\n * This is two storage operations, not a transaction: two concurrent\n * rotations of the same key on a shared backend can both succeed. Serialise\n * rotation per key if several writers share the storage.\n *\n * @throws {KeyInvalidStateError} if the old key is revoked or already rotated\n *\n * The new key does not inherit the old key's expiry instant — that made a\n * freshly rotated key die on its predecessor's date. See\n * {@link RotateKeyOptions.expiresAt}.\n * \n * Returns the new key's metadata.\n */\n async rotateKey(\n oldKeyId: string,\n newKeyId: string,\n newKeypair: Keypair,\n options: RotateKeyOptions = {}\n ): Promise<KeyMeta> {\n const oldKey = await this.storage.load(oldKeyId);\n if (!oldKey) {\n throw new Error(`Cannot rotate: key not found: ${oldKeyId}`);\n }\n // A revoked key must not come back as a fresh active successor, and a key\n // that was already rotated must not get a second one. An expired key may\n // be rotated: that is how it is renewed.\n if (oldKey.meta.status === 'revoked' || oldKey.meta.status === 'rotated') {\n throw new KeyInvalidStateError(oldKeyId, oldKey.meta.status, 'active or expired');\n }\n\n let expiresAt: string | undefined;\n if (options.expiresAt === null) {\n expiresAt = undefined;\n } else if (options.expiresAt !== undefined) {\n expiresAt = options.expiresAt;\n } else if (oldKey.meta.expiresAt !== undefined) {\n const lifetime =\n new Date(oldKey.meta.expiresAt).getTime() - new Date(oldKey.meta.createdAt).getTime();\n if (Number.isFinite(lifetime) && lifetime > 0) {\n expiresAt = new Date(Date.now() + lifetime).toISOString();\n } else {\n throw new InvalidKeyParametersError(\n `cannot infer a lifetime for the replacement of ${oldKeyId} ` +\n `(createdAt ${oldKey.meta.createdAt}, expiresAt ${oldKey.meta.expiresAt}); ` +\n `pass options.expiresAt`\n );\n }\n }\n\n const newMeta = await this.registerKey(newKeyId, newKeypair, oldKey.meta.suiteId, {\n usage: oldKey.meta.usage,\n cryptoProfileVersion: oldKey.meta.cryptoProfileVersion,\n expiresAt,\n status: 'active',\n rotatedFrom: oldKeyId,\n derivation: options.derivation,\n });\n\n try {\n await this.storage.updateMeta(oldKeyId, {\n status: 'rotated',\n });\n } catch (error) {\n // Do not leave predecessor and successor both active.\n await this.storage.delete(newKeyId).catch(() => undefined);\n throw error;\n }\n\n return newMeta;\n }\n \n /**\n * Revoke a key (marks as unusable, but doesn't delete).\n */\n async revokeKey(keyId: string, reason?: string): Promise<void> {\n await this.storage.updateMeta(keyId, {\n status: 'revoked',\n revokedAt: new Date().toISOString(),\n });\n }\n \n /**\n * Delete a key permanently (use with caution).\n */\n async deleteKey(keyId: string): Promise<void> {\n await this.storage.delete(keyId);\n }\n \n /**\n * Mark expired keys as 'expired' status.\n * Returns count of keys marked expired.\n */\n async markExpiredKeys(): Promise<number> {\n const allKeys = await this.storage.list();\n const now = new Date();\n let count = 0;\n \n for (const meta of allKeys) {\n if (meta.status === 'active' && !isKeyUsable(meta, now)) {\n await this.storage.updateMeta(meta.keyId, {\n status: 'expired',\n });\n count++;\n }\n }\n \n return count;\n }\n \n /**\n * Cleanup: delete keys that have been revoked/expired for longer than retention period.\n * \n * @param retentionDays How many days to keep revoked/expired keys (default: 90)\n */\n async pruneOldKeys(retentionDays: number = 90): Promise<number> {\n const allKeys = await this.storage.list();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n \n let count = 0;\n \n for (const meta of allKeys) {\n const shouldPrune = \n (meta.status === 'revoked' && meta.revokedAt && new Date(meta.revokedAt) < cutoffDate) ||\n (meta.status === 'expired' && meta.expiresAt && new Date(meta.expiresAt) < cutoffDate);\n \n if (shouldPrune) {\n await this.storage.delete(meta.keyId);\n count++;\n }\n }\n \n return count;\n }\n}\n", "/**\n * Default implementation of KeySDK.\n * \n * Integrates KeyRegistry and SignatureSuiteRegistry to provide\n * a clean, high-level API for key operations.\n */\n\nimport {\n KeyRegistry,\n SignatureSuiteRegistry,\n KeyMeta,\n Keypair,\n CryptoProfile,\n hashBytes,\n assertKeyUsable,\n isKeyUsable,\n cloneKeyMeta,\n agentIdOfKey,\n KeyAlreadyExistsError,\n BIP32Derivation,\n InMemoryKeyStorage,\n BsvEcdsaSuite,\n MlDsa44Suite,\n MlDsa65Suite,\n MlDsa87Suite,\n} from '@smartledger/crypto';\nimport {\n KeySDK,\n KeyRecord,\n CreateKeyOptions,\n AgentKeyConfig,\n MultiSignatureResult,\n MultiVerificationResult,\n SuiteSignature,\n SuiteVerificationResult,\n KeyStatusPolicy,\n VerifySignatureOptions,\n VerifyWithSuitesOptions,\n RotateAgentKeysOptions,\n WalletKeyPath,\n} from './types.js';\n\n/**\n * Configuration for DefaultKeySDK.\n */\nexport interface KeySDKConfig {\n /** Key registry instance */\n keyRegistry: KeyRegistry;\n \n /** Signature suite registry instance */\n suiteRegistry: SignatureSuiteRegistry;\n}\n\nexport { agentIdOfKey };\n\nconst COUNTER_SUFFIX = /^pk-[^:-]+-(\\d+)$/;\nconst MAX_KEY_ID_ATTEMPTS = 8;\n\nfunction assertAgentId(agentId: unknown): asserts agentId is string {\n if (typeof agentId !== 'string' || agentId.length === 0) {\n throw new Error('agentId must be a non-empty string');\n }\n}\n\nfunction toRecord(meta: KeyMeta, publicKey: Uint8Array): KeyRecord {\n // Copies, so a caller cannot reach registry state through a KeyRecord even\n // when a custom storage backend hands out its own objects.\n return { meta: cloneKeyMeta(meta), publicKey: Uint8Array.from(publicKey) };\n}\n\nfunction statusAllows(meta: KeyMeta, policy: KeyStatusPolicy): boolean {\n if (policy === 'any') return true;\n if (policy === 'not-revoked') return meta.status !== 'revoked';\n return isKeyUsable(meta);\n}\n\n/**\n * Default KeySDK implementation.\n * \n * Provides a simple, safe API for key operations while hiding complexity.\n */\nexport class DefaultKeySDK implements KeySDK {\n private keyRegistry: KeyRegistry;\n private suiteRegistry: SignatureSuiteRegistry;\n private keyCounter = new Map<string, number>(); // agentId -> counter\n private counterInitialized = new Set<string>();\n private counterInitPromises = new Map<string, Promise<void>>();\n private getOrCreateInFlight = new Map<string, Promise<KeyRecord>>();\n \n constructor(config: KeySDKConfig) {\n this.keyRegistry = config.keyRegistry;\n this.suiteRegistry = config.suiteRegistry;\n }\n \n /**\n * Create a new key for an agent.\n */\n async createKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n\n // Get suite\n const suite = this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n \n // Generate keypair (with optional derivation)\n let keypair;\n \n if (options.derivationContext) {\n // Check if suite supports derivation\n if (!suite.capabilities?.derivation) {\n const available = this.getSuitesWithCapability('derivation');\n throw new Error(\n `Suite '${suite.suiteId}' does not support key derivation.\\n` +\n (available.length > 0\n ? `Suites with derivation capability: ${available.join(', ')}\\n` +\n `Consider using one of these suites or remove the derivationContext option.`\n : `No suites currently support derivation. Remove the derivationContext option.`)\n );\n }\n \n // Use derivation capability\n keypair = await suite.capabilities.derivation.deriveKeypair(options.derivationContext);\n } else {\n // Standard random key generation\n keypair = await suite.generateKeypair();\n }\n \n const meta = await this.registerUnderFreshId(agentId, profile.primarySignatureSuite, keyId =>\n this.keyRegistry.registerKey(keyId, keypair, profile.primarySignatureSuite, {\n expiresAt: options.expiresAt,\n usage: options.usage || ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n // Record that (and where) the key was derived. Never the seed.\n derivation: options.derivationContext\n ? { path: options.derivationContext.path ?? '' }\n : undefined,\n })\n );\n \n return toRecord(meta, keypair.publicKey);\n }\n \n /**\n * Get an existing key.\n */\n async getKey(keyId: string): Promise<KeyRecord | null> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return null;\n }\n \n return toRecord(result.meta, result.publicKey);\n }\n \n /**\n * Sign with a key (private key never exposed).\n *\n * @throws if the key is unknown, not active, past its `expiresAt`, or not\n * registered for signing\n */\n async signWithKey(\n keyId: string,\n message: Uint8Array\n ): Promise<Uint8Array> {\n // Get full keypair (private access)\n const result = await this.keyRegistry.getKey(keyId);\n \n if (!result) {\n throw new Error(`Key not found: ${keyId}`);\n }\n \n if (result.meta.status && result.meta.status !== 'active') {\n throw new Error(`Key is not active: ${keyId} (status: ${result.meta.status})`);\n }\n // Status alone is not enough: an expired key keeps status 'active' until\n // markExpiredKeys() runs, and used to go on signing in the meantime.\n assertKeyUsable(result.meta);\n\n if (!result.meta.usage.some(u => u === 'signing' || u === 'both')) {\n throw new Error(\n `Key is not registered for signing: ${keyId} (usage: ${result.meta.usage.join(', ')})`\n );\n }\n \n // Get suite and sign\n const suite = this.suiteRegistry.getSuite(result.meta.suiteId);\n \n // Hash the message (consistent with signAgentResponse)\n const hashAlg = this.getHashAlgorithm(result.meta.suiteId);\n const messageHash = await hashBytes(message, hashAlg);\n \n return await suite.sign(result.keypair.privateKey, messageHash);\n }\n \n /**\n * Verify a signature.\n *\n * By default this is the cryptographic check only: a signature made by a\n * key that has since been rotated, expired or revoked still verifies, which\n * is what verifying a historical signature needs. Pass `keyStatus` to also\n * require something of the key's state now.\n */\n async verifySignature(\n keyId: string,\n message: Uint8Array,\n signature: Uint8Array,\n options: VerifySignatureOptions = {}\n ): Promise<boolean> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return false;\n }\n\n if (!statusAllows(result.meta, options.keyStatus ?? 'any')) {\n return false;\n }\n \n return this.verifyAgainst(result.meta, result.publicKey, message, signature);\n }\n\n /** The cryptographic check alone. Anything but a strict `true` is a failure. */\n private async verifyAgainst(\n meta: KeyMeta,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array\n ): Promise<boolean> {\n try {\n const suite = this.suiteRegistry.getSuite(meta.suiteId);\n const hashAlg = this.getHashAlgorithm(meta.suiteId);\n const messageHash = await hashBytes(message, hashAlg);\n return (await suite.verify(publicKey, messageHash, signature)) === true;\n } catch {\n return false;\n }\n }\n \n /**\n * List keys for an agent.\n */\n async listKeysForAgent(\n agentId: string,\n activeOnly: boolean = true\n ): Promise<KeyRecord[]> {\n assertAgentId(agentId);\n\n const keys = activeOnly\n ? await this.keyRegistry.listActiveKeys()\n : await this.keyRegistry.listKeys();\n \n // Exact ownership, not a prefix match (see agentIdOfKey)\n const agentKeys = keys.filter(meta => agentIdOfKey(meta.keyId) === agentId);\n \n // Convert to KeyRecords\n const records: KeyRecord[] = [];\n \n for (const meta of agentKeys) {\n const result = await this.keyRegistry.getPublicKey(meta.keyId);\n if (result) {\n records.push(toRecord(result.meta, result.publicKey));\n }\n }\n \n return records;\n }\n \n /**\n * Get active crypto profile for an agent.\n */\n async getActiveCryptoProfile(agentId: string): Promise<CryptoProfile | null> {\n const keys = await this.listKeysForAgent(agentId, true);\n \n if (keys.length === 0) {\n return null;\n }\n \n // Group by suite\n const sorted = this.sortKeysByCreatedAt(keys);\n const suites = new Set(sorted.map(k => k.meta.suiteId));\n const suiteArray = Array.from(suites);\n \n // Assume first is primary, second is secondary\n return {\n primarySignatureSuite: suiteArray[0],\n secondarySignatureSuite: suiteArray[1],\n };\n }\n \n /**\n * Rotate all keys for an agent.\n *\n * Each replacement gets its predecessor's lifetime again, counted from now\n * (or `options.expiresAt`); it does not inherit the old expiry instant.\n *\n * A key derived from a seed cannot be re-derived here, because the SDK does\n * not keep seeds. By default the call refuses, before changing anything,\n * rather than silently swapping a recoverable key for a random one. See\n * {@link RotateAgentKeysOptions.derivedKeys}.\n */\n async rotateAgentKeys(\n agentId: string,\n options: RotateAgentKeysOptions = {}\n ): Promise<KeyRecord[]> {\n const derivedPolicy = options.derivedKeys ?? 'error';\n const activeKeys = await this.listKeysForAgent(agentId, true);\n\n // Decide everything before changing anything.\n const toRotate: KeyRecord[] = [];\n for (const keyRecord of activeKeys) {\n // Resolves the suite now, so an unknown suite fails before any rotation.\n this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n if (keyRecord.meta.derivation) {\n if (derivedPolicy === 'error') {\n throw new Error(\n `Key ${keyRecord.meta.keyId} was derived from a seed ` +\n `(path ${keyRecord.meta.derivation.path || 'unknown'}). Rotating it here would ` +\n `replace it with a random key that the mnemonic cannot recover. Derive the ` +\n `successor yourself with createKeyFromMnemonic at a new path, or pass ` +\n `{ derivedKeys: 'skip' } or { derivedKeys: 'randomize' }. No keys were rotated.`\n );\n }\n if (derivedPolicy === 'skip') continue;\n }\n toRotate.push(keyRecord);\n }\n\n // Generate every replacement before committing any, so a failing suite\n // cannot leave the agent half rotated. The commits below are then one\n // registry rotation per key; they are not a single transaction, so a\n // storage failure part-way through leaves the earlier keys rotated.\n const replacements: Keypair[] = [];\n for (const keyRecord of toRotate) {\n const suite = this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n replacements.push(await suite.generateKeypair());\n }\n\n const newKeys: KeyRecord[] = [];\n \n for (const [i, keyRecord] of toRotate.entries()) {\n const newKeypair = replacements[i];\n \n const newMeta = await this.registerUnderFreshId(agentId, keyRecord.meta.suiteId, newKeyId =>\n this.keyRegistry.rotateKey(keyRecord.meta.keyId, newKeyId, newKeypair, {\n expiresAt: options.expiresAt,\n })\n );\n \n newKeys.push(toRecord(newMeta, newKeypair.publicKey));\n }\n \n return newKeys;\n }\n \n /**\n * Get or create key (idempotent).\n *\n * Concurrent calls on this SDK instance for the same agent and suite share\n * one creation. Two SDK instances (or processes) on one storage backend can\n * still each create a key; that needs a lock in the backend.\n */\n async getOrCreateKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n const slot = JSON.stringify([agentId, profile.primarySignatureSuite]);\n\n const pending = this.getOrCreateInFlight.get(slot);\n if (pending) {\n const record = await pending;\n return toRecord(record.meta, record.publicKey);\n }\n\n const work = (async () => {\n // Check if key exists\n const existingKeys = await this.listKeysForAgent(agentId, true);\n const primaryKey = existingKeys.find(\n k => k.meta.suiteId === profile.primarySignatureSuite\n );\n \n if (primaryKey) {\n return primaryKey;\n }\n \n // Create new key\n return await this.createKey(agentId, profile, options);\n })();\n\n this.getOrCreateInFlight.set(slot, work);\n try {\n return await work;\n } finally {\n this.getOrCreateInFlight.delete(slot);\n }\n }\n\n /**\n * Create both primary and secondary keys for an agent.\n */\n async createDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Idempotent creation of both primary and secondary keys.\n */\n async getOrCreateDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Fail before creating either key if the pair could not be a hybrid pair:\n * an unknown suite, or the same suite twice (two ECDSA keys are not a\n * classical + post-quantum pair, whatever the profile calls them).\n */\n private assertDualProfile(profile: CryptoProfile): void {\n this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n this.suiteRegistry.getSuite(profile.secondarySignatureSuite!);\n if (profile.primarySignatureSuite === profile.secondarySignatureSuite) {\n throw new Error(\n `Dual signature keys need two different suites; both are ${profile.primarySignatureSuite}`\n );\n }\n }\n\n /**\n * Sign with one or more suites for an agent.\n */\n async signWithSuites(\n agentId: string,\n message: Uint8Array,\n suites?: string[]\n ): Promise<MultiSignatureResult> {\n const activeKeys = this.sortKeysByCreatedAt(await this.listKeysForAgent(agentId, true));\n\n if (activeKeys.length === 0) {\n throw new Error(`No active keys found for agent: ${agentId}`);\n }\n\n const suitesToUse = Array.from(\n new Set(suites?.length ? suites : activeKeys.map(k => k.meta.suiteId))\n );\n const signatures: SuiteSignature[] = [];\n\n for (const suiteId of suitesToUse) {\n const key = activeKeys.find(k => k.meta.suiteId === suiteId);\n if (!key) {\n throw new Error(`No active key for suite '${suiteId}' and agent '${agentId}'`);\n }\n\n const signature = await this.signWithKey(key.meta.keyId, message);\n signatures.push({ suiteId, keyId: key.meta.keyId, signature });\n }\n\n return { signatures };\n }\n\n /**\n * Verify a set of signatures as a hybrid (multi-suite) signature by `agentId`.\n *\n * `allValid` is true only when ALL of these hold:\n * - at least one signature was supplied;\n * - every supplied signature is by a key that belongs to `agentId`, names\n * that key's real suite, passes the key-status policy, and verifies;\n * - every REQUIRED suite has such a signature.\n *\n * The required suites come from the verifier: `options.requiredSuites`, or\n * by default the suites of the agent's currently usable keys in this SDK's\n * registry. They are never read from `signatures`. The check walks the\n * required suites and looks each one up among the valid signatures, so an\n * empty list, or one that merely omits the post-quantum signature, is\n * refused instead of passing because everything in it happens to be valid.\n */\n async verifyWithSuites(\n agentId: string,\n message: Uint8Array,\n signatures: SuiteSignature[],\n options: VerifyWithSuitesOptions = {}\n ): Promise<MultiVerificationResult> {\n assertAgentId(agentId);\n const keyStatus = options.keyStatus ?? 'not-revoked';\n\n const requiredSuites = Array.from(\n new Set(\n options.requiredSuites ??\n (await this.listKeysForAgent(agentId, true)).map(k => k.meta.suiteId)\n )\n );\n\n const refuse = (error: string, results: SuiteVerificationResult[] = []): MultiVerificationResult => ({\n results,\n allValid: false,\n requiredSuites,\n missingSuites: requiredSuites.filter(s => !results.some(r => r.valid && r.suiteId === s)),\n error,\n });\n\n if (!Array.isArray(signatures)) {\n return refuse('signatures must be an array');\n }\n\n const results: SuiteVerificationResult[] = [];\n\n for (const entry of signatures) {\n const suiteId = String(entry?.suiteId);\n const keyId = String(entry?.keyId);\n const fail = (error: string) => results.push({ suiteId, keyId, valid: false, error });\n\n try {\n if (agentIdOfKey(keyId) !== agentId) {\n fail(`Key does not belong to agent '${agentId}'`);\n continue;\n }\n const key = await this.keyRegistry.getPublicKey(keyId);\n if (!key) {\n fail('Key not found');\n continue;\n }\n if (key.meta.suiteId !== suiteId) {\n fail(`Suite mismatch: key is ${key.meta.suiteId}, signature claims ${suiteId}`);\n continue;\n }\n if (!statusAllows(key.meta, keyStatus)) {\n fail(`Key status not accepted (status: ${key.meta.status ?? 'active'}, policy: ${keyStatus})`);\n continue;\n }\n if (!(entry.signature instanceof Uint8Array)) {\n fail('Signature must be a Uint8Array');\n continue;\n }\n const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature);\n if (valid) {\n results.push({ suiteId, keyId, valid: true });\n } else {\n fail('Signature verification failed');\n }\n } catch (error) {\n fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (requiredSuites.length === 0) {\n return refuse(\n `No required suites: agent '${agentId}' has no usable keys and options.requiredSuites was not given`,\n results\n );\n }\n if (results.length === 0) {\n return refuse('No signatures supplied', results);\n }\n\n // Walk the REQUIRED suites and look each up among the valid signatures.\n const missingSuites = requiredSuites.filter(\n required => !results.some(r => r.valid && r.suiteId === required)\n );\n const everySuppliedValid = results.every(r => r.valid === true);\n\n return {\n results,\n allValid: everySuppliedValid && missingSuites.length === 0,\n requiredSuites,\n missingSuites,\n ...(missingSuites.length > 0\n ? { error: `No valid signature for required suite(s): ${missingSuites.join(', ')}` }\n : {}),\n };\n }\n \n /**\n * Generate a new BIP39 mnemonic phrase.\n * \n * @param strength 128 (12 words) or 256 (24 words)\n * @returns Mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n const bip32 = new BIP32Derivation();\n return bip32.generateMnemonic(strength);\n }\n \n /**\n * Create a key from a BIP39 mnemonic using HD derivation.\n * \n * Only works with suites that support BIP32 derivation (e.g., bsv-ecdsa-secp256k1).\n * \n * @param agentId Agent identifier\n * @param profile Crypto profile (must use derivation-capable suite)\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path BIP32 derivation path (default: \"m/44'/0'/0'/0/0\")\n * @param passphrase Optional BIP39 passphrase\n * @param options Additional key creation options\n * @returns KeyRecord with derived key\n * @throws if the mnemonic has an unknown word, a wrong word count or a bad checksum\n */\n async createKeyFromMnemonic(\n agentId: string,\n profile: CryptoProfile,\n mnemonic: string,\n path: string = BIP32Derivation.bitcoinPath(0, 0, 0),\n passphrase?: string,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const bip32 = new BIP32Derivation();\n const seed = bip32.mnemonicToSeed(mnemonic, passphrase);\n \n try {\n return await this.createKey(agentId, profile, {\n ...options,\n derivationContext: {\n seed,\n path,\n },\n });\n } finally {\n // The seed is the root of every key in the wallet; do not leave it behind.\n seed.fill(0);\n }\n }\n \n /**\n * Get available capabilities for a specific suite.\n * \n * @param suiteId Suite identifier\n * @returns Array of capability names\n */\n getCapabilities(suiteId: string): string[] {\n const suite = this.suiteRegistry.getSuite(suiteId);\n const caps: string[] = [];\n \n if (suite.capabilities?.derivation) caps.push('derivation');\n if ((suite.capabilities as any)?.encryption) caps.push('encryption');\n if ((suite.capabilities as any)?.threshold) caps.push('threshold');\n \n return caps;\n }\n \n /**\n * Get all suite IDs that support a specific capability.\n * \n * @param capability Capability name\n * @returns Array of suite IDs\n */\n getSuitesWithCapability(capability: 'derivation' | 'encryption' | 'threshold'): string[] {\n const allSuites = this.suiteRegistry.getAllSuites();\n return allSuites\n .filter(suite => !!(suite.capabilities as any)?.[capability])\n .map(suite => suite.suiteId);\n }\n\n /**\n * Create a wallet key from a mnemonic at an explicit BIP44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type is required and has no default. It decides which wallets\n * will find the key again: Bitcoin (BTC) is 0, Bitcoin SV is 236.\n *\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path Coin type and position in the BIP44 tree\n * @param options Additional key creation options\n * @returns KeyRecord with the derived secp256k1 key\n */\n async createWalletKey(\n agentId: string,\n mnemonic: string,\n path: WalletKeyPath,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n if (!path || typeof path.coinType !== 'number') {\n throw new Error(\n 'createWalletKey requires path.coinType (SLIP-44: Bitcoin is 0, Bitcoin SV is 236)'\n );\n }\n const derivationPath = BIP32Derivation.bip44Path(\n path.coinType,\n path.account ?? 0,\n path.change ? 1 : 0,\n path.index ?? 0\n );\n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n derivationPath,\n path.passphrase,\n options\n );\n }\n \n /**\n * Create a wallet key from mnemonic at the Bitcoin (BTC) BIP44 path:\n * m/44'/0'/account'/change/addressIndex\n *\n * NOTE: coin type 0 is BTC. A Bitcoin SV wallet restoring the same mnemonic\n * looks under coin type 236 and will not find this key. The path is left\n * as it is because changing it would move every key already created with\n * this method. For new code use {@link createWalletKey}, which makes the\n * coin type explicit.\n * \n * @deprecated Use createWalletKey(agentId, mnemonic, { coinType, ... }).\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase\n * @param accountIndex Account index (default: 0)\n * @param addressIndex Address index (default: 0)\n * @param isChange Use change address path (default: false)\n * @param options Additional key creation options\n * @returns KeyRecord with Bitcoin-compatible key\n */\n async createBitcoinWalletKey(\n agentId: string,\n mnemonic: string,\n accountIndex: number = 0,\n addressIndex: number = 0,\n isChange: boolean = false,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const path = BIP32Derivation.bitcoinPath(accountIndex, isChange ? 1 : 0, addressIndex);\n \n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n path,\n undefined,\n options\n );\n }\n \n /**\n * Helper: Get hash algorithm for a suite.\n */\n private getHashAlgorithm(suiteId: string): 'sha256' | 'sha3-256' | 'sha512' {\n if (suiteId.startsWith('ml-dsa')) {\n return 'sha3-256';\n }\n return 'sha256';\n }\n\n /**\n * Helper: register a key under the agent's next free key ID.\n *\n * The counter is cached per SDK instance, so another instance (or process)\n * on the same storage can have taken the ID already. The registry refuses\n * to overwrite; on that refusal the counter is re-read from storage and the\n * next ID is tried. Before, the second writer silently replaced the first\n * writer's private key.\n */\n private async registerUnderFreshId(\n agentId: string,\n suiteId: string,\n register: (keyId: string) => Promise<KeyMeta>\n ): Promise<KeyMeta> {\n // 'ml' for every ml-dsa suite, 'bsv' for bsv-ecdsa-secp256k1\n const suiteName = suiteId.split('-')[0].replace(/[^A-Za-z0-9]/g, '') || 'key';\n\n for (let attempt = 0; attempt < MAX_KEY_ID_ATTEMPTS; attempt++) {\n const counter = await this.getNextCounter(agentId);\n const keyId = `${agentId}:pk-${suiteName}-${counter}`;\n try {\n return await register(keyId);\n } catch (error) {\n if (!(error instanceof KeyAlreadyExistsError)) throw error;\n // Someone else holds that ID: forget the cached counter and re-read.\n this.counterInitialized.delete(agentId);\n this.keyCounter.delete(agentId);\n }\n }\n throw new Error(\n `Could not allocate a key ID for agent '${agentId}' after ${MAX_KEY_ID_ATTEMPTS} attempts`\n );\n }\n \n /**\n * Helper: Get next counter for an agent.\n */\n private async getNextCounter(agentId: string): Promise<number> {\n if (!this.counterInitialized.has(agentId)) {\n if (!this.counterInitPromises.has(agentId)) {\n const initPromise = (async () => {\n try {\n const existing = await this.keyRegistry.listKeys();\n const max = existing.reduce((acc, meta) => {\n if (agentIdOfKey(meta.keyId) !== agentId) return acc;\n const local = meta.keyId.slice(agentId.length + 1);\n const match = COUNTER_SUFFIX.exec(local);\n if (!match) return acc;\n const num = parseInt(match[1], 10);\n return Number.isSafeInteger(num) ? Math.max(acc, num) : acc;\n }, 0);\n // A counter handed out while this scan ran must not be reused.\n this.keyCounter.set(agentId, Math.max(max, this.keyCounter.get(agentId) || 0));\n this.counterInitialized.add(agentId);\n } finally {\n this.counterInitPromises.delete(agentId);\n }\n })();\n this.counterInitPromises.set(agentId, initPromise);\n }\n\n const pendingInit = this.counterInitPromises.get(agentId);\n if (pendingInit) {\n await pendingInit;\n }\n }\n\n const current = this.keyCounter.get(agentId) || 0;\n const next = current + 1;\n this.keyCounter.set(agentId, next);\n return next;\n }\n\n /**\n * Helper: sort keys deterministically by createdAt then keyId.\n */\n private sortKeysByCreatedAt(keys: KeyRecord[]): KeyRecord[] {\n return [...keys].sort((a, b) => {\n const aTime = new Date(a.meta.createdAt).getTime();\n const bTime = new Date(b.meta.createdAt).getTime();\n if (aTime !== bTime) return aTime - bTime;\n const priorityDiff = this.getSuitePriority(a.meta.suiteId) - this.getSuitePriority(b.meta.suiteId);\n if (priorityDiff !== 0) return priorityDiff;\n return a.meta.keyId.localeCompare(b.meta.keyId);\n });\n }\n\n private getSuitePriority(suiteId: string): number {\n if (suiteId.startsWith('ml-dsa')) return 0;\n if (suiteId.includes('ecdsa')) return 1;\n return 2;\n }\n}\n\n/**\n * Create a KeySDK instance with default configuration\n * \n * Uses in-memory storage and registers both ECDSA and ML-DSA suites.\n * For custom storage or different suites, instantiate DefaultKeySDK directly.\n * \n * @example\n * ```typescript\n * import { createKeySDK } from '@smartledger/keys';\n * \n * const sdk = createKeySDK();\n * const key = await sdk.createKey('my-agent', { primarySignatureSuite: 'ml-dsa-87' });\n * ```\n */\nexport function createKeySDK(config?: Partial<KeySDKConfig>): KeySDK {\n const keyRegistry = config?.keyRegistry || new KeyRegistry(new InMemoryKeyStorage());\n const suiteRegistry = config?.suiteRegistry || new SignatureSuiteRegistry();\n \n // Register default suites if not provided.\n //\n // All three ML-DSA levels are registered, not just 87. The README documents\n // ml-dsa-65 as the recommended default and ml-dsa-44 for constrained\n // devices; registering only 87 made every one of those examples throw\n // `Unknown signature suite` at runtime, with no way for a caller to fix it\n // -- SignatureSuiteRegistry is not re-exported from this package.\n if (!config?.suiteRegistry) {\n suiteRegistry.register(new BsvEcdsaSuite());\n suiteRegistry.register(new MlDsa44Suite());\n suiteRegistry.register(new MlDsa65Suite());\n suiteRegistry.register(new MlDsa87Suite());\n }\n \n return new DefaultKeySDK({\n keyRegistry,\n suiteRegistry,\n });\n}\n"],
|
|
5
|
-
"mappings": "0nBAUO,SAASA,GAAQC,EAAG,CAKvB,OAAQA,aAAa,YAChB,YAAY,OAAOA,CAAC,GACjBA,EAAE,YAAY,OAAS,cACvB,sBAAuBA,GACvBA,EAAE,oBAAsB,CACpC,CAiBO,SAASC,GAAQC,EAAGC,EAAQ,GAAI,CACnC,GAAI,OAAOD,GAAM,SACb,MAAM,IAAI,UAAUE,GAAOD,CAAK,EAAI,wBAA0B,OAAOD,CAAC,EAC1E,GAAI,CAAC,OAAO,cAAcA,CAAC,GAAKA,EAAI,EAChC,MAAM,IAAI,WAAWE,GAAOD,CAAK,EAAI,8BAAgCD,CAAC,EAC1E,OAAOA,CACX,CAaO,SAASG,GAAMC,EAAOH,EAAQ,GAAI,CACrC,GAAI,OAAOG,GAAU,UACjB,MAAM,IAAI,UAAUF,GAAOD,CAAK,EAAI,8BAAgC,OAAOG,CAAK,EACpF,OAAOA,CACX,CAeO,SAASC,EAAOD,EAAOE,EAAQL,EAAQ,GAAI,CAG9C,GAAIJ,GAAQO,CAAK,IAAME,IAAW,QAAaF,EAAM,SAAWE,GAC5D,OAAOF,EAEPE,IAAW,QACXP,GAAQO,EAAQ,QAAQ,EAC5B,IAAMC,EAAQV,GAAQO,CAA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jG,OAAIG,IAAiB,EAAUA,EACxBJ,EAAE,KAAK,MAAM,cAAcC,EAAE,KAAK,KAAK,CAChD,CAAC,CACH,CAEQ,iBAAiBxC,EAAyB,CAChD,OAAIA,EAAQ,WAAW,QAAQ,EAAU,EACrCA,EAAQ,SAAS,OAAO,EAAU,EAC/B,CACT,CACF,EvBt0BA,eAAsB4C,GAAaC,EAAyD,CAC1F,IAAMC,EAAcD,GAAQ,aAAe,IAAIE,GAAY,IAAIC,EAAoB,EAUnF,OANY,IAAIC,GAAc,CAC5B,YAAAH,EACA,cAAeI,EACjB,CAAC,CAIH,CAKA,IAAOC,GAAQ,CACb,aAAAP,EACF,EAGI,OAAO,OAAW,MACnB,OAAe,UAAY,CAC1B,aAAAA,EACF",
|
|
6
|
-
"names": ["isBytes", "a", "anumber", "n", "title", "atitle", "abool", "value", "abytes", "length", "bytes", "ofLen", "got", "message", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "u32", "arr", "clean", "arrays", "i", "createView", "rotr", "word", "shift", "rotl", "byteSwap", "byteSwap32", "bytesToHex", "hasHexBuiltin", "hex", "hexes", "asciiToBase16", "ch", "hexToBytes", "error", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "utf8ToBytes", "str", "kdfInputToBytes", "data", "errorTitle", "concatBytes", "sum", "res", "pad", "checkOpts", "defaults", "opts", "aobject", "createHasher", "hashCons", "info", "hashC", "msg", "tmp", "randomBytes", "bytesLength", "cr", "isLE", "swap32IfBE", "oidNist", "init_utils", "__esmMin", "label", "u", "_", "suffix", "fromBig", "n", "le", "U32_MASK64", "_32n", "split", "lst", "len", "Ah", "Al", "i", "h", "l", "setU64FromNum", "view", "byteOffset", "isLE", "fromNumH", "fromNumL", "add", "Bh", "Bl", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add3L", "add3H", "add4L", "add4H", "add5L", "add5H", "init_u64", "__esmMin", "_l", "s", "Cl", "low", "Ch", "Dl", "Dh", "El", "Eh", "keccakP", "s", "rounds", "anumber", "round", "x", "B", "idx1", "idx0", "B0", "B1", "Th", "rotlH", "Tl", "rotlL", "y", "curH", "curL", "t", "shift", "SHA3_ROTL", "PI", "SHA3_PI", "b0", "b1", "b2", "b3", "SHA3_IOTA_H", "SHA3_IOTA_L", "clean", "_0n", "_1n", "_2n", "_7n", "_256n", "_0x71n", "_SHA3_IOTA", "IOTAS", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "Keccak", "genKeccak", "sha3_256", "genShake", "shake128", "shake256", "init_sha3", "__esmMin", "init_u64", "init_utils", "R", "j", "split", "h", "l", "_Keccak", "blockLen", "suffix", "outputLen", "enableXOF", "__publicField", "abool", "u32", "swap32IfBE", "data", "aexists", "abytes", "state", "state32", "len", "canUseU32", "blockLen32", "data32", "pos", "i", "o", "take", "out", "bufferOut", "bytes", "aoutput", "to", "info", "createHasher", "oidNist", "opts", "checkOpts", "aarray", "item", "title", "inner", "i", "astring", "value", "prefix", "aobject", "afunction", "abool", "atitle", "abignumber", "n", "isPosBig", "anumber", "asafenumber", "numberToHexUnpadded", "num", "hex", "hexToNumber", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "copyBytes", "abytes", "numberToBytesBE", "len", "expectedLen", "hexToBytes", "numberToBytesLE", "inRange", "min", "max", "aInRange", "bitLen", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "u8n", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "reset", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "label", "val", "current", "iter", "f", "isBytes", "randomBytes", "_1n", "bitMask", "init_utils", "__esmMin", "length", "arrays", "bytesLength", "mod", "a", "b", "_0n", "result", "pow", "num", "power", "modulo", "_1n", "d", "POW_WINDOWED_MIN", "p", "digits", "_15n", "_4n", "table", "i", "w", "digit", "pow2", "x", "res", "invert", "number", "u", "q", "r", "m", "invertCt", "prime", "an", "inverse", "_2n", "assertIsSquare", "Fp", "root", "n", "F", "aoddModulus", "order", "fnName", "sqrt3mod4", "p1div4", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "v", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "t_tmp", "exponent", "FpSqrt", "_9n", "validateField", "field", "aobject", "asafenumber", "name", "FIELD_FIELDS", "afunction", "FpInvertBatch", "nums", "passZero", "aarray", "abool", "inverted", "multipliedAcc", "acc", "invertedAcc", "p1mod2", "powered", "yes", "zero", "no", "nLength", "nBitLength", "anumber", "bits", "bitLen", "_nBitLength", "nByteLength", "ORDER", "opts", "_Field", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "bytesToNumberLE", "bytesToNumberBE", "reduced", "numberToBytesLE", "numberToBytesBE", "FIELD_SQRT", "init_modular", "__esmMin", "init_utils", "__publicField", "_nbitLength", "lhs", "rhs", "sqrt", "bytes", "skipValidation", "allowedLengths", "BYTES", "modFromBytes", "padded", "scalar", "lst", "condition", "checkU32", "n", "title", "isPowerOfTwo", "x", "reverseBits", "bits", "reversed", "i", "log2", "bitReversalInplace", "values", "j", "tmp", "FFTCore", "init_fft", "__esmMin", "init_utils", "F", "coreOpts", "validateObject", "N", "roots", "dit", "invertButterflies", "skipStages", "brp", "maxSkipStages", "isDit", "g", "s", "m", "m2", "stride", "k", "grp", "rootPos", "i0", "i1", "omega", "b", "a", "t", "aarray", "item", "title", "inner", "i", "aobject", "value", "equalBytes", "a", "b", "abytes", "diff", "validateOpts", "opts", "isBytes", "validateVerOpts", "validateSigOpts", "splitCoder", "label", "lengths", "getLength", "c", "bytesLen", "sum", "bufs", "res", "pos", "l", "buf", "vecCoder", "vecLen", "coder", "u", "uArr", "r", "cleanBytes", "list", "t", "getMask", "bits", "anumber", "getMessage", "msg", "ctx", "EMPTY", "concatBytes", "checkHash", "hash", "requiredStrength", "ahash", "oid", "oidNistP", "collisionResistance", "getMessagePrehash", "hashed", "abytesDoc", "randomBytes", "init_utils", "__esmMin", "genCrystals", "createXofShake", "XOF128", "XOF256", "init_crystals", "__esmMin", "init_fft", "init_sha3", "init_utils", "opts", "newPoly", "N", "Q", "F", "ROOT_OF_UNITY", "brvBits", "isKyber", "mod", "a", "modulo", "result", "smod", "r", "getZettas", "out", "i", "b", "reverseBits", "p", "nttZetas", "inv", "_a", "field", "nttOpts", "dif", "FFTCore", "dit", "NTT", "d", "c", "bufLen", "getMask", "mask", "bytesLen", "poly_", "poly", "buf", "pos", "bytes", "shake", "seed", "blockLen", "_seed", "seedLen", "h", "calls", "xofs", "x", "y", "cleanBytes", "shake128", "shake256", "ml_dsa_exports", "__export", "PARAMS", "ml_dsa44", "ml_dsa65", "ml_dsa87", "validateInternalOpts", "opts", "validateOpts", "abool", "RejNTTPoly", "xof_", "xof", "newPoly", "N", "j", "b", "i", "t", "Q", "getDilithium", "opts_", "K", "L", "GAMMA1", "GAMMA2", "TAU", "ETA", "OMEGA", "CRH_BYTES", "TR_BYTES", "C_TILDE_BYTES", "XOF128", "XOF256", "securityLevel", "GAMMA2_1", "GAMMA2_2", "BETA", "decompose", "r", "rPlus", "crystals", "r0", "HighBits", "LowBits", "MakeHint", "z", "HINT_M", "UseHint", "h", "r1", "Power2Round", "D", "hintCoder", "h_", "res", "k", "buf", "hi", "ETACoder", "polyCoder", "T0Coder", "T1Coder", "ZCoder", "W1Coder", "W1Vec", "vecCoder", "publicCoder", "splitCoder", "secretCoder", "sigCoder", "CoefFromHalfByte", "n", "RejBoundedPoly", "d1", "d2", "SampleInBall", "seed", "pre", "s", "shake256", "masks", "pos", "maskPos", "maskBit", "polyPowerRound", "p_", "p", "res0", "res1", "polyUseHint", "u_", "u", "polyMakeHint", "a_", "b_", "a", "v", "cnt", "signRandBytes", "seedCoder", "internal", "seedDst", "randSeed", "randomBytes", "abytesDoc", "cleanBytes", "rho", "rhoPrime", "K_", "xofPrime", "s1", "s2", "s1Hat", "t0", "t1", "aij", "polyAdd", "MultiplyNTTs", "publicKey", "tr", "secretKey", "_K", "_tr", "_t0", "tmp", "msg", "validateSigOpts", "random", "externalMu", "ownRnd", "rnd", "decoded", "error", "A", "pv", "mu", "rhoprime", "x256", "main_loop", "kappa", "y", "w", "wi", "w1", "cTilde", "cHat", "cs1", "polyChknorm", "cs2", "polySub", "ct0", "hint", "sig", "c", "zNtt", "wTick1", "ct12d", "polyShiftl", "Az", "wApprox", "c2", "acc", "equalBytes", "M", "getMessage", "validateVerOpts", "hash", "checkHash", "rawHash", "getMessagePrehash", "ROOT_OF_UNITY", "F", "id", "init_ml_dsa", "__esmMin", "init_utils", "init_sha3", "init_crystals", "genCrystals", "d", "compress", "verify", "B", "browser_exports", "__export", "InMemoryKeyStorage", "KeyRegistry", "createKeySDK", "browser_default", "secp256k1_CURVE", "P", "N", "Gx", "Gy", "_b", "L", "L2", "lengths", "err", "message", "E", "e", "captureStackTrace", "isBytes", "a", "abytes", "value", "length", "title", "bytes", "len", "needsLen", "prefix", "ofLen", "got", "msg", "u8n", "padh", "n", "pad", "bytesToHex", "b", "hex", "C", "_ch", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "subtle", "concatBytes", "arrs", "randomBytes", "big", "arange", "min", "max", "M", "modN", "invert", "num", "md", "x", "y", "u", "v", "q", "r", "m", "callHash", "name", "fn", "hashes", "gh", "gha", "apoint", "p", "Point", "err", "koblitz", "x", "M", "_b", "FpIsValid", "n", "arange", "P", "FpIsValidNot0", "FnIsValidNot0", "N", "isEven", "y", "u8of", "getPrefix", "lift_x", "c", "num", "e", "_Point", "X", "Y", "Z", "__publicField", "FpIsValid", "FpIsValidNot0", "secp256k1_CURVE", "ap", "x", "y", "I", "bytes", "abytes", "comp", "uncomp", "lengths", "p", "length", "head", "tail", "sliceBytesNumBE", "L", "lift_x", "M", "L2", "err", "hex", "hexToBytes", "other", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "apoint", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "a", "b", "_b", "X3", "Y3", "Z3", "b3", "t0", "t1", "t2", "t3", "t4", "t5", "n", "safe", "FnIsValidNot0", "G", "wNAF", "f", "d", "scalar", "z", "iz", "invert", "P", "koblitz", "isCompressed", "x32b", "numTo32b", "concatBytes", "getPrefix", "u8of", "bytesToHex", "Point", "Gx", "Gy", "doubleScalarMulUns", "R", "u1", "u2", "bytesToNumBE", "big", "from", "to", "B256", "num", "padh", "arange", "secretKeyToScalar", "secretKey", "N", "highS", "getPublicKey", "privKey", "isValidSecretKey", "isValidPublicKey", "publicKey", "publicKeyUncompressed", "l", "assertRecoveryBit", "recovery", "assertSigFormat", "format", "SIG_DER", "SIG_COMPACT", "SIG_RECOVERED", "assertSigLength", "sig", "len", "Signature", "_Signature", "r", "s", "rec", "bit", "res", "bits2int", "delta", "bits2int_modN", "modN", "_sha", "hashes", "key", "message", "subtle", "name", "k", "u8n", "msg", "prepMsg", "opts", "async_", "gha", "gh", "NULL", "byte0", "byte1", "_maxDrbgIters", "_drbgErr", "hmacDrbg", "seed", "pred", "v", "i", "reset", "h", "reseed", "gen", "_sign", "messageHash", "secretKey", "opts", "hmacDrbg", "lowS", "extraEntropy", "int2octets", "numTo32b", "h1i", "bits2int_modN", "h1o", "d", "secretKeyToScalar", "seedArgs", "e", "randomBytes", "L", "abytes", "seed", "concatBytes", "m", "kBytes", "k", "bits2int", "N", "ik", "invert", "q", "G", "r", "modN", "s", "recovery", "normS", "highS", "Signature", "_verify", "sig", "publicKey", "format", "err", "assertSigLength", "h", "P", "Point", "is", "u1", "u2", "R", "doubleScalarMulUns", "setDefaults", "SIG_COMPACT", "sign", "message", "assertSigFormat", "msg", "prepMsg", "verify", "signature", "message", "publicKey", "opts", "setDefaults", "msg", "prepMsg", "_verify", "randomSecretKey", "seed", "randomBytes", "lengths", "abytes", "err", "num", "M", "bytesToNumBE", "N", "numTo32b", "utils", "isValidSecretKey", "isValidPublicKey", "randomSecretKey", "W", "scalarBits", "pwindows", "pwindowSize", "precompute", "points", "p", "G", "b", "w", "i", "Gpows", "ctneg", "cnd", "n", "wNAF", "comp", "I", "f", "pow_2_w", "maxNum", "mask", "big", "shiftBy", "wbits", "off", "offF", "offP", "isEven", "isNeg", "err", "init_utils", "_HMAC", "hash", "key", "__publicField", "ahash", "abytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "aoutput", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "canXOF", "hmac", "hmac_", "message", "init_u64", "init_utils", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "__publicField", "createView", "data", "aexists", "abytes", "view", "buffer", "len", "processed", "pos", "take", "dataView", "out", "aoutput", "setU64FromNum", "oview", "outLen", "state", "i", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA512_IV", "init_u64", "init_utils", "SHA256_K", "SHA256_W", "SHA2_32B", "HashMD", "outputLen", "IV", "__publicField", "A", "B", "C", "D", "E", "F", "G", "H", "to", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "IV", "__publicField", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "to", "view", "offset", "i", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "clean", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "init_sha3", "bytesToHex", "bytes", "b", "hexToBytes", "hex", "i", "hashBytes", "bytes", "algorithm", "sha256", "sha512", "sha3_256", "init_utils", "init_modular", "_0n", "_1n", "_4n", "BLIND_BYTES", "BLIND_BITS", "FW_WINDOW", "TABLE_BYTES_MAX", "validatePointCons", "Point", "pc", "afunction", "aobject", "validateField", "normalizeZ", "c", "points", "validateMSMPoints", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "min", "validateTableBytes", "numPoints", "fpBytes", "bytes", "probeRandomBytes", "randomBytes", "length", "probe", "isBytes", "aarray", "validateMSMScalars", "scalars", "field", "maxScalar", "s", "isPosBig", "pointWindowSizes", "getWindowSize", "P", "oddMultiples", "size", "dbl", "t", "j", "wnafDigits", "n", "half", "mask", "d", "w", "signedWindowDigits", "windows", "shiftBy", "v", "wnafWalk", "zero", "tables", "digits", "max", "acc", "bit", "item", "ScalarMultiplier", "__publicField", "point", "comp", "base", "precomputes", "digit", "start", "idx", "sel", "neg", "transform", "entries", "entry", "scalar", "inRange", "blind", "bytesToNumberBE", "bitMask", "table", "window", "cofactor", "mulAddUnsafe", "allowOversized", "abool", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "validateObject", "p", "val", "isPosBig", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "init_modular", "init_utils", "init_utils", "_0n", "DERErr", "m", "_DER", "tag", "data", "E", "asafenumber", "astring", "dataLen", "len", "numberToHexUnpadded", "lenLen", "abytes", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "num", "abignumber", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "validateObject", "rs", "ss", "seq", "DER", "init_modular", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "aInRange", "_0n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "validateObject", "optsn", "optName", "abool", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "endo", "allowInfinityPoint", "randomBytes", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "bytes", "abytes", "comp", "uncomp", "length", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "b3", "mulA", "_", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "pushWnafPair", "points", "scalars", "p", "psi", "validityCache", "_Point", "X", "Y", "Z", "__publicField", "P", "hex", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "f", "normalize", "sc", "mulAddUnsafe", "a", "b", "invertedZ", "iz", "is0", "zz", "isTorsionFree", "clearCofactor", "bytesToHex", "normalizeZ", "ScalarMultiplier", "ecdh", "ecdhOpts", "validatePointCons", "randomBytes_", "getMinHashLength", "isValidSecretKey", "secretKey", "isValidPublicKey", "publicKey", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "getPublicKey", "isProbPub", "item", "allowedLengths", "isBytes", "isPub", "isSec", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "hash_", "ahash", "hmac", "key", "msg", "fnBits", "blindLength", "csprng", "probeRandomBytes", "defaultSigOpts", "hasLargeRecoveryLifts", "isBiggerThanHalfOrder", "number", "HALF", "validateRS", "assertFieldSignIsSupported", "getRecoveryBit", "r", "assertRecoverableCurve", "validateSigLength", "size", "sizer", "Signature", "recovery", "recid", "DER", "messageHash", "radj", "R", "ir", "h", "bits2int_modN", "u1", "u2", "Q", "rb", "sb", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "int2octets", "validateMsgAndHash", "message", "prehash", "prepSig", "lowS", "extraEntropy", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "q", "ibk", "bm", "bd", "ik", "invertCt", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "init_utils", "Rho160", "Id160", "_", "i", "Pi160", "idxLR", "res", "j", "k", "idxL", "idxR", "shifts160", "shiftsL160", "idx", "shiftsR160", "Kl160", "Kr160", "ripemd_f", "group", "x", "y", "z", "BUF_160", "_RIPEMD160", "HashMD", "__publicField", "h0", "h1", "h2", "h3", "h4", "to", "view", "offset", "al", "ar", "bl", "br", "cl", "cr", "dl", "dr", "el", "er", "rGroup", "hbl", "hbr", "rl", "rr", "sl", "sr", "tl", "rotl", "tr", "clean", "ripemd160", "createHasher", "init_utils", "freeze", "fn", "isBytes", "a", "abytes", "b", "afn", "input", "astr", "label", "anumber", "n", "title", "chain", "args", "id", "a", "wrap", "b", "c", "encode", "x", "decode", "asciiDecoder", "decoder", "B2S_CHUNK", "charcodesToString", "codes", "len", "res", "i", "alphabet", "letters", "aliases", "len", "encTable", "decTable", "i", "code", "alias", "target", "digits", "codes", "d", "charcodesToString", "input", "astr", "slen", "digit", "checksum", "len", "fn", "anumber", "afn", "_fn", "data", "abytes", "sum", "res", "payload", "oldChecksum", "newChecksum", "i", "B58_GROUP", "radix58", "bytes", "abytes", "blen", "zeros", "nlimbs", "limbs", "odd", "i", "j", "groups", "pos", "carry", "cur", "q", "top", "sig", "v", "res", "g", "k", "digits", "dlen", "used", "group", "gval", "factor", "end", "d", "valueBytes", "limb", "genBase58", "abc", "chain", "alphabet", "base58", "freeze", "createBase58check", "sha256", "afn", "_sha256", "chain", "checksum", "data", "base58", "Point", "secp256k1", "Fn", "base58check", "createBase58check", "sha256", "MASTER_SECRET", "char", "BITCOIN_VERSIONS", "HARDENED_OFFSET", "hash160", "data", "ripemd160", "fromU32", "createView", "toU32", "n", "title", "buf", "validateVersions", "versions", "HDKey", "_HDKey", "opt", "__publicField", "priv", "concatBytes", "seed", "abytes", "I", "hmac", "sha512", "privateKey", "chainCode", "base58key", "keyBuffer", "keyView", "version", "key", "isPriv", "json", "path", "parts", "child", "c", "m", "m1", "idx", "index", "_I", "out", "childTweak", "ctweak", "added", "point", "hash", "signature", "init_utils", "pbkdf2Init", "hash", "_password", "_salt", "_opts", "ahash", "opts", "checkOpts", "c", "dkLen", "asyncTick", "anumber", "p", "kdfInputToBytes", "s", "DK", "iHash", "oHash", "outputLen", "hmac", "u", "eng", "pbkdf2Engine", "salt", "counter", "view", "createView", "salted", "work", "iClone", "oClone", "ti", "Ti", "ui", "i", "clean", "pbkdf2", "password", "pos", "init_utils", "isJapanese", "wordlist", "nfkd", "str", "normalize", "norm", "words", "aentropy", "ent", "abytes", "generateMnemonic", "strength", "anumber", "entropyToMnemonic", "randomBytes", "calcChecksum", "entropy", "bitsLeft", "sha256", "awordlist", "i", "encodeWords", "bytes", "carry", "bits", "byte", "decodeWords", "entLen", "pos", "word", "index", "mnemonicToEntropy", "mnemonic", "validateMnemonic", "psalt", "passphrase", "mnemonicToSeedSync", "mnemonic", "passphrase", "pbkdf2", "sha512", "normalize", "psalt", "wordlist", "BIP32Derivation", "context", "childKey", "HDKey", "error", "mnemonic", "passphrase", "validateMnemonic", "wordlist", "mnemonicToSeedSync", "strength", "generateMnemonic", "account", "change", "index", "coinType", "name", "v", "BASE58_ALPHABET", "base58Encode", "data", "num", "byte", "encoded", "remainder", "base58Decode", "str", "char", "index", "bytes", "encodeWIF", "privateKey", "compressed", "network", "version", "payload", "hash1", "sha256", "checksum", "decodeWIF", "wif", "expectedChecksum", "i", "hashes", "msg", "sha256", "key", "hmac", "assertValidSecretKey", "bytes", "utils", "BsvEcdsaSuite", "__publicField", "BIP32Derivation", "privateKey", "publicKey", "getPublicKey", "message", "sign", "error", "signature", "verify", "pub", "bytesToHex", "encoded", "hexToBytes", "priv", "encodeWIF", "decodeWIF", "ml_dsa44_lib", "ml_dsa65_lib", "ml_dsa87_lib", "getMlDsa44", "getMlDsa65", "getMlDsa87", "ML_DSA_SIZES", "BaseMlDsaSuite", "__publicField", "keypair", "error", "privateKey", "message", "publicKey", "signature", "lib", "pub", "bytesToHex", "encoded", "bytes", "hexToBytes", "priv", "MlDsa44Suite", "MlDsa65Suite", "MlDsa87Suite", "SignatureSuiteRegistry", "__publicField", "suite", "suiteId", "globalRegistry", "BsvEcdsaSuite", "MlDsa44Suite", "MlDsa65Suite", "MlDsa87Suite", "SmartLedgerCryptoError", "message", "code", "__publicField", "KeyNotFoundError", "keyId", "KeyAlreadyExistsError", "KeyExpiredError", "expiresAt", "KeyInvalidStateError", "currentState", "requiredState", "InvalidKeyParametersError", "SmartLedgerCryptoError", "message", "agentIdOfKey", "keyId", "i", "cloneKeyMeta", "meta", "cloneKeypair", "keypair", "isKeyUsable", "now", "expires", "assertKeyUsable", "KeyInvalidStateError", "KeyExpiredError", "assertValidExpiry", "expiresAt", "InvalidKeyParametersError", "InMemoryKeyStorage", "__publicField", "found", "filter", "allMeta", "k", "key", "value", "u", "updates", "existing", "KeyNotFoundError", "KeyRegistry", "storage", "suiteId", "options", "KeyAlreadyExistsError", "result", "allKeys", "oldKeyId", "newKeyId", "newKeypair", "oldKey", "lifetime", "newMeta", "error", "reason", "count", "retentionDays", "cutoffDate", "COUNTER_SUFFIX", "MAX_KEY_ID_ATTEMPTS", "assertAgentId", "agentId", "toRecord", "meta", "publicKey", "cloneKeyMeta", "statusAllows", "policy", "isKeyUsable", "DefaultKeySDK", "config", "profile", "options", "suite", "keypair", "available", "keyId", "result", "message", "assertKeyUsable", "u", "hashAlg", "messageHash", "hashBytes", "signature", "activeOnly", "agentKeys", "agentIdOfKey", "records", "keys", "sorted", "suites", "k", "suiteArray", "derivedPolicy", "activeKeys", "toRotate", "keyRecord", "replacements", "newKeys", "i", "newKeypair", "newMeta", "newKeyId", "slot", "pending", "record", "work", "primaryKey", "secondaryKey", "suitesToUse", "signatures", "suiteId", "key", "keyStatus", "requiredSuites", "refuse", "error", "results", "s", "r", "entry", "fail", "missingSuites", "required", "everySuppliedValid", "strength", "BIP32Derivation", "mnemonic", "path", "passphrase", "seed", "caps", "capability", "derivationPath", "accountIndex", "addressIndex", "isChange", "register", "suiteName", "attempt", "counter", "KeyAlreadyExistsError", "initPromise", "max", "acc", "local", "match", "num", "pendingInit", "next", "a", "b", "aTime", "bTime", "priorityDiff", "createKeySDK", "config", "keyRegistry", "KeyRegistry", "InMemoryKeyStorage", "DefaultKeySDK", "globalRegistry", "browser_default"]
|
|
4
|
+
"sourcesContent": ["/**\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) {\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 (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// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\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, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\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(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\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) {\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));\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) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash 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 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\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, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\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, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\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) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\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) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\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) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\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) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\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, shift) {\n return (word << (32 - shift)) | (word >>> shift);\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, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\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) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\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 = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\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) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\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 = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\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) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n 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// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\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) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n 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)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\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 () => { };\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 * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\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(iters, tick, cb) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\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)\n continue;\n await nextTick();\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts += diff;\n }\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) {\n if (typeof str !== 'string')\n throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\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, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\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) {\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/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\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(defaults, opts, title = 'opts') {\n aobject(defaults, 'defaults');\n if (opts !== undefined)\n aobject(opts, title);\n const merged = Object.assign(defaults, opts);\n return merged;\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 * @throws On wrong argument types. {@link TypeError}\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(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(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) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\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) {\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.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.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 * 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) => ({\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", "const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n", "/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { split } from \"./_u64.js\";\n// prettier-ignore\nimport { abool, abytes, aexists, anumber, aoutput, checkOpts, clean, createHasher, oidNist, swap32IfBE, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// 64-bit left rotates as u32 pairs. Inlined here (not imported from _u64) so V8 can\n// inline them into keccakP \u2014 the import path costs ~24% on sha3_256. SHA3 is the only\n// consumer of left-rotates; other hashes use right-rotates from _u64.\n// Valid for s in 1..31 (SH/SL) and 33..63 (BH/BL); keccak never rotates by 0/32/64.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Reused Theta scratch buffer (column parities), same pattern as SHA256_W in sha2.\n// keccakP never calls user code, so the shared buffer cannot be observed mid-permutation.\nconst B = new Uint32Array(5 * 2);\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s, rounds = 24) {\n if (!(s instanceof Uint32Array))\n throw new TypeError('\"s\" expected Uint32Array(50), got type=' + typeof s);\n if (s.length !== 50)\n throw new RangeError('\"s\" expected Uint32Array(50), got length=' + s.length);\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24)\n throw new Error('\"rounds\" expected integer 1..24');\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta \u03B8\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (\u03C1) and Pi (\u03C0)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (\u03C7)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (\u03B9)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak {\n state;\n pos = 0;\n posOut = 0;\n finished = false;\n state32;\n destroyed = false;\n blockLen;\n suffix;\n outputLen;\n canXOF;\n enableXOF = false;\n rounds;\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n anumber(blockLen, 'blockLen');\n anumber(suffix, 'suffix');\n anumber(rounds, 'rounds');\n abool(enableXOF, 'enableXOF');\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // Only keccak-f1600 is supported: 1600 bits (5x5 matrix of 64bit) === 200 bytes of state.\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('\"blockLen\" must be 1..199');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { blockLen, state, state32 } = this;\n const len = data.length;\n // Absorb full blocks with u32 XORs when both sides are 4-byte aligned.\n // XOR of same-position words equals XOR of same-position bytes, so this is endianness-safe.\n const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;\n const blockLen32 = blockLen / 4;\n const data32 = canUseU32 && len >= blockLen ? u32(data) : undefined;\n for (let pos = 0; pos < len;) {\n if (data32 !== undefined && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {\n for (let i = 0, o = pos / 4; i < blockLen32; i++)\n state32[i] ^= data32[o + i];\n pos += blockLen;\n // Subclasses (_KeccakPRG) read `this.pos` inside their `keccak()` override,\n // so it must reflect the fully-absorbed block before the permutation fires.\n this.pos = blockLen;\n this.keccak();\n continue;\n }\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF)\n throw new Error('XOF is not enabled');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out;\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n // Sponge padding and XOF output are positional, so both offsets are part of the clone state.\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, \n/* @__PURE__ */ oidNist(0x07));\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => {\n opts = checkOpts({}, opts);\n return new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true);\n}, info);\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\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 = (value, length, title) => abytes_(value, length, title);\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 * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\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 = 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) => concatBytes_(...arrays);\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) => hexToBytes_(hex);\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 = 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) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\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, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\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(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return 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, title = '') {\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 * 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) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\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) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\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) {\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) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\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 * @throws If a documented runtime validation or state check fails. {@link Error}\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, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\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 > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\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 * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\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) {\n return hexToBytes_(numberToHexUnpadded(abignumber(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, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\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) {\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));\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) {\n if (typeof ascii !== 'string')\n 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(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return 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, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\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, n, min, max) {\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// Bit operations\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) {\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)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\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, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\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, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\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 * 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) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\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 hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\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 = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = 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) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = 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)\n 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)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\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, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\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 * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\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(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\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 = () => {\n throw new Error('not implemented');\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 { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\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 _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\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, b) {\n if (b <= _0n)\n 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, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` \u2014 invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\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, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n 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 * 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 - Modulus greater than 1.\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, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the B\u00E9zout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) \u2261 a\u207B\u00B9 (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time \u2014 JS bigint\n * multiplication/reduction is still value-dependent \u2014 and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 \u2261 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions \u2014 (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 \u2014 truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\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// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\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 ((Fp, n) => {\n const F = Fp;\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 });\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) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\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 // 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)\n 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)\n return sqrt3mod4;\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(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\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 // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) \u2261 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)\n throw new Error('Cannot find square root');\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 // 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 };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 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) {\n aoddModulus(P, 'Fp.sqrt');\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n)\n return sqrt5mod8;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n)\n return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\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, modulo) => (mod(num, modulo) & _1n) === _1n;\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];\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(field) {\n aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\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)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\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(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first \u2014 same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\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))\n 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))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\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(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\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) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the powered value does not match a valid Legendre symbol. {@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(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\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)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\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(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\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, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n 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 nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\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();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\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)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = 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')\n _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')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n 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 create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\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) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\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)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\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, 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('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\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)\n 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) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\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, b, condition) {\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/**\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, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\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(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n 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 * @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(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n 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 * 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) {\n if (typeof fieldOrder !== 'bigint')\n 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)\n 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 * 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) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\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(key, fieldOrder, isLE = false) {\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 // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.\n * API may change at any time. The code has not been audited. Feature requests are welcome.\n * @module\n */\nimport { aarray, validateObject } from \"../utils.js\";\nimport { validateField } from \"./modular.js\";\nfunction checkU32(n, title = 'n') {\n // 0xff_ff_ff_ff\n if (typeof n !== 'number')\n throw new TypeError(`wrong u32 integer \"${title}\": expected number, got type=${typeof n}`);\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new RangeError(`wrong u32 integer \"${title}\": expected 0..4294967295, got ${n}`);\n return n;\n}\n/**\n * Checks if integer is in form of `1 << X`.\n * @param x - Integer to inspect.\n * @returns `true` when the value is a power of two.\n * @example\n * Validate that an FFT size is a power of two.\n *\n * ```ts\n * isPowerOfTwo(8);\n * ```\n */\nexport function isPowerOfTwo(x) {\n checkU32(x, 'x');\n return (x & (x - 1)) === 0 && x !== 0;\n}\n/**\n * @param n - Input value.\n * @returns Next power of two within the u32/array-length domain.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Round an integer up to the FFT size it needs.\n *\n * ```ts\n * nextPowerOfTwo(9);\n * ```\n */\nexport function nextPowerOfTwo(n) {\n checkU32(n);\n if (n <= 1)\n return 1;\n // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:\n // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.\n if (n > 0x8000_0000)\n throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\n/**\n * @param n - Value to reverse.\n * @param bits - Number of bits to use.\n * @returns Bit-reversed integer.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Reverse the low `bits` bits of one index.\n *\n * ```ts\n * reverseBits(3, 3);\n * ```\n */\nexport function reverseBits(n, bits) {\n checkU32(n);\n if (typeof bits !== 'number')\n throw new TypeError('\"bits\" expected number, got type=' + typeof bits);\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);\n let reversed = 0;\n for (let i = 0; i < bits; i++, n >>>= 1)\n reversed = (reversed << 1) | (n & 1);\n // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.\n return reversed >>> 0;\n}\n/**\n * Similar to `bitLen(x)-1` but much faster for small integers, like indices.\n * @param n - Input value.\n * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.\n * @example\n * Compute the radix-2 stage count for one transform size.\n *\n * ```ts\n * log2(8);\n * ```\n */\nexport function log2(n) {\n checkU32(n);\n return 31 - Math.clz32(n);\n}\n/**\n * Moves lowest bit to highest position, which at first step splits\n * array on even and odd indices, then it applied again to each part,\n * which is core of fft\n * @param values - Mutable coefficient array.\n * @returns Mutated input array.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Reorder coefficients into bit-reversed order in place.\n *\n * ```ts\n * const values = Uint8Array.from([0, 1, 2, 3]);\n * bitReversalInplace(values);\n * ```\n */\nexport function bitReversalInplace(values) {\n if (!values ||\n typeof values !== 'object' ||\n typeof values.length !== 'number')\n throw new TypeError('\"values\" expected array-like, got type=' + typeof values);\n const n = values.length;\n // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.\n if (!isPowerOfTwo(n))\n throw new Error('expected positive power-of-two length, got ' + n);\n const bits = log2(n);\n for (let i = 0; i < n; i++) {\n const j = reverseBits(i, bits);\n if (i < j) {\n const tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n }\n return values;\n}\n/**\n * @param values - Input values.\n * @returns Reordered copy.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Return a reordered copy instead of mutating the input in place.\n *\n * ```ts\n * const reordered = bitReversalPermutation([0, 1, 2, 3]);\n * ```\n */\nexport function bitReversalPermutation(values) {\n aarray(values, 'values');\n return bitReversalInplace(values.slice());\n}\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++)\n ;\n return G;\n}\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomial should be rare.\n * @param field - Field implementation.\n * @param generator - Optional trusted non-quadratic-residue override for callers that already know the field.\n * @returns Roots-of-unity cache.\n * @example\n * Cache roots once, then ask for the omega table of one FFT size.\n *\n * ```ts\n * import { rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const roots = rootsOfUnity(Field(17n));\n * const omega = roots.omega(4);\n * ```\n */\nexport function rootsOfUnity(field, generator) {\n validateField(field);\n if (generator !== undefined && typeof generator !== 'bigint')\n throw new TypeError('\"generator\" expected bigint, got type=' + typeof generator);\n // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo\n let oddFactor = field.ORDER - _1n;\n let powerOfTwo = 0;\n for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n)\n ;\n // Find non quadratic residue\n let G = generator !== undefined ? BigInt(generator) : findGenerator(field);\n // Powers of generator\n const omegas = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--)\n omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache = [];\n const checkBits = (bits) => {\n checkU32(bits, 'bits');\n if (bits > 31 || bits > powerOfTwo)\n throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);\n return bits;\n };\n const precomputeRoots = (maxPower) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power])\n continue; // Skip if we've already computed roots for this power\n const above = rootsCache[power + 1];\n const rootsAtPower = [];\n if (above) {\n // \u03C9_{2^p} = \u03C9_{2^{p+1}}\u00B2, so the smaller table is the even-index stride of the bigger\n // one: only the largest requested power pays for the multiplication chain.\n for (let j = 0; j < 2 ** power; j++)\n rootsAtPower.push(above[2 * j]);\n }\n else {\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\n }\n rootsCache[power] = rootsAtPower;\n }\n return rootsCache[maxPower];\n };\n const brpCache = new Map();\n const inverseCache = new Map();\n // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not necessarily isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits) => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits) {\n const b = checkBits(bits);\n if (brpCache.has(b))\n return brpCache.get(b);\n else {\n const res = bitReversalPermutation(this.roots(b));\n brpCache.set(b, res);\n return res;\n }\n },\n inverse(bits) {\n const b = checkBits(bits);\n if (inverseCache.has(b))\n return inverseCache.get(b);\n else {\n // \u03C9\u1D3A = 1, so inv(\u03C9\u1D4F) = \u03C9\u1D3A\u207B\u1D4F: the inverse table is the reversed roots table.\n // Value-identical to field.invertBatch(roots), but skips its 3N muls + inversion.\n const r = this.roots(b);\n const res = [r[0]].concat(r.slice(1).reverse());\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits) => omegas[checkBits(bits)],\n clear: () => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n/**\n * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:\n *\n * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cooley-Tukey\n * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande\n *\n * DIT takes brp input, returns natural output.\n * DIF takes natural input, returns brp output.\n *\n * The output is actually identical. Time / frequence distinction is not meaningful\n * for Polynomial multiplication in fields.\n * Which means if protocol supports/needs brp output/inputs, then we can skip this step.\n *\n * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega\n * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa\n *\n * `invertButterflies` indexes roots by a per-butterfly-group counter (`grp`): forward\n * (`dit: false`) reads `roots[grp]` with grp = 1..; inverse (`dit: true`) reads `roots[N - grp]`\n * with grp restarting at 1. With `skipStages: 0` one table serves both directions (\u03C9\u1D3A = 1 makes\n * the reversed walk self-inverse). With `skipStages > 0` the inverse walk starts at `N - 1`\n * instead of continuing where the skipped stages would have left off, so the caller must supply\n * a table shaped for that (ML-KEM: `\u03B6^BitRev7(i)` over all N=256 indices, whose aliased upper\n * half is exactly the FIPS 203 inverse walk).\n * @param F - Field operations.\n * @param coreOpts - FFT configuration. See {@link FFTCoreOpts}:\n * - `N`: Transform size. Must be a power of two.\n * - `roots`: Stage roots for the selected transform size.\n * - `dit`: Whether to run the DIT variant instead of DIF.\n * - `invertButterflies` (optional): Whether to invert butterfly placement.\n * - `skipStages` (optional): Number of initial stages to skip.\n * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.\n * @returns Low-level FFT loop.\n * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}\n * @example\n * Constructs different flavors of FFT.\n *\n * ```ts\n * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const roots = rootsOfUnity(Fp).roots(2);\n * const loop = FFTCore(Fp, { N: 4, roots, dit: true });\n * const values = loop([1n, 2n, 3n, 4n]);\n * ```\n */\nexport const FFTCore = (F, coreOpts) => {\n validateObject(coreOpts, { N: 'number', roots: 'object', dit: 'boolean' }, { invertButterflies: 'boolean', skipStages: 'number', brp: 'boolean' }, 'coreOpts');\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n checkU32(N, 'coreOpts.N');\n const bits = log2(N);\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n checkU32(skipStages, 'coreOpts.skipStages');\n const maxSkipStages = bits === 0 ? 0 : bits - 1;\n // Skipping every stage leaves only boundary layout changes, not a valid FFT loop shape.\n if (skipStages > maxSkipStages)\n throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);\n // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.\n if (roots.length !== N)\n throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);\n const isDit = dit !== invertButterflies;\n return (values) => {\n if (values.length !== N)\n throw new Error('FFT: wrong Polynomial length');\n if (dit && brp)\n bitReversalInplace(values);\n for (let i = 0, g = 1; i < bits - skipStages; i++) {\n // For each stage s (sub-FFT length m = 2^s)\n const s = dit ? i + 1 + skipStages : bits - i;\n const m = 1 << s;\n const m2 = m >> 1;\n const stride = N >> s;\n // Loop over each subarray of length m\n for (let k = 0; k < N; k += m) {\n // Loop over each butterfly within the subarray\n for (let j = 0, grp = g++; j < m2; j++) {\n const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;\n const i0 = k + j;\n const i1 = k + j + m2;\n const omega = roots[rootPos];\n const b = values[i1];\n const a = values[i0];\n // Inlining gives us 10% perf in kyber vs functions\n if (isDit) {\n const t = F.mul(b, omega); // Standard DIT butterfly\n values[i0] = F.add(a, t);\n values[i1] = F.sub(a, t);\n }\n else if (invertButterflies) {\n values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)\n values[i1] = F.mul(F.sub(b, a), omega);\n }\n else {\n values[i0] = F.add(a, b); // Standard DIF butterfly\n values[i1] = F.mul(F.sub(a, b), omega);\n }\n }\n }\n }\n if (!dit && brp)\n bitReversalInplace(values);\n return values;\n };\n};\n/**\n * NTT aka FFT over finite field (NOT over complex numbers).\n * Naming mirrors other libraries.\n * @param roots - Roots-of-unity cache.\n * @param opts - Field operations. See {@link FFTOpts}.\n * @returns Forward and inverse FFT helpers.\n * @example\n * NTT aka FFT over finite field (NOT over complex numbers).\n *\n * ```ts\n * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const fft = FFT(rootsOfUnity(Fp), Fp);\n * const values = fft.direct([1n, 2n, 3n, 4n]);\n * ```\n */\nexport function FFT(roots, opts) {\n // Loops are cached per (size, direction, brp flags): FFTCore construction validates options\n // and allocates closures, which costs more than a small transform itself. The cached loop\n // closes over the root table active at first use; `roots.clear()` rebuilds value-identical\n // tables, so a stale reference stays correct.\n const loops = new Map();\n const getLoop = (N, rootsTable, key) => {\n const cached = loops.get(key);\n if (cached)\n return cached;\n const brpInput = !!(key & 2);\n const brpOutput = !!(key & 1);\n let loop;\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n const core = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n loop = (values) => core(bitReversalInplace(values));\n }\n else if (brpInput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: false });\n else if (brpOutput)\n loop = FFTCore(opts, { N, roots: rootsTable, dit: false, brp: false });\n else\n loop = FFTCore(opts, { N, roots: rootsTable, dit: true, brp: true }); // all natural\n loops.set(key, loop);\n return loop;\n };\n const loopKey = (bits, isInverse, brpInput, brpOutput) => (bits << 3) | (isInverse ? 4 : 0) | (brpInput ? 2 : 0) | (brpOutput ? 1 : 0);\n return {\n direct(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, false, brpInput, brpOutput);\n return getLoop(N, roots.roots(bits), key)(values.slice());\n },\n inverse(values, brpInput = false, brpOutput = false) {\n const N = values.length;\n if (!isPowerOfTwo(N))\n throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const key = loopKey(bits, true, brpInput, brpOutput);\n const res = getLoop(N, roots.inverse(bits), key)(values.slice());\n const ivm = opts.inv(BigInt(values.length)); // scale\n // we can get brp output if we use dif instead of dit!\n for (let i = 0; i < res.length; i++)\n res[i] = opts.mul(res[i], ivm);\n // Allows to re-use non-inverted roots, but is VERY fragile\n // return [res[0]].concat(res.slice(1).reverse());\n // inverse calculated as pow(-1), which transforms into \u03C9^{-kn} (-> reverses indices)\n return res;\n },\n };\n}\nexport function poly(field, roots, create, fft, length) {\n validateField(field);\n const F = field;\n const _create = create ||\n ((len, elm) => new Array(len).fill(elm ?? F.ZERO));\n // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted\n // polynomial containers concrete instead of trying to support arbitrary wrappers.\n const isPoly = (x) => {\n if (Array.isArray(x))\n return true;\n if (!ArrayBuffer.isView(x))\n return false;\n const v = x;\n return (typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function');\n };\n const checkPoly = (title, value) => {\n if (!isPoly(value))\n throw new TypeError(`\"${title}\" expected polynomial, got type=${typeof value}`);\n };\n const checkLength = (a, b) => {\n checkPoly('a', a);\n const L = a.length;\n if (b !== undefined) {\n checkPoly('b', b);\n if (b.length !== L)\n throw new Error(`poly: mismatched lengths ${L} vs ${b.length}`);\n }\n if (length !== undefined && L !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${L}`);\n return L;\n };\n function findOmegaIndex(x, n, brp = false, weights) {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n // Explicit weights define the interpolation domain, including the Kronecker-\u03B4 shortcut.\n const omega = weights || (brp ? roots.brp(log2(n)) : roots.roots(log2(n)));\n for (let i = 0; i < n; i++)\n if (F.eql(x, omega[i]))\n return i;\n return -1;\n }\n // TODO: mutating versions for mlkem/mldsa\n return {\n roots,\n create: _create,\n length,\n extend: (a, len) => {\n checkLength(a);\n const out = _create(len, F.ZERO);\n // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep\n // `extend()` consistent with typed arrays and with its documented truncate behavior.\n for (let i = 0; i < Math.min(a.length, len); i++)\n out[i] = a[i];\n return out;\n },\n degree: (a) => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--)\n if (!F.is0(a[i]))\n return i;\n return -1;\n },\n add: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a, b) => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++)\n out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a, b) => {\n if (isPoly(b)) {\n const len = checkLength(a, b);\n if (fft) {\n const A = fft.direct(a, false, true);\n const B = fft.direct(b, false, true);\n for (let i = 0; i < A.length; i++)\n A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false);\n }\n else {\n // NOTE: this is quadratic and mostly for compat tests with FFT\n const res = _create(len);\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n const k = (i + j) % len; // wrap mod length\n res[k] = F.add(res[k], F.mul(a[i], b[j]));\n }\n }\n return res;\n }\n }\n else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++)\n out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a, b) {\n checkPoly('a', a);\n checkPoly('b', b);\n const len = nextPowerOfTwo(a.length + b.length - 1);\n return this.mul(this.extend(a, len), this.extend(b, len));\n },\n shift(p, factor) {\n checkPoly('p', p);\n const out = _create(p.length);\n if (length !== undefined && p.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${p.length}`);\n if (!p.length)\n return out;\n out[0] = p[0];\n for (let i = 1, power = F.ONE; i < p.length; i++) {\n power = F.mul(power, factor);\n out[i] = F.mul(p[i], power);\n }\n return out;\n },\n clone: (a) => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++)\n out[i] = a[i];\n return out;\n },\n eval: (a, basis) => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x, n) => {\n const out = _create(n);\n let pow = F.ONE;\n for (let i = 0; i < n; i++) {\n out[i] = pow;\n pow = F.mul(pow, x);\n }\n return out;\n },\n eval: (a, x) => {\n checkLength(a);\n // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way\n let acc = F.ZERO;\n for (let i = a.length - 1; i >= 0; i--)\n acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x, n, brp = false, weights) => {\n if (!isPowerOfTwo(n))\n throw new Error('poly.lagrange: expected power of two length, got ' + n);\n const bits = log2(n);\n const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [\u03C9\u2070, \u03C9\u00B9, ..., \u03C9\u207F\u207B\u00B9]\n const out = _create(n);\n // Fast Kronecker-\u03B4 shortcut\n const idx = findOmegaIndex(x, n, brp, weights);\n if (idx !== -1) {\n out[idx] = F.ONE;\n return out;\n }\n const tm = F.pow(x, BigInt(n));\n const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (x\u207F - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++)\n denom[i] = F.sub(x, cache[i]);\n const inv = F.invertBatch(denom);\n for (let i = 0; i < n; i++)\n out[i] = F.mul(c, F.mul(cache[i], inv[i]));\n return out;\n },\n eval(a, x, brp = false) {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1)\n return a[idx]; // fast path\n const L = this.basis(x, a.length, brp); // L\u1D62(x)\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++)\n if (!F.is0(a[i]))\n acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots) {\n checkPoly('roots', roots);\n if (length !== undefined && roots.length !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${roots.length}`);\n const out = _create(roots.length + 1, F.ZERO);\n out[0] = F.ONE;\n for (const r of roots) {\n const neg = F.neg(r);\n for (let j = out.length - 1; j > 0; j--)\n out[j] = F.add(F.mul(out[j], neg), out[j - 1]);\n out[0] = F.mul(out[0], neg);\n }\n return out;\n },\n };\n}\n", "/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abytes, abytes as abytes_, ahash as ahash_, anumber, concatBytes, isBytes, isLE, randomBytes as randb, } from '@noble/hashes/utils.js';\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes = randb;\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Inputs are validated as byte arrays; unequal lengths return `false` immediately.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes) {\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));\n}\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64(arr) {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If = isLE\n ? (arr) => arr\n : byteSwap64;\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts) {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (isBytes(opts))\n throw new TypeError('\"opts\" expected object, got Uint8Array');\n aobject(opts, 'opts');\n}\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts) {\n validateOpts(opts);\n if (opts.context !== undefined)\n abytes(opts.context, undefined, 'opts.context');\n}\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts) {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder(label, ...lengths) {\n const getLength = (c) => typeof c === 'number' ? c : c.bytesLen;\n const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number')\n b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res;\n },\n };\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder(c, vecLen) {\n const coder = c;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u) => {\n const uArr = aarray(u, 'u');\n if (uArr.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < uArr.length; i++) {\n const b = coder.encode(uArr[i]);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res;\n },\n decode: (a) => {\n abytes_(a, bytesLen);\n const r = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r;\n },\n };\n}\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list) {\n for (const t of list) {\n if (Array.isArray(t))\n for (const b of t)\n b.fill(0);\n else\n t.fill(0);\n }\n}\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits) {\n anumber(bits, 'bits');\n if (bits > 32)\n throw new RangeError('\"bits\" expected <= 32, got ' + bits);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n/** Shared empty byte array used as the default context. */\nexport const EMPTY = /* @__PURE__ */ Uint8Array.of();\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg, ctx = EMPTY) {\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash, requiredStrength = 0) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new TypeError('\"hash\" expected hash function, got type=' + typeof hash);\n ahash_(hash);\n anumber(requiredStrength, 'requiredStrength');\n const oid = hash.oid;\n abytes_(oid, undefined, 'hash.oid');\n if (!equalBytes(oid.subarray(0, 10), oidNistP))\n throw new Error('\"hash.oid\" is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error('Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength);\n }\n}\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(hash, msg, ctx = EMPTY) {\n checkHash(hash);\n abytes_(msg, undefined, 'msg');\n abytes_(ctx, undefined, 'ctx');\n if (ctx.length > 255)\n throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed);\n}\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n", "/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport { cleanBytes, getMask, } from \"./utils.js\";\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = (opts) => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 \u00A72.3 / FIPS 204 \u00A72.3 before downstream mod-q arithmetic.\n const mod = (a, modulo = Q) => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 \u00A77.4 uses the centered `mod \u00B1` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a, modulo = Q) => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 \u00A77.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n const inv = (_a) => {\n throw new Error('not implemented');\n };\n // ML-KEM (Kyber) polynomials always enter the transform reduced to [0, Q), so add/sub only\n // need one conditional correction instead of `%`; measured ~20% faster NTT there.\n // ML-DSA keeps the generic mod() path on purpose: its first forward stage sees centered\n // (negative) coefficients, and `sub(a, t)` can drop below -Q (t is a mul output in [0, Q)),\n // so a single correction is not enough. A guarded fast path with mod() fallback was measured\n // slower than plain `%` for the 23-bit Q (V8 int32 modulo is one div; the branches lose).\n const field = isKyber\n ? {\n add: (a, b) => {\n const r = (a + b) | 0;\n return r >= Q ? (r - Q) | 0 : r;\n },\n sub: (a, b) => {\n const r = (a - b) | 0;\n return r < 0 ? (r + Q) | 0 : r;\n },\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n }\n : {\n add: (a, b) => mod((a | 0) + (b | 0)) | 0,\n sub: (a, b) => mod((a | 0) - (b | 0)) | 0,\n mul: (a, b) => mod((a | 0) * (b | 0)) | 0,\n inv,\n };\n const nttOpts = {\n N,\n roots: nttZetas,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r) => {\n return dif(r);\n },\n decode: (r) => {\n dit(r);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++)\n r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d, c) => {\n // Validate the carry shape once: JS bitwise operations silently truncate wider accumulators.\n for (let i = 0, bufLen = 0; i < N; i++) {\n bufLen += d;\n if (bufLen > 32)\n getMask(bufLen);\n bufLen %= 8;\n }\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_) => {\n const poly = poly_;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n // Take the low byte directly: `& 0xff` matches the previous getMask(bufLen) result\n // after Uint8Array truncation, without a validated function call per output byte.\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8)\n r[pos++] = buf & 0xff;\n }\n return r;\n },\n decode: (bytes) => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d)\n r[pos++] = c.decode(buf & mask);\n }\n return r;\n },\n };\n };\n return {\n mod,\n smod,\n nttZetas: nttZetas,\n NTT: {\n encode: (r) => NTT.encode(r),\n decode: (r) => NTT.decode(r),\n },\n bitsCoder: bitsCoder,\n };\n};\nconst createXofShake = (shake) => (seed, blockLen) => {\n if (!blockLen)\n blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x, y) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf);\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n};\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128 = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256 = /* @__PURE__ */ createXofShake(shake256);\n", "/**\n * ML-DSA: Module Lattice-based Digital Signature Algorithm from\n * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.\n *\n * Has similar internals to ML-KEM, but their keys and params are different.\n * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),\n * [repo](https://github.com/pq-crystals/dilithium).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abool } from '@noble/curves/utils.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport { genCrystals, XOF128, XOF256 } from \"./_crystals.js\";\nimport { abytes, checkHash, cleanBytes, equalBytes, getMessage, getMessagePrehash, randomBytes, splitCoder, validateOpts, validateSigOpts, validateVerOpts, vecCoder, } from \"./utils.js\";\nfunction validateInternalOpts(opts) {\n validateOpts(opts);\n if (opts.externalMu !== undefined)\n abool(opts.externalMu, 'opts.externalMu');\n}\n// Constants\n// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients.\nconst N = 256;\n// 2**23 \u2212 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints\nconst Q = 8380417;\n// FIPS 204 \u00A72.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT.\nconst ROOT_OF_UNITY = 1753;\n// f = 256**\u22121 mod q, pow(256, -1, q) = 8347681 (python3)\nconst F = 8347681;\n// FIPS 204 Table 1 / \u00A77.4 fixes d = 13 dropped low bits for Power2Round on t.\nconst D = 13;\n// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87;\n// \u00A77.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint.\n// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.\nconst GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;\nconst GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;\n/** Internal params for different versions of ML-DSA */\n// prettier-ignore\n/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5`\n * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`.\n * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later,\n * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers.\n */\nexport const PARAMS = /* @__PURE__ */ (() => Object.freeze({\n 2: Object.freeze({\n K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80\n }),\n 3: Object.freeze({\n K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55\n }),\n 5: Object.freeze({\n K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75\n }),\n}))();\nconst newPoly = (n) => new Int32Array(n);\n// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal,\n// and Int32Array polys because ordinary-form coefficients can be negative / centered.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly,\n isKyber: false,\n brvBits: 8,\n});\nconst id = (n) => n;\n// compress()/verify() must be compatible in both directions:\n// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps.\n// malformed-input rejection only happens through the optional verify hook.\nconst polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, {\n encode: (i) => compress(verify(i)),\n decode: (i) => verify(compress(i)),\n});\n// Mutates `a` in place; callers must pass same-length polynomials.\n// NOTE: conditional-reduction variants (as in ml-kem) were measured performance-neutral here \u2014\n// int32 `%` with 23-bit Q is already cheap \u2014 so the simpler mod() form is kept for audit.\nconst polyAdd = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] + b[i]);\n return a;\n};\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polySub = (a_, b_) => {\n const a = a_;\n const b = b_;\n for (let i = 0; i < a.length; i++)\n a[i] = crystals.mod(a[i] - b[i]);\n return a;\n};\n// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.\nconst polyShiftl = (p_) => {\n const p = p_;\n for (let i = 0; i < N; i++)\n p[i] <<= D;\n return p;\n};\nconst polyChknorm = (p_, B) => {\n const p = p_;\n // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.\n for (let i = 0; i < N; i++)\n if (Math.abs(crystals.smod(p[i])) >= B)\n return true;\n return false;\n};\n// Both inputs must already be in NTT / `T_q` form.\nconst MultiplyNTTs = (a_, b_) => {\n const a = a_;\n const b = b_;\n // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,\n // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,\n // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).\n // Barrett reduction is slower than mod :(\n const c = newPoly(N);\n for (let i = 0; i < a.length; i++)\n c[i] = crystals.mod(a[i] * b[i]);\n return c;\n};\n// Return poly in NTT representation\nfunction RejNTTPoly(xof_) {\n const xof = xof_;\n // Samples a polynomial \u2208 Tq. xof() must return byte lengths divisible by 3.\n const r = newPoly(N);\n // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(\n for (let j = 0; j < N;) {\n const b = xof();\n if (b.length % 3)\n throw new Error('RejNTTPoly: unaligned block');\n for (let i = 0; j < N && i <= b.length - 3; i += 3) {\n // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate.\n const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes\n if (t < Q)\n r[j++] = t;\n }\n }\n return r;\n}\n// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the\n// Table 2 byte lengths / hash-width choices used by the public wrappers below.\nfunction getDilithium(opts_) {\n const opts = opts_;\n const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;\n const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;\n if (![2, 4].includes(ETA))\n throw new Error('Wrong ETA');\n if (![1 << 17, 1 << 19].includes(GAMMA1))\n throw new Error('Wrong GAMMA1');\n if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2))\n throw new Error('Wrong GAMMA2');\n const BETA = TAU * ETA;\n const decompose = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1(2\u03B32) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;\n // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`.\n if (rPlus - r0 === Q - 1)\n return { r1: 0 | 0, r0: (r0 - 1) | 0 };\n const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;\n return { r1, r0 }; // r1 = HighBits, r0 = LowBits\n };\n const HighBits = (r) => decompose(r).r1;\n const LowBits = (r) => decompose(r).r0;\n const MakeHint = (z, r) => {\n // Compute hint bit indicating whether adding z to r alters the high bits of r.\n // FIPS 204 \u00A76.2 also permits the Section 5.1 alternative from [6], which uses the\n // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally.\n // This optimized predicate only applies to those transformed Section 5.1 inputs; it is\n // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs.\n // From dilithium code\n const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;\n // from FIPS204:\n // // const r1 = HighBits(r);\n // // const v1 = HighBits(r + z);\n // // const res1 = +(r1 !== v1);\n // But they return different results! However, decompose is same.\n // So, either there is a bug in Dilithium ref implementation or in FIPS204.\n // For now, lets use dilithium one, so test vectors can be passed.\n // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after\n // `r0 += ct0`.\n // See dilithium-py README section \"Optimising decomposition and making hints\".\n return res0;\n };\n // m = (q-1)/(2\u03B32): 44 for ML-DSA-44, 16 for 65/87. Hoisted out of UseHint, which runs\n // per coefficient during verification.\n const HINT_M = Math.floor((Q - 1) / (2 * GAMMA2));\n const UseHint = (h, r) => {\n // Returns the high bits of r adjusted according to hint h\n const { r1, r0 } = decompose(r);\n // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m\n // 4: if h = 1 and r0 \u2264 0 return (r1 \u2212 1) mod m\n if (h === 1)\n return r0 > 0 ? crystals.mod(r1 + 1, HINT_M) | 0 : crystals.mod(r1 - 1, HINT_M) | 0;\n return r1 | 0;\n };\n const Power2Round = (r) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1*(2**d) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 ** D) | 0;\n return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };\n };\n const hintCoder = {\n bytesLen: OMEGA + K,\n encode: (h_) => {\n const h = h_;\n if (h === false)\n throw new Error('hint.encode: hint is false'); // should never happen\n const res = new Uint8Array(OMEGA + K);\n for (let i = 0, k = 0; i < K; i++) {\n for (let j = 0; j < N; j++)\n if (h[i][j] !== 0)\n res[k++] = j;\n res[OMEGA + i] = k;\n }\n return res;\n },\n decode: (buf) => {\n const h = [];\n let k = 0;\n for (let i = 0; i < K; i++) {\n const hi = newPoly(N);\n if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA)\n return false;\n for (let j = k; j < buf[OMEGA + i]; j++) {\n if (j > k && buf[j] <= buf[j - 1])\n return false;\n hi[buf[j]] = 1;\n }\n k = buf[OMEGA + i];\n h.push(hi);\n }\n for (let j = k; j < OMEGA; j++)\n if (buf[j] !== 0)\n return false;\n return h;\n },\n };\n const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => {\n if (!(-ETA <= i && i <= ETA))\n throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);\n return i;\n });\n const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i);\n const T1Coder = polyCoder(10);\n // Requires smod. Need to fix!\n const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i));\n const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);\n const W1Vec = vecCoder(W1Coder, K);\n // Main structures\n const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));\n const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K));\n const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);\n const CoefFromHalfByte = ETA === 2\n ? (n) => (n < 15 ? 2 - (n % 5) : false)\n : (n) => (n < 9 ? 4 - n : false);\n // Return poly in ordinary representation.\n // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply\n // `NTT.encode()` later when needed.\n function RejBoundedPoly(xof_) {\n const xof = xof_;\n // Samples an element a \u2208 Rq with coeffcients in [\u2212\u03B7, \u03B7] computed via rejection sampling from \u03C1.\n const r = newPoly(N);\n for (let j = 0; j < N;) {\n const b = xof();\n for (let i = 0; j < N && i < b.length; i += 1) {\n // half byte. Should be superfast with vector instructions. But very slow with js :(\n const d1 = CoefFromHalfByte(b[i] & 0x0f);\n const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);\n if (d1 !== false)\n r[j++] = d1;\n if (j < N && d2 !== false)\n r[j++] = d2;\n }\n }\n return r;\n }\n const SampleInBall = (seed) => {\n // Samples a polynomial c \u2208 Rq with coeffcients from {\u22121, 0, 1} and Hamming weight \u03C4\n const pre = newPoly(N);\n const s = shake256.create({}).update(seed);\n const buf = new Uint8Array(shake256.blockLen);\n s.xofInto(buf);\n // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`,\n // then rejection-samples coefficient positions from the remaining XOF stream.\n const masks = buf.slice(0, 8);\n for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {\n let b = i + 1;\n for (; b > i;) {\n b = buf[pos++];\n if (pos < shake256.blockLen)\n continue;\n s.xofInto(buf);\n pos = 0;\n }\n pre[i] = pre[b];\n pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);\n if (maskBit >= 8) {\n maskPos++;\n maskBit = 0;\n }\n }\n return pre;\n };\n const polyPowerRound = (p_) => {\n const p = p_;\n const res0 = newPoly(N);\n const res1 = newPoly(N);\n for (let i = 0; i < p.length; i++) {\n const { r0, r1 } = Power2Round(p[i]);\n res0[i] = r0;\n res1[i] = r1;\n }\n return { r0: res0, r1: res1 };\n };\n const polyUseHint = (u_, h_) => {\n const u = u_;\n const h = h_;\n // In-place on `u`: verification only needs the recovered high bits, so reuse the\n // temporary `wApprox` buffer instead of allocating another polynomial.\n for (let i = 0; i < N; i++)\n u[i] = UseHint(h[i], u[i]);\n return u;\n };\n const polyMakeHint = (a_, b_) => {\n const a = a_;\n const b = b_;\n const v = newPoly(N);\n let cnt = 0;\n for (let i = 0; i < N; i++) {\n const h = MakeHint(a[i], b[i]);\n v[i] = h;\n cnt += h;\n }\n return { v, cnt };\n };\n const signRandBytes = 32;\n const seedCoder = splitCoder('seed', 32, 64, 32);\n // API & argument positions are exactly as in FIPS204.\n const internal = Object.freeze({\n info: Object.freeze({ type: 'internal-ml-dsa' }),\n lengths: Object.freeze({\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n seed: 32,\n signature: sigCoder.bytesLen,\n signRand: signRandBytes,\n }),\n keygen: (seed) => {\n // H(\uD835\uDF09||IntegerToBytes(\uD835\uDC58, 1)||IntegerToBytes(\u2113, 1), 128) 2: \u25B7 expand seed\n const seedDst = new Uint8Array(32 + 2);\n const randSeed = seed === undefined;\n if (randSeed)\n seed = randomBytes(32);\n abytes(seed, 32, 'seed');\n seedDst.set(seed);\n if (randSeed)\n cleanBytes(seed);\n seedDst[32] = K;\n seedDst[33] = L;\n const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen }));\n const xofPrime = XOF256(rhoPrime);\n const s1 = [];\n for (let i = 0; i < L; i++)\n s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s2 = [];\n for (let i = L; i < L + K; i++)\n s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));\n const t0 = [];\n const t1 = [];\n const xof = XOF128(rho);\n const t = newPoly(N);\n for (let i = 0; i < K; i++) {\n // t \u2190 NTT\u22121(A*NTT(s1)) + s2\n cleanBytes(t); // don't-reallocate\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // super slow!\n polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));\n }\n crystals.NTT.decode(t);\n const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) \u2190 Power2Round(t, d)\n t0.push(r0);\n t1.push(r1);\n }\n const publicKey = publicCoder.encode([rho, t1]); // pk \u2190 pkEncode(\u03C1, t1)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr \u2190 H(BytesToBits(pk), 512)\n // sk \u2190 skEncode(\u03C1, K,tr, s1, s2, t0)\n const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);\n xof.clean();\n xofPrime.clean();\n // STATS\n // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 },\n // Kyber1024: { calls: 16, xofs: 48 }\n // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 },\n // DSA87: { calls: 71, xofs: 71 }\n cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);\n return {\n publicKey: publicKey,\n secretKey: secretKey,\n };\n },\n getPublicKey: (secretKey) => {\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);\n const xof = XOF128(rho);\n const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));\n const t1 = [];\n const tmp = newPoly(N);\n for (let i = 0; i < K; i++) {\n tmp.fill(0);\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT\n polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j\n }\n crystals.NTT.decode(tmp); // NTT\u207B\u00B9\n polyAdd(tmp, s2[i]); // t_i = A\u00B7s1 + s2\n const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 \u2248 t0\n t1.push(r1);\n }\n xof.clean();\n cleanBytes(tmp, s1Hat, _t0, s1, s2);\n return publicCoder.encode([rho, t1]);\n },\n // NOTE: random is optional.\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n validateInternalOpts(opts);\n const { extraEntropy: random, externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // Prepare entropy before touching decoded secrets: randomBytes() may throw, and an RNG\n // failure must not leave expanded secret-polynomial copies behind.\n const ownRnd = random === false || random === undefined;\n const rnd = random === false\n ? new Uint8Array(32)\n : random === undefined\n ? randomBytes(signRandBytes)\n : random;\n abytes(rnd, 32, 'extraEntropy');\n // This part can be pre-cached per secretKey, but there is only minor performance improvement,\n // since we re-use a lot of variables to computation.\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const decoded = (() => {\n try {\n return secretCoder.decode(secretKey);\n }\n catch (error) {\n // A malformed key must not strand entropy owned by the library.\n if (ownRnd)\n cleanBytes(rnd);\n throw error;\n }\n })();\n const [rho, _K, tr, s1, s2, t0] = decoded;\n // Cache matrix to avoid re-compute later\n const A = []; // A \u2190 ExpandA(\u03C1)\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const pv = [];\n for (let j = 0; j < L; j++)\n pv.push(RejNTTPoly(xof.get(j, i)));\n A.push(pv);\n }\n xof.clean();\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(s1[i]); // s\u02C61 \u2190 NTT(s1)\n for (let i = 0; i < K; i++) {\n crystals.NTT.encode(s2[i]); // s\u02C62 \u2190 NTT(s2)\n crystals.NTT.encode(t0[i]); // t\u02C60 \u2190 NTT(t0)\n }\n // This part is per msg\n const mu = externalMu\n ? msg\n : // 6: \u00B5 \u2190 H(tr||M, 512)\n // \u25B7 Compute message representative \u00B5\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n const rhoprime = shake256\n .create({ dkLen: CRH_BYTES })\n .update(_K)\n .update(rnd)\n .update(mu)\n .digest(); // \u03C1\u2032\u2190 H(K||rnd||\u00B5, 512)\n // Only wipe entropy we generated; caller-provided extraEntropy stays caller-owned.\n if (ownRnd)\n cleanBytes(rnd);\n abytes(rhoprime, CRH_BYTES);\n const x256 = XOF256(rhoprime, ZCoder.bytesLen);\n // Rejection sampling loop\n main_loop: for (let kappa = 0;;) {\n const y = [];\n // y \u2190 ExpandMask(\u03C1 , \u03BA)\n for (let i = 0; i < L; i++, kappa++)\n y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));\n const z = y.map((i) => crystals.NTT.encode(i.slice()));\n const w = [];\n for (let i = 0; i < K; i++) {\n // w \u2190 NTT\u22121(A \u25E6 NTT(y))\n const wi = newPoly(N);\n for (let j = 0; j < L; j++)\n polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));\n crystals.NTT.decode(wi);\n w.push(wi);\n }\n const w1 = w.map((j) => j.map(HighBits)); // w1 \u2190 HighBits(w)\n // Commitment hash: c\u02DC \u2208{0, 1 2\u03BB } \u2190 H(\u00B5||w1Encode(w1), 2\u03BB)\n const cTilde = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(w1))\n .digest();\n // Verifer\u2019s challenge\n // c \u2190 SampleInBall(c\u02DC1); c\u02C6 \u2190 NTT(c)\n const cHat = crystals.NTT.encode(SampleInBall(cTilde));\n // \u27E8\u27E8cs1\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C61)\n const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));\n for (let i = 0; i < L; i++) {\n polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z \u2190 y + \u27E8\u27E8cs1\u27E9\u27E9\n if (polyChknorm(cs1[i], GAMMA1 - BETA))\n continue main_loop; // ||z||\u221E \u2265 \u03B31 \u2212 \u03B2\n }\n // cs1 is now z (\u25B7 Signer\u2019s response)\n let cnt = 0;\n const h = [];\n for (let i = 0; i < K; i++) {\n const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // \u27E8\u27E8cs2\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C62)\n const r0 = polySub(w[i], cs2).map(LowBits); // r0 \u2190 LowBits(w \u2212 \u27E8\u27E8cs2\u27E9\u27E9)\n if (polyChknorm(r0, GAMMA2 - BETA))\n continue main_loop; // ||r0||\u221E \u2265 \u03B32 \u2212 \u03B2\n const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // \u27E8\u27E8ct0\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 t\u02C60)\n if (polyChknorm(ct0, GAMMA2))\n continue main_loop;\n polyAdd(r0, ct0);\n // \u25B7 Signer\u2019s hint\n const hint = polyMakeHint(r0, w1[i]); // h \u2190 MakeHint(\u2212\u27E8\u27E8ct0\u27E9\u27E9, w\u2212 \u27E8\u27E8cs2\u27E9\u27E9 + \u27E8\u27E8ct0\u27E9\u27E9)\n h.push(hint.v);\n cnt += hint.cnt;\n }\n if (cnt > OMEGA)\n continue; // the number of 1\u2019s in h is greater than \u03C9\n x256.clean();\n const res = sigCoder.encode([cTilde, cs1, h]); // \u03C3 \u2190 sigEncode(c\u02DC, z mod\u00B1q, h)\n // rho, _K, tr is subarray of secretKey, cannot clean.\n cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);\n // `externalMu` hands ownership of `mu` to the caller,\n // so only wipe the internally derived digest form here;\n // zeroizing caller memory would break the caller's own reuse / verify path.\n if (!externalMu)\n cleanBytes(mu);\n return res;\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateInternalOpts(opts);\n const { externalMu = false } = opts;\n // FIPS 204 external-mu mode expects the 64-byte message representative \u00B5 = H(tr || M).\n if (externalMu)\n abytes(msg, CRH_BYTES, 'mu');\n // ML-DSA.Verify(pk, M, \u03C3): Verifes a signature \u03C3 for a message M.\n const [rho, t1] = publicCoder.decode(publicKey); // (\u03C1, t1) \u2190 pkDecode(pk)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr \u2190 H(BytesToBits(pk), 512)\n if (sig.length !== sigCoder.bytesLen)\n return false; // return false instead of exception\n // (c\u02DC, z, h) \u2190 sigDecode(\u03C3)\n // \u25B7 Signer\u2019s commitment hash c \u02DC, response z and hint\n const [cTilde, z, h] = sigCoder.decode(sig);\n if (h === false)\n return false; // if h = \u22A5 then return false\n for (let i = 0; i < L; i++)\n if (polyChknorm(z[i], GAMMA1 - BETA))\n return false;\n const mu = externalMu\n ? msg\n : // 7: \u00B5 \u2190 H(tr||M, 512)\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n // Compute verifer\u2019s challenge from c\u02DC\n const c = crystals.NTT.encode(SampleInBall(cTilde)); // c \u2190 SampleInBall(c\u02DC1)\n const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)\n for (let i = 0; i < L; i++)\n crystals.NTT.encode(zNtt[i]);\n const wTick1 = [];\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)\n const Az = newPoly(N); // // A * z\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace\n polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));\n }\n // wApprox = A*z - c*t1 * (2**d)\n const wApprox = crystals.NTT.decode(polySub(Az, ct12d));\n // Reconstruction of signer\u2019s commitment\n wTick1.push(polyUseHint(wApprox, h[i])); // w \u2032 \u2190 UseHint(h, w'approx )\n }\n xof.clean();\n // c\u02DC\u2032\u2190 H (\u00B5||w1Encode(w\u20321), 2\u03BB), Hash it; this should match c\u02DC\n const c2 = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(wTick1))\n .digest();\n // Additional checks in FIPS-204:\n // [[ ||z||\u221E < \u03B31 \u2212 \u03B2 ]] and [[c \u02DC = c\u02DC\u2032]] and [[number of 1\u2019s in h is \u2264 \u03C9]]\n for (const t of h) {\n const sum = t.reduce((acc, i) => acc + i, 0);\n if (!(sum <= OMEGA))\n return false;\n }\n for (const t of z)\n if (polyChknorm(t, GAMMA1 - BETA))\n return false;\n return equalBytes(cTilde, c2);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-dsa' }),\n internal,\n securityLevel: securityLevel,\n keygen: internal.keygen,\n lengths: internal.lengths,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash) => {\n checkHash(hash, securityLevel);\n const rawHash = hash;\n return Object.freeze({\n info: Object.freeze({ type: 'hashml-dsa' }),\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg, secretKey, opts = {}) => {\n validateSigOpts(opts);\n const M = getMessagePrehash(rawHash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res;\n },\n verify: (sig, msg, publicKey, opts = {}) => {\n validateVerOpts(opts);\n abytes(sig, undefined, 'signature');\n return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n/**\n * ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD.\n * @example\n * Generate deterministic ML-DSA-44 keys, sign one message, and verify the signature.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';\n * const seed = new Uint8Array(ml_dsa44.lengths.seed!);\n * const { secretKey, publicKey } = ml_dsa44.keygen(seed);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ml_dsa44.sign(msg, secretKey);\n * const isValid = ml_dsa44.verify(sig, msg, publicKey);\n * const recovered = ml_dsa44.getPublicKey(secretKey);\n * const context = new Uint8Array([1, 2, 3]);\n * const prehash = ml_dsa44.prehash(sha256);\n * const preSig = prehash.sign(msg, secretKey, { context });\n * const preValid = prehash.verify(preSig, msg, publicKey, { context });\n * const internalSig = ml_dsa44.internal.sign(msg, secretKey);\n * ```\n */\nexport const ml_dsa44 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[2],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 32,\n XOF128,\n XOF256,\n securityLevel: 128,\n}))();\n/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa65 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[3],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 48,\n XOF128,\n XOF256,\n securityLevel: 192,\n}))();\n/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */\nexport const ml_dsa87 = /* @__PURE__ */ (() => getDilithium({\n ...PARAMS[5],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 64,\n XOF128,\n XOF256,\n securityLevel: 256,\n}))();\n", "/**\n * Entry point of the browser <script> bundle (dist/lumen-keys(.min).js),\n * which exposes `window.LumenKeys`.\n *\n * Bundlers and Node should import '@smartledger/keys' itself: the ESM build\n * runs unchanged in browsers. This file exists for the script-tag build only.\n */\n\nimport { DefaultKeySDK } from './sdk.js';\nimport { \n InMemoryKeyStorage, \n KeyRegistry,\n globalRegistry,\n} from '@smartledger/crypto';\nimport type { KeySDK } from './types.js';\n\n// Re-export all types for browser usage\nexport * from './types.js';\nexport { InMemoryKeyStorage, KeyRegistry } from '@smartledger/crypto';\n\n/**\n * Creates a new KeySDK instance for browser usage.\n *\n * Async for backward compatibility with earlier bundles; nothing is awaited\n * (the cryptography is pure JavaScript, there is no WASM to initialise).\n * \n * All signature suites (ECDSA, ML-DSA-44, ML-DSA-65, ML-DSA-87) are\n * auto-registered in globalRegistry when @smartledger/crypto loads.\n *\n * Keys live in memory only and are gone when the page unloads.\n */\nexport async function createKeySDK(config?: { keyRegistry?: KeyRegistry }): Promise<KeySDK> {\n const keyRegistry = config?.keyRegistry ?? new KeyRegistry(new InMemoryKeyStorage());\n \n // Use the global registry with auto-registered suites\n // (BsvEcdsaSuite, MlDsa44Suite, MlDsa65Suite, MlDsa87Suite)\n const sdk = new DefaultKeySDK({\n keyRegistry,\n suiteRegistry: globalRegistry,\n });\n \n \n return sdk;\n}\n\n/**\n * Browser-ready default export\n */\nexport default {\n createKeySDK,\n};\n\n// Global export for CDN usage\nif (typeof window !== 'undefined') {\n (window as any).LumenKeys = {\n createKeySDK,\n };\n}\n", "/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 5KB JS implementation of secp256k1 ECDSA / Schnorr signatures & ECDH.\n * Compliant with RFC6979 & BIP340.\n * @module\n */\n/**\n * Curve params from SEC 2 v2 \u00A72.4.1.\n * secp256k1 is a short Weierstrass / Koblitz curve with equation\n * `y\u00B2 == x\u00B3 + ax + b`.\n * * P = `2n**256n - 2n**32n - 977n` // field over which calculations are done\n * * N = `2n**256n - 0x14551231950b75fc4402da1732fc9bebfn` // group order, amount of curve points\n * * h = `1n` // cofactor\n * * a = `0n` // equation param\n * * b = `7n` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n */\n// Mirror noble-curves: Point.CURVE() returns shared params, but those params must stay frozen so\n// callers cannot mutate them out from under the arithmetic constants captured below.\nconst secp256k1_CURVE = Object.freeze({\n p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn,\n n: 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n,\n h: 1n,\n a: 0n,\n b: 7n,\n Gx: 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n,\n Gy: 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n,\n});\nconst { p: P, n: N, Gx, Gy, b: _b } = secp256k1_CURVE;\n// 32-byte field / scalar width, and the SHA-256 / HMAC-DRBG output width used\n// by the RFC6979 paths here.\nconst L = 32;\nconst L2 = 64; // 64-byte compact signatures, and 64 hex chars for zero-padded 32-byte scalars\nconst lengths = {\n publicKey: L + 1,\n publicKeyUncompressed: L2 + 1,\n signature: L2,\n // 48-byte keygen seed floor: 384 bits exceeds FIPS 186-5 Table A.2's\n // 352-bit recommendation for 256-bit prime curves.\n seed: L + L / 2,\n};\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\nconst err = (message = '', E = Error) => {\n const e = new E(message);\n const { captureStackTrace } = Error;\n if (typeof captureStackTrace === 'function')\n captureStackTrace(e, err);\n throw e;\n};\n// Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n// fallback still requires a real ArrayBuffer view so plain JSON-deserialized `{ constructor: ... }`\n// spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\nconst isBytes = (a) => a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n a.BYTES_PER_ELEMENT === 1);\n/** Asserts something is Bytes. */\nconst abytes = (value, length, title = '') => {\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 msg = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n return bytes ? err(msg, RangeError) : err(msg, TypeError);\n }\n return value;\n};\n/** create Uint8Array */\nconst u8n = (len) => new Uint8Array(len);\n// Callers keep values non-negative and within the requested width; padStart() won't truncate over-wide inputs.\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\n/** Render bytes as lowercase hex. */\nconst bytesToHex = (b) => {\n let hex = '';\n for (const e of abytes(b))\n hex += padh(e, 2);\n return hex;\n};\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// prettier-ignore\nconst _ch = (ch) => ch >= C._0 && ch <= C._9 ? ch - C._0 // '2' => 50-48\n : ch >= C.A && ch <= C.F ? ch - (C.A - 10) // 'B' => 66-(65-10)\n : ch >= C.a && ch <= C.f ? ch - (C.a - 10) // 'b' => 98-(97-10)\n : undefined;\nconst hexToBytes = (hex) => {\n const e = 'hex invalid'; // Strict ASCII hex only, with one generic error for type and parse failures.\n if (typeof hex !== 'string')\n return err(e);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n return err(e);\n const array = u8n(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n // treat each char as ASCII\n const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined)\n return err(e);\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n};\n// WebCrypto is available in all modern environments\nconst subtle = () => globalThis?.crypto?.subtle ?? err('crypto.subtle must be defined, consider polyfill');\n// prettier-ignore\nconst concatBytes = (...arrs) => {\n let len = 0;\n for (const a of arrs)\n len += abytes(a).length; // validate every input and sum lengths before copying\n const r = u8n(len);\n let pad = 0; // walk through each array,\n for (const a of arrs)\n r.set(a, pad), pad += a.length; // ensure they have proper type\n return r;\n};\n/**\n * WebCrypto OS-level CSPRNG (random number generator).\n * Will throw when not available; large-request ceilings are delegated to getRandomValues().\n */\nconst randomBytes = (len = L) => (globalThis?.crypto).getRandomValues(u8n(len));\nconst big = BigInt;\nconst arange = (n, min, max, msg = 'bad number: out of range') => {\n if (typeof n !== 'bigint')\n return err(msg, TypeError);\n if (min <= n && n < max)\n return n;\n return err(msg, RangeError);\n};\n/** Canonical modular reduction. Callers must provide a positive modulus. */\nconst M = (a, b = P) => {\n const r = a % b;\n return r >= 0n ? r : b + r;\n};\nconst modN = (a) => M(a, N);\n/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */\n// prettier-ignore\nconst invert = (num, md) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md);\n let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) {\n const q = b / a, r = b % a;\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst callHash = (name) => {\n // @ts-ignore\n const fn = hashes[name];\n if (typeof fn !== 'function')\n err('hashes.' + name + ' not set');\n return fn;\n};\n// All exported provider slots are caller-configurable and may be unset or return arbitrary values,\n// so wrapper helpers must enforce the exact 32-byte digest contract instead of trusting providers.\nconst gh = (name, a, b) => abytes(callHash(name)(a, b), L, 'digest');\nconst gha = (name, a, b) => Promise.resolve(callHash(name)(a, b)).then((r) => abytes(r, L, 'digest'));\n/**\n * SHA-256 helper used by the synchronous API.\n * @param msg - message bytes to hash\n * @returns 32-byte SHA-256 digest.\n * @example\n * Hash message bytes after wiring the synchronous SHA-256 implementation.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * const digest = secp.hash(new Uint8Array([1, 2, 3]));\n * ```\n */\n// Public helper validates the message boundary explicitly; the configured provider is still looked\n// up dynamically and its output is checked with `gh(...)`.\nconst hash = (msg) => gh('sha256', abytes(msg, undefined, 'message'));\n// also rejects structurally similar Point values from other realms / bundled copies\nconst apoint = (p) => (p instanceof Point ? p : err('Point expected'));\n// ## End of Helpers\n// -----------------\n/**\n * secp256k1 formula. Koblitz curves are subclass of weierstrass curves with a=0,\n * making it x\u00B3+b; callers validate x first.\n */\nconst koblitz = (x) => M(M(x * x) * x + _b);\n/** assert is element of field mod P (incl. 0 for projective infinity coordinates) */\nconst FpIsValid = (n) => arange(n, 0n, P);\n/** assert is element of field mod P (excl. 0 where current callers need a non-zero coordinate) */\nconst FpIsValidNot0 = (n) => arange(n, 1n, P);\n/** assert is element of field mod N (excl. 0), matching the shared BIP340 scalar-failure rule used here */\nconst FnIsValidNot0 = (n) => arange(n, 1n, N);\n// Shared parity primitive for BIP340 even-y checks and SEC 1 compressed prefixes.\nconst isEven = (y) => !(y & 1n);\n/** create Uint8Array of byte n */\nconst u8of = (n) => Uint8Array.of(n);\n/** SEC 1 compressed-prefix helper. Parity only: callers validate y before asking for the prefix byte. */\nconst getPrefix = (y) => u8of(isEven(y) ? 0x02 : 0x03);\n/** lift_x from BIP340 returns the unique even square root for x\u00B3+7.\n * SEC 1 callers still flip it for the odd-prefix branch. */\nconst lift_x = (x) => {\n // Let c = x\u00B3 + 7 mod p. Fail if x \u2265 p. (also fail if x < 1)\n const c = koblitz(FpIsValidNot0(x));\n // r = \u221Ac candidate\n // r = c^((p+1)/4) mod p\n // This formula works for fields p = 3 mod 4 -- a special, fast case.\n // Paper: \"Square Roots from 1;24,51,10 to Dan Shanks\".\n let r = 1n;\n for (let num = c, e = (P + 1n) / 4n; e > 0n; e >>= 1n) {\n // powMod: modular exponentiation.\n if (e & 1n)\n r = (r * num) % P; // Uses exponentiation by squaring.\n num = (num * num) % P; // Not constant-time.\n }\n if (M(r * r) !== c)\n err('sqrt invalid'); // check if result is valid\n return isEven(r) ? r : M(-r);\n};\nexport const __TEST = /* @__PURE__ */ Object.freeze({\n // Shared tests expect the BIP340 helper to expose the canonical even-y point, not just the root.\n lift_x: (x) => Point.fromAffine({ x, y: lift_x(x) }),\n extractK: (rand) => extractK(rand),\n});\n/**\n * Point in 3d xyz projective coordinates. 3d takes less inversions than 2d.\n * @param X - X coordinate.\n * @param Y - Y coordinate.\n * @param Z - projective Z coordinate.\n * @example\n * Do point arithmetic with the base point and encode the result as hex.\n * ```ts\n * import { Point } from '@noble/secp256k1';\n * const hex = Point.BASE.double().toHex();\n * ```\n */\nclass Point {\n static BASE;\n static ZERO;\n X;\n Y;\n Z;\n constructor(X, Y, Z) {\n this.X = FpIsValid(X);\n this.Y = FpIsValidNot0(Y); // Y can't be 0 in Projective\n this.Z = FpIsValid(Z);\n Object.freeze(this);\n }\n /** Returns the shared curve metadata object by reference.\n * It is readonly only at type level, and mutating it won't retarget arithmetic,\n * which already uses module-load snapshots. */\n static CURVE() {\n return secp256k1_CURVE;\n }\n /** Create 3d xyz point from 2d xy. (0, 0) => (0, 1, 0), not (0, 0, 1) */\n static fromAffine(ap) {\n const { x, y } = ap;\n return x === 0n && y === 0n ? I : new Point(x, y, 1n);\n }\n /** Convert Uint8Array or hex string to Point. */\n static fromBytes(bytes) {\n abytes(bytes);\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n let p = undefined;\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n const x = sliceBytesNumBE(tail, 0, L);\n // SEC 1 defines the rare infinity encoding 0x00, but SEC 1 public-key validation rejects\n // infinity. We keep 0x00 rejected here because this parser is reused by verify(), ECDH,\n // and public-key validation helpers, so strict handling applies to all callers by default.\n // Local secp256k1 crosstests show OpenSSL raw point codecs accept 0x00 too.\n // Parse SEC 1 compressed/uncompressed encodings, then finish with assertValidity() before returning.\n if (length === comp && (head === 0x02 || head === 0x03)) {\n // Equation is y\u00B2 == x\u00B3 + ax + b. We calculate y from x.\n // lift_x() returns the even root; SEC 1 0x03 still needs the odd root.\n let y = lift_x(x);\n if (head === 0x03)\n y = M(-y);\n p = new Point(x, y, 1n);\n }\n // Uncompressed 65-byte point, 0x04 prefix\n if (length === uncomp && head === 0x04)\n p = new Point(x, sliceBytesNumBE(tail, L, L2), 1n);\n // Validate point\n return p ? p.assertValidity() : err('bad point: not on curve');\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality\n const X1Z2 = M(X1 * Z2);\n const X2Z1 = M(X2 * Z1);\n const Y1Z2 = M(Y1 * Z2);\n const Y2Z1 = M(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(this.X, M(-this.Y), this.Z);\n }\n /** Point doubling: P+P, complete formula. */\n double() {\n return this.add(this);\n }\n /**\n * Point addition: P+Q, complete, exception-free formula\n * (Renes-Costello-Batina, algo 1 of [2015/1060](https://eprint.iacr.org/2015/1060)).\n * Cost: `12M + 0S + 3*a + 3*b3 + 23add`.\n */\n // prettier-ignore\n add(other) {\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = apoint(other);\n const a = 0n;\n const b = _b;\n let X3 = 0n, Y3 = 0n, Z3 = 0n;\n const b3 = M(b * 3n);\n let t0 = M(X1 * X2), t1 = M(Y1 * Y2), t2 = M(Z1 * Z2), t3 = M(X1 + Y1); // step 1\n let t4 = M(X2 + Y2); // step 5\n t3 = M(t3 * t4);\n t4 = M(t0 + t1);\n t3 = M(t3 - t4);\n t4 = M(X1 + Z1);\n let t5 = M(X2 + Z2); // step 10\n t4 = M(t4 * t5);\n t5 = M(t0 + t2);\n t4 = M(t4 - t5);\n t5 = M(Y1 + Z1);\n X3 = M(Y2 + Z2); // step 15\n t5 = M(t5 * X3);\n X3 = M(t1 + t2);\n t5 = M(t5 - X3);\n Z3 = M(a * t4);\n X3 = M(b3 * t2); // step 20\n Z3 = M(X3 + Z3);\n X3 = M(t1 - Z3);\n Z3 = M(t1 + Z3);\n Y3 = M(X3 * Z3);\n t1 = M(t0 + t0); // step 25\n t1 = M(t1 + t0);\n t2 = M(a * t2);\n t4 = M(b3 * t4);\n t1 = M(t1 + t2);\n t2 = M(t0 - t2); // step 30\n t2 = M(a * t2);\n t4 = M(t4 + t2);\n t0 = M(t1 * t4);\n Y3 = M(Y3 + t0);\n t0 = M(t5 * t4); // step 35\n X3 = M(t3 * X3);\n X3 = M(X3 - t0);\n t0 = M(t3 * t1);\n Z3 = M(t5 * Z3);\n Z3 = M(Z3 + t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(apoint(other).negate());\n }\n /**\n * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate leakage shape in JS, not as a hard constant-time guarantee.\n * @param n scalar by which point is multiplied\n * @param safe safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n // Unsafe internal callers may legitimately need 0*P = O during double-scalar multiplication.\n if (!safe && n === 0n)\n return I;\n FnIsValidNot0(n);\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n }\n return p;\n }\n multiplyUnsafe(scalar) {\n return this.multiply(scalar, false);\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) \u220B (x=X/Z, y=Y/Z) */\n toAffine() {\n const { X: x, Y: y, Z: z } = this;\n // fast-paths for ZERO point OR Z=1\n if (this.equals(I))\n return { x: 0n, y: 0n };\n if (z === 1n)\n return { x, y };\n const iz = invert(z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (M(z * iz) !== 1n)\n err('inverse invalid');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: M(x * iz), y: M(y * iz) };\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const { x, y } = this.toAffine(); // convert to 2d xy affine point.\n FpIsValidNot0(x); // must be in range 1 <= x,y < P\n FpIsValidNot0(y);\n // y\u00B2 == x\u00B3 + ax + b, equation sides must be equal\n return M(y * y) === koblitz(x) ? this : err('bad point: not on curve');\n }\n /** Converts point to 33/65-byte Uint8Array. */\n toBytes(isCompressed = true) {\n // Same policy as fromBytes(): SEC 1 has the rare infinity encoding 0x00, but we keep ZERO\n // out of this byte surface because callers treat these encodings as public keys by default.\n const { x, y } = this.assertValidity().toAffine();\n const x32b = numTo32b(x);\n if (isCompressed)\n return concatBytes(getPrefix(y), x32b);\n return concatBytes(u8of(0x04), x32b, numTo32b(y));\n }\n toHex(isCompressed) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n);\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\n/** `Q = u1\u22C5G + u2\u22C5R`. Verifies Q is not ZERO. Unsafe: non-CT. */\nconst doubleScalarMulUns = (R, u1, u2) => {\n return G.multiply(u1, false)\n .add(R.multiply(u2, false))\n .assertValidity();\n};\n// Inherits byte validation from bytesToHex(); the || '0' fallback keeps empty input mapped to 0n.\nconst bytesToNumBE = (b) => big('0x' + (bytesToHex(b) || '0'));\n// Callers provide monotone slice bounds; subarray() would otherwise clamp or reinterpret them silently.\nconst sliceBytesNumBE = (b, from, to) => bytesToNumBE(b.subarray(from, to));\nconst B256 = 2n ** 256n; // secp256k1 is weierstrass curve. Equation is x\u00B3 + ax + b.\n/** Generic 32-byte big-endian encoder. Must be 0 <= num < B256; call sites need not be field/scalar elements. */\nconst numTo32b = (num) => hexToBytes(padh(arange(num, 0n, B256), L2));\n/** Normalize private key to scalar (bigint). Verifies scalar is in range 1 <= d < N. */\nconst secretKeyToScalar = (secretKey) => {\n const num = bytesToNumBE(abytes(secretKey, L, 'secret key'));\n return arange(num, 1n, N, 'invalid secret key: outside of range');\n};\n/** For signature malleability, checks the strict upper-half predicate s > floor(N/2). */\nconst highS = (n) => n > N >> 1n;\n/**\n * Creates a SEC 1 public key from a 32-byte private key.\n * @param privKey - 32-byte secret key.\n * @param isCompressed - return 33-byte compressed SEC 1 encoding when `true`, otherwise 65-byte uncompressed.\n * @returns serialized secp256k1 public key in SEC 1 encoding.\n * @example\n * Derive the serialized public key for a secp256k1 secret key.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const publicKey = secp.getPublicKey(secretKey);\n * ```\n */\nconst getPublicKey = (privKey, isCompressed = true) => {\n return G.multiply(secretKeyToScalar(privKey)).toBytes(isCompressed);\n};\nconst isValidSecretKey = (secretKey) => {\n try {\n return !!secretKeyToScalar(secretKey);\n }\n catch (error) {\n return false;\n }\n};\nconst isValidPublicKey = (publicKey, isCompressed) => {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\n }\n};\nconst assertRecoveryBit = (recovery) => [0, 1, 2, 3].includes(recovery) ? recovery : err('invalid recovery id');\nconst assertSigFormat = (format) => {\n if (format === SIG_DER)\n err('Signature format \"der\" is not supported: switch to noble-curves');\n if (format != null && format !== SIG_COMPACT && format !== SIG_RECOVERED)\n err('Signature format must be one of: compact, recovered, der');\n};\nconst assertSigLength = (sig, format = SIG_COMPACT) => {\n assertSigFormat(format);\n const len = lengths.signature + Number(format === SIG_RECOVERED);\n if (sig.length !== len)\n err(`Signature format \"${format}\" expects Uint8Array with length ${len}`);\n};\n/**\n * ECDSA Signature class. Supports only compact 64-byte representation, not DER.\n * @param r - signature `r` scalar.\n * @param s - signature `s` scalar.\n * @param recovery - optional recovery id.\n * @example\n * Build a recovered-format signature object and serialize it.\n * ```ts\n * import { Signature } from '@noble/secp256k1';\n * const bytes = new Signature(1n, 2n, 0).toBytes('recovered');\n * ```\n */\nclass Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\n this.r = FnIsValidNot0(r); // 1 <= r < N\n this.s = FnIsValidNot0(s); // 1 <= s < N\n // Keep recovered Signature objects internally consistent across all construction paths.\n if (recovery != null)\n this.recovery = assertRecoveryBit(recovery);\n Object.freeze(this);\n }\n static fromBytes(b, format = SIG_COMPACT) {\n assertSigLength(b, format);\n let rec;\n if (format === SIG_RECOVERED) {\n rec = b[0];\n b = b.subarray(1);\n }\n const r = sliceBytesNumBE(b, 0, L);\n const s = sliceBytesNumBE(b, L, L2);\n return new Signature(r, s, rec);\n }\n addRecoveryBit(bit) {\n return new Signature(this.r, this.s, bit);\n }\n hasHighS() {\n return highS(this.s);\n }\n toBytes(format = SIG_COMPACT) {\n // Standalone noble-secp256k1 does not implement DER; reject here so direct Signature users\n // don't silently get compact bytes for an unsupported format.\n assertSigFormat(format);\n const { r, s, recovery } = this;\n const res = concatBytes(numTo32b(r), numTo32b(s));\n if (format === SIG_RECOVERED) {\n return concatBytes(u8of(assertRecoveryBit(recovery)), res);\n }\n return res;\n }\n}\n/**\n * RFC6979: ensure ECDSA msg is X bytes, convert to BigInt.\n * RFC 6979 \u00A72.3.2 says bits2int keeps the leftmost qlen bits and discards the rest.\n * FIPS 186-4 4.6 gives the same leftmost-bit truncation rule. bits2int can produce res>N.\n */\nconst bits2int = (bytes) => {\n // The 8 KiB cap is only a local DoS guard. Longer ordinary prehashes must still follow\n // RFC 6979 \u00A72.3.2 truncation instead of being rejected just because blen > qlen.\n if (bytes.length > 8192)\n err('input is too large');\n const delta = bytes.length * 8 - 256;\n const num = bytesToNumBE(bytes);\n return delta > 0 ? num >> big(delta) : num;\n};\n/** int2octets can't be used; pads small msgs with 0: BAD for truncation as per RFC vectors */\nconst bits2int_modN = (bytes) => modN(bits2int(abytes(bytes)));\n// todo: better name\nconst SIG_COMPACT = 'compact';\nconst SIG_RECOVERED = 'recovered';\nconst SIG_DER = 'der';\nconst _sha = 'SHA-256';\n/**\n * Hash implementations used by the synchronous and async ECDSA / Schnorr helpers.\n * All slots are configurable API surface; wrapper helpers revalidate that SHA-256 and HMAC-SHA256\n * providers still return exact 32-byte Uint8Array digests.\n * @example\n * Provide sync hash helpers before calling the synchronous signing API.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const sig = secp.sign(new Uint8Array([1, 2, 3]), secretKey);\n * ```\n */\nconst hashes = {\n hmacSha256Async: async (key, message) => {\n const s = subtle();\n const name = 'HMAC';\n const k = await s.importKey('raw', key, { name, hash: { name: _sha } }, false, ['sign']);\n return u8n(await s.sign(name, k, message));\n },\n hmacSha256: undefined,\n sha256Async: async (msg) => u8n(await subtle().digest(_sha, msg)),\n sha256: undefined,\n};\n// prehash=false means the caller already supplies the digest bytes\n// used by sign/verify/recover, and this helper returns the same reference unchanged.\nconst prepMsg = (msg, opts, async_) => {\n const message = abytes(msg, undefined, 'message');\n if (!opts.prehash)\n return message;\n return async_ ? gha('sha256Async', message) : gh('sha256', message);\n};\nconst NULL = /* @__PURE__ */ u8n(0);\nconst byte0 = /* @__PURE__ */ u8of(0x00);\nconst byte1 = /* @__PURE__ */ u8of(0x01);\nconst _maxDrbgIters = 1000;\nconst _drbgErr = 'drbg: tried max amount of iterations';\n// HMAC-DRBG from NIST 800-90. Minimal, non-full-spec - used for RFC6979 signatures.\nconst hmacDrbg = (seed, pred) => {\n let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen\n let k = u8n(L); // In our case, it's always equal to L\n let i = 0; // Iterations counter, will throw when over max\n const reset = () => {\n v.fill(1);\n k.fill(0);\n };\n // h = hmac(K || V || ...). The configured provider is still checked on every call because the\n // exported slot can be replaced or unset at runtime.\n const h = (...b) => gh('hmacSha256', k, concatBytes(v, ...b));\n const reseed = (seed = 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)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n // HMAC-DRBG generate() function\n const gen = () => {\n if (i++ >= _maxDrbgIters)\n err(_drbgErr);\n v = h(); // v = hmac(k || v)\n return v; // One block is enough here because secp256k1 qlen and SHA-256 hlen are both 32 bytes.\n };\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n // `pred` receives the live V buffer from gen(); it must treat that input as read-only and\n // return independent bytes, because reset() scrubs the DRBG state before hmacDrbg returns.\n while (!(res = pred(gen())))\n reseed(); // test predicate until it returns ok\n reset();\n return res;\n};\n// Identical to hmacDrbg, but async: uses built-in WebCrypto\nconst hmacDrbgAsync = async (seed, pred) => {\n let v = u8n(L); // Steps B, C of RFC6979 3.2: set hashLen\n let k = u8n(L); // In our case, it's always equal to L\n let i = 0; // Iterations counter, will throw when over max\n const reset = () => {\n v.fill(1);\n k.fill(0);\n };\n // h = hmac(K || V || ...). Async provider lookup still goes through `callHash(...)` because the\n // exported slot can be replaced or unset at runtime.\n const h = (...b) => gha('hmacSha256Async', k, concatBytes(v, ...b));\n const reseed = async (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = await h(byte0, seed); // k = hmac(K || V || 0x00 || seed)\n v = await h(); // v = hmac(K || V)\n if (seed.length === 0)\n return;\n k = await h(byte1, seed); // k = hmac(K || V || 0x01 || seed)\n v = await h(); // v = hmac(K || V)\n };\n // HMAC-DRBG generate() function\n const gen = async () => {\n if (i++ >= _maxDrbgIters)\n err(_drbgErr);\n v = await h(); // v = hmac(K || V)\n return v; // Same one-block shortcut: secp256k1 qlen and SHA-256 hlen are both 32 bytes here.\n };\n reset();\n await reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n // Same contract as sync hmacDrbg(): pred sees the live V buffer and must not mutate or return it.\n while (!(res = pred(await gen())))\n await reseed(); // test predicate until it returns ok\n reset();\n return res;\n};\n// RFC6979 signature generation, preparation step.\n// Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.3 & RFC6979.\nconst _sign = (messageHash, secretKey, opts, hmacDrbg) => {\n let { lowS, extraEntropy } = opts; // generates low-s sigs by default\n // RFC6979 3.2: we skip step A\n const int2octets = numTo32b; // int to octets\n const h1i = bits2int_modN(messageHash); // msg bigint\n const h1o = int2octets(h1i); // msg octets\n const d = secretKeyToScalar(secretKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), h1o]; // Step D of RFC6979 3.2\n /** RFC6979 3.6: additional k' (optional). See {@link ECDSAExtraEntropy}. */\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(L) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs);\n const m = h1i; // convert msg to bigint\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k\u22C5G\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 \u2208 [1,q\u22121] 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 const k2sig = (kBytes) => {\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);\n if (!(1n <= k && k < N))\n return; // Valid scalars (including k) must be in 1..N-1\n const ik = invert(k, N); // k^-1 mod n\n const q = G.multiply(k).toAffine(); // q = k\u22C5G\n const r = modN(q.x); // r = q.x mod n\n // RFC 6979 \u00A72.4 step 3 / \u00A73.4 only spell out retry for r = 0.\n // FIPS 186-5 \u00A76.4.1 step 11 says deterministic ECDSA should fail on r = 0 or s = 0, but\n // that restart-from-scratch note does not apply here: hmacDrbg() keeps advancing through one\n // RFC6979 stream until k2sig() accepts a candidate, instead of restarting from the same seed.\n if (r === 0n)\n return;\n const s = modN(ik * modN(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === 0n)\n 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; // normalized S\n if (lowS && highS(s)) {\n // if lowS was passed, ensure s is always\n normS = modN(-s); // in the bottom half of CURVE.n\n recovery ^= 1;\n }\n const sig = new Signature(r, normS, recovery); // use normS, not s\n return sig.toBytes(opts.format);\n };\n return hmacDrbg(seed, k2sig);\n};\n// Follows [SEC1](https://secg.org/sec1-v2.pdf) 4.1.4.\nconst _verify = (sig, messageHash, publicKey, opts = {}) => {\n const { lowS, format } = opts;\n if (sig instanceof Signature)\n err('Signature must be in Uint8Array, use .toBytes()');\n assertSigLength(sig, format);\n abytes(publicKey, undefined, 'publicKey');\n try {\n const { r, s } = Signature.fromBytes(sig, format);\n const h = bits2int_modN(messageHash); // Truncate hash\n const P = Point.fromBytes(publicKey); // Validate public key\n if (lowS && highS(s))\n return false; // lowS bans sig.s >= CURVE.n/2\n const is = invert(s, N); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = doubleScalarMulUns(P, u1, u2).toAffine(); // R = u1\u22C5G + u2\u22C5P\n // Stop if R is identity / zero point. Check is done inside `doubleScalarMulUns`\n const v = modN(R.x); // R.x must be in N's field, not P's\n return v === r; // mod(R.x, n) == r\n }\n catch (error) {\n return false;\n }\n};\nconst setDefaults = (opts) => {\n // Inline defaults keep the same returned keys/values while avoiding the extra defaults object.\n return {\n lowS: opts.lowS ?? true,\n prehash: opts.prehash ?? true,\n format: opts.format ?? SIG_COMPACT,\n extraEntropy: opts.extraEntropy ?? false,\n };\n};\n/**\n * Sign a message using secp256k1. Sync: uses `hashes.sha256` and `hashes.hmacSha256`.\n * Prehashes message with sha256, disable using `prehash: false`.\n * @param message - message bytes to sign.\n * @param secretKey - 32-byte secret key.\n * @param opts - See {@link ECDSASignOpts} for details. Enabling {@link ECDSAExtraEntropy} improves security.\n * @returns ECDSA signature encoded according to `opts.format`.\n * @example\n * Sign a message using secp256k1.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * secp.sign(msg, secretKey);\n * secp.sign(msg, secretKey, { extraEntropy: true });\n * secp.sign(msg, secretKey, { format: 'recovered' });\n * ```\n */\nconst sign = (message, secretKey, opts = {}) => {\n opts = setDefaults(opts);\n assertSigFormat(opts.format);\n const msg = prepMsg(message, opts, false);\n return _sign(msg, secretKey, opts, hmacDrbg);\n};\n/**\n * Sign a message using secp256k1. Async: uses built-in WebCrypto hashes.\n * Prehashes message with sha256, disable using `prehash: false`.\n * @param message - message bytes to sign.\n * @param secretKey - 32-byte secret key.\n * @param opts - See {@link ECDSASignOpts} for details. Enabling {@link ECDSAExtraEntropy} improves security.\n * @returns ECDSA signature encoded according to `opts.format`.\n * @example\n * Sign a message using secp256k1 with the async WebCrypto path.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * await secp.signAsync(msg, secretKey);\n * await secp.signAsync(keccak_256(msg), secretKey, { prehash: false });\n * await secp.signAsync(msg, secretKey, { extraEntropy: true });\n * await secp.signAsync(msg, secretKey, { format: 'recovered' });\n * ```\n */\nconst signAsync = async (message, secretKey, opts = {}) => {\n opts = setDefaults(opts);\n assertSigFormat(opts.format);\n const msg = (await prepMsg(message, opts, true));\n return _sign(msg, secretKey, opts, hmacDrbgAsync);\n};\n/**\n * Verify a signature using secp256k1. Sync: uses `hashes.sha256` and `hashes.hmacSha256`.\n * @param signature - default is 64-byte `compact` format; also see {@link ECDSASignatureFormat}.\n * @param message - message which was signed. Keep in mind `prehash` from opts.\n * @param publicKey - public key that should verify the signature.\n * @param opts - See {@link ECDSAVerifyOpts} for details.\n * @returns `true` when the signature is valid. Unsupported format configuration still\n * throws instead of returning `false`.\n * @example\n * Verify a signature using secp256k1.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * const publicKey = secp.getPublicKey(secretKey);\n * const sig = secp.sign(msg, secretKey);\n * const sigr = secp.sign(msg, secretKey, { format: 'recovered' });\n * secp.verify(sig, msg, publicKey);\n * secp.verify(sig, keccak_256(msg), publicKey, { prehash: false });\n * secp.verify(sig, msg, publicKey, { lowS: false });\n * secp.verify(sigr, msg, publicKey, { format: 'recovered' });\n * ```\n */\nconst verify = (signature, message, publicKey, opts = {}) => {\n opts = setDefaults(opts);\n const msg = prepMsg(message, opts, false);\n return _verify(signature, msg, publicKey, opts);\n};\n/**\n * Verify a signature using secp256k1. Async: uses built-in WebCrypto hashes.\n * @param sig - default is 64-byte `compact` format; also see {@link ECDSASignatureFormat}.\n * @param message - message which was signed. Keep in mind `prehash` from opts.\n * @param publicKey - public key that should verify the signature.\n * @param opts - See {@link ECDSAVerifyOpts} for details.\n * @returns `true` when the signature is valid. Unsupported format configuration still\n * throws instead of returning `false`.\n * @example\n * Verify a signature using secp256k1 with the async WebCrypto path.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { keccak_256 } from '@noble/hashes/sha3.js';\n * const secretKey = secp.utils.randomSecretKey();\n * const msg = new TextEncoder().encode('hello noble');\n * const publicKey = secp.getPublicKey(secretKey);\n * const sig = await secp.signAsync(msg, secretKey);\n * const sigr = await secp.signAsync(msg, secretKey, { format: 'recovered' });\n * await secp.verifyAsync(sig, msg, publicKey);\n * await secp.verifyAsync(sigr, msg, publicKey, { format: 'recovered' });\n * await secp.verifyAsync(sig, keccak_256(msg), publicKey, { prehash: false });\n * ```\n */\nconst verifyAsync = async (sig, message, publicKey, opts = {}) => {\n opts = setDefaults(opts);\n const msg = (await prepMsg(message, opts, true));\n return _verify(sig, msg, publicKey, opts);\n};\nconst _recover = (signature, messageHash) => {\n const sig = Signature.fromBytes(signature, 'recovered');\n const { r, s, recovery } = sig;\n // 0 or 1 recovery id determines sign of \"y\" coordinate.\n // 2 or 3 means q.x was >N.\n assertRecoveryBit(recovery);\n // SEC 1 recovery derives e through the same truncation path as verification, so prehash:false\n // must accept long digests here too instead of hard-requiring 32-byte SHA-256 input.\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const radj = recovery === 2 || recovery === 3 ? r + N : r;\n FpIsValidNot0(radj); // ensure q.x is still a field element\n const head = getPrefix(big(recovery)); // head is 0x02 or 0x03\n const Rb = concatBytes(head, numTo32b(radj)); // concat head + r\n const R = Point.fromBytes(Rb);\n const ir = invert(radj, N); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const point = doubleScalarMulUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n return point.toBytes();\n};\n/**\n * ECDSA public key recovery. Requires msg hash and recovery id.\n * Follows {@link https://secg.org/sec1-v2.pdf | SEC1} 4.1.6.\n * @param signature - recovered-format signature from `sign(..., { format: 'recovered' })`.\n * @param message - signed message bytes.\n * @param opts - See {@link ECDSARecoverOpts} for details.\n * @returns recovered public key bytes.\n * @example\n * Recover a secp256k1 public key from a recovered-format signature.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = secp.sign(message, secretKey, { format: 'recovered' });\n * secp.recoverPublicKey(sig, message);\n * ```\n */\nconst recoverPublicKey = (signature, message, opts = {}) => {\n const msg = prepMsg(message, setDefaults(opts), false);\n return _recover(signature, msg);\n};\n/**\n * Async ECDSA public key recovery. Requires msg hash and recovery id.\n * @param signature - recovered-format signature from `signAsync(..., { format: 'recovered' })`.\n * @param message - signed message bytes.\n * @param opts - See {@link ECDSARecoverOpts} for details.\n * @returns recovered public key bytes.\n * @example\n * Recover a secp256k1 public key from a recovered-format signature with the async API.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = await secp.signAsync(message, secretKey, { format: 'recovered' });\n * await secp.recoverPublicKeyAsync(sig, message);\n * ```\n */\nconst recoverPublicKeyAsync = async (signature, message, opts = {}) => {\n const msg = (await prepMsg(message, setDefaults(opts), true));\n return _recover(signature, msg);\n};\n/**\n * Elliptic Curve Diffie-Hellman (ECDH) on secp256k1.\n * Result is **NOT hashed** and returns the serialized shared point (compressed by default),\n * not the SEC 1 x-only primitive `z = x_P`.\n * secp256k1 has cofactor `h = 1`, so there is no separate cofactor-ECDH distinction here.\n * @param secretKeyA - local 32-byte secret key.\n * @param publicKeyB - peer public key.\n * @param isCompressed - return 33-byte compressed output when `true`.\n * @returns shared secret point bytes.\n * @example\n * Derive a shared secp256k1 secret with ECDH.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const alice = secp.utils.randomSecretKey();\n * const bob = secp.utils.randomSecretKey();\n * const shared = secp.getSharedSecret(alice, secp.getPublicKey(bob));\n * ```\n */\nconst getSharedSecret = (secretKeyA, publicKeyB, isCompressed = true) => {\n return Point.fromBytes(publicKeyB).multiply(secretKeyToScalar(secretKeyA)).toBytes(isCompressed);\n};\n// FIPS 186-5 Appendix A.4.1 style key generation reduces a wide random integer mod (n - 1) and adds 1.\n// The 48-byte minimum keeps the secp256k1 bias bound below the appendix's epsilon <= 2^-64 target.\nconst randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n abytes(seed);\n // Keep the public range text aligned with the enforced 48-byte FIPS floor.\n if (seed.length < lengths.seed || seed.length > 1024)\n return err('expected 48-1024b', RangeError);\n const num = M(bytesToNumBE(seed), N - 1n);\n return numTo32b(num + 1n);\n};\nconst createKeygen = (getPublicKey) => (seed) => {\n const secretKey = randomSecretKey(seed);\n return {\n secretKey,\n publicKey: getPublicKey(secretKey),\n };\n};\n/**\n * Generates a secp256k1 keypair.\n * @param seed - optional entropy seed.\n * @returns keypair with `secretKey` and `publicKey`.\n * @example\n * Generate a secp256k1 keypair for sync signing.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * secp.hashes.hmacSha256 = (key, msg) => hmac(sha256, key, msg);\n * const { secretKey, publicKey } = secp.keygen();\n * ```\n */\nconst keygen = /* @__PURE__ */ createKeygen(getPublicKey);\n/**\n * Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves.\n * @example\n * Convert bytes to a hex string with the low-level helper namespace.\n * ```ts\n * import { etc } from '@noble/secp256k1';\n * const hex = etc.bytesToHex(new Uint8Array([1, 2, 3]));\n * ```\n */\nconst etc = /* @__PURE__ */ Object.freeze({\n hexToBytes,\n bytesToHex,\n concatBytes,\n bytesToNumberBE: bytesToNumBE,\n numberToBytesBE: numTo32b,\n mod: M,\n invert: invert, // math utilities; keep public alias type aligned with runtime\n randomBytes,\n secretKeyToScalar: secretKeyToScalar,\n abytes: abytes,\n});\n/**\n * Curve-specific key utilities.\n * @example\n * Generate a fresh secret key and derive its public key.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * const secretKey = secp.utils.randomSecretKey();\n * const publicKey = secp.getPublicKey(secretKey);\n * ```\n */\nconst utils = /* @__PURE__ */ Object.freeze({\n isValidSecretKey: isValidSecretKey,\n isValidPublicKey: isValidPublicKey,\n randomSecretKey: randomSecretKey, // preserve the optional seeded call\n});\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n// Internal BIP340 tag names are ASCII-only here, so charCodeAt() is enough; this is not a general UTF-8 encoder.\nconst getTag = (tag) => Uint8Array.from('BIP0340/' + tag, (c) => c.charCodeAt(0));\nconst T_AUX = 'aux';\nconst T_NONCE = 'nonce';\nconst T_CHALLENGE = 'challenge';\n// Both SHA-256 provider slots are configurable, so tag hashing still goes through the checked\n// wrappers even though the built-in defaults are deterministic and the tag bytes are ASCII-only.\nconst taggedHash = (tag, ...messages) => {\n const tagH = gh('sha256', getTag(tag));\n return gh('sha256', concatBytes(tagH, tagH, ...messages));\n};\n// Async twin of taggedHash with the same checked provider boundary.\nconst taggedHashAsync = (tag, ...messages) => gha('sha256Async', getTag(tag)).then((tagH) => gha('sha256Async', concatBytes(tagH, tagH, ...messages)));\n// BIP340 PubKey(sk) = bytes(d'\u22C5G), where bytes(P) is bytes(x(P)); signing also normalizes\n// d to the equivalent scalar whose point has even y so the x-only public key stays canonical.\nconst extpubSchnorr = (priv) => {\n const d_ = secretKeyToScalar(priv);\n const p = G.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const { x, y } = p.assertValidity().toAffine(); // validate Point is not at infinity\n const d = isEven(y) ? d_ : modN(-d_);\n const px = numTo32b(x);\n return { d, px };\n};\nconst bytesModN = (bytes) => modN(bytesToNumBE(bytes));\nconst challenge = (...args) => bytesModN(taggedHash(T_CHALLENGE, ...args));\nconst challengeAsync = async (...args) => bytesModN(await taggedHashAsync(T_CHALLENGE, ...args));\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nconst pubSchnorr = (secretKey) => {\n return extpubSchnorr(secretKey).px; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n};\nconst keygenSchnorr = /* @__PURE__ */ createKeygen(pubSchnorr);\n// Common preparation fn for both sync and async signing\nconst prepSigSchnorr = (message, secretKey, auxRand) => {\n const { px, d } = extpubSchnorr(secretKey);\n return { m: abytes(message), px, d, a: abytes(auxRand, L) };\n};\nconst extractK = (rand) => {\n const k_ = bytesModN(rand); // Let k' = int(rand) mod n\n if (k_ === 0n)\n err('sign failed: k is zero'); // Fail if k' = 0.\n const { px, d } = extpubSchnorr(numTo32b(k_)); // Let R = k'\u22C5G.\n return { rx: px, k: d };\n};\n// Common signature creation helper\nconst createSigSchnorr = (k, px, e, d) => {\n return concatBytes(px, numTo32b(modN(k + e * d)));\n};\nconst E_INVSIG = 'invalid signature produced';\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and defaults to fresh 32-byte randomness; it is not the sole source of\n * k generation, so bad CSPRNG won't be the only entropy source.\n */\nconst signSchnorr = (message, secretKey, auxRand = randomBytes(L)) => {\n const { m, px, d, a } = prepSigSchnorr(message, secretKey, auxRand);\n const aux = taggedHash(T_AUX, a);\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const t = numTo32b(d ^ bytesToNumBE(aux));\n // Let rand = hash/nonce(t || bytes(P) || m)\n const rand = taggedHash(T_NONCE, t, px, m);\n const { rx, k } = extractK(rand);\n // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const e = challenge(rx, px, m);\n const sig = createSigSchnorr(k, rx, e, d);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!verifySchnorr(sig, m, px))\n err(E_INVSIG);\n return sig;\n};\nconst signSchnorrAsync = async (message, secretKey, auxRand = randomBytes(L)) => {\n const { m, px, d, a } = prepSigSchnorr(message, secretKey, auxRand);\n const aux = await taggedHashAsync(T_AUX, a);\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const t = numTo32b(d ^ bytesToNumBE(aux));\n // Let rand = hash/nonce(t || bytes(P) || m)\n const rand = await taggedHashAsync(T_NONCE, t, px, m);\n const { rx, k } = extractK(rand);\n // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const e = await challengeAsync(rx, px, m);\n const sig = createSigSchnorr(k, rx, e, d);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!(await verifySchnorrAsync(sig, m, px)))\n err(E_INVSIG);\n return sig;\n};\nconst callSyncAsyncFn = (res, later) => {\n return res instanceof Promise ? res.then(later) : later(res);\n};\nconst _verifSchnorr = (signature, message, publicKey, challengeFn) => {\n const sig = abytes(signature, L2, 'signature');\n const msg = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, L, 'publicKey');\n try {\n // lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n // Fail if x \u2265 p. Let c = x\u00B3 + 7 mod p.\n const x = bytesToNumBE(pub);\n const y = lift_x(x); // lift_x already returns the unique even root required by BIP340.\n const P_ = new Point(x, y, 1n).assertValidity();\n const px = numTo32b(P_.toAffine().x);\n // P = lift_x(int(pk)); fail if that fails\n const r = sliceBytesNumBE(sig, 0, L); // Let r = int(sig[0:32]); fail if r \u2265 p.\n arange(r, 1n, P);\n const s = sliceBytesNumBE(sig, L, L2); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n arange(s, 1n, N);\n const i = concatBytes(numTo32b(r), px, msg);\n // int(challenge(bytes(r)||bytes(P)||m))%n\n return callSyncAsyncFn(challengeFn(i), (e) => {\n const { x, y } = doubleScalarMulUns(P_, s, modN(-e)).toAffine(); // R = s\u22C5G - e\u22C5P\n if (!isEven(y) || x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n });\n }\n catch (error) {\n return false;\n }\n};\n/** Verifies Schnorr signature. Sync wrapper returns false for post-validation failures\n * after the initial byte checks. */\nconst verifySchnorr = (s, m, p) => _verifSchnorr(s, m, p, challenge);\n/** Async Schnorr verification. Curve/encoding failures after the initial byte checks still\n * become false, but async backend failures reject the promise. Missing crypto.subtle is a\n * runtime/backend error, not an \"invalid signature\" result, so we surface it instead of\n * turning it into false. */\nconst verifySchnorrAsync = async (s, m, p) => _verifSchnorr(s, m, p, challengeAsync);\n/**\n * BIP340 Schnorr helpers over secp256k1.\n * @example\n * Sign and verify a BIP340 Schnorr signature.\n * ```ts\n * import * as secp from '@noble/secp256k1';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * secp.hashes.sha256 = sha256;\n * const secretKey = secp.utils.randomSecretKey();\n * const message = new Uint8Array([1, 2, 3]);\n * const sig = secp.schnorr.sign(message, secretKey);\n * const publicKey = secp.schnorr.getPublicKey(secretKey);\n * const isValid = secp.schnorr.verify(sig, message, publicKey);\n * ```\n */\nconst schnorr = /* @__PURE__ */ Object.freeze({\n keygen: keygenSchnorr,\n getPublicKey: pubSchnorr,\n sign: signSchnorr,\n verify: verifySchnorr,\n signAsync: signSchnorrAsync,\n verifyAsync: verifySchnorrAsync,\n});\n// ## Precomputes\n// --------------\nconst W = 8; // W is window size\nconst scalarBits = 256;\nconst pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8, NOT 32 - see wNAF loop\nconst pwindowSize = 2 ** (W - 1); // 128 for W=8\nconst precompute = () => {\n const points = [];\n let p = G;\n let b = p;\n for (let w = 0; w < pwindows; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < pwindowSize; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // precomputes for base point G\n// Branch-shaped negate helper for wNAF; not a hard constant-time primitive in JavaScript.\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n const pow_2_w = 2 ** W; // 256 for W=8\n const maxNum = pow_2_w; // 256 for W=8\n const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111\n const shiftBy = big(W); // 8 for W=8\n for (let w = 0; w < pwindows; w++) {\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n // We use negative indexes to reduce size of precomputed table by 2x.\n // Instead of needing precomputes 0..256, we only calculate them for 0..128.\n // If an index > 128 is found, we do (256-index) - where 256 is next window.\n // Naive: index +127 => 127, +224 => 224\n // Optimized: index +127 => 127, +224 => 256-32\n if (wbits > pwindowSize) {\n wbits -= maxNum;\n n += 1n;\n }\n const off = w * pwindowSize;\n const offF = off; // offsets, evaluate both\n const offP = off + Math.abs(wbits) - 1;\n const isEven = w % 2 !== 0; // conditions, evaluate both\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // off == I: can't add it. Adding random offF instead.\n f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n if (n !== 0n)\n err('invalid wnaf');\n return { p, f }; // return both real and fake points for JIT/leakage-shape symmetry\n};\n// !! Remove the export below to easily use in REPL / browser console\nexport { etc, getPublicKey, getSharedSecret, hash, hashes, keygen, Point, recoverPublicKey, recoverPublicKeyAsync, schnorr, sign, signAsync, Signature, utils, verify, verifyAsync, };\n", "/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, aoutput, clean, } from \"./utils.js\";\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC {\n oHash;\n iHash;\n blockLen;\n outputLen;\n canXOF = false;\n finished = false;\n destroyed = false;\n constructor(hash, key) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('expected Hash instance');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf) {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.canXOF = canXOF;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\nexport const hmac = /* @__PURE__ */ (() => {\n const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());\n hmac_.create = (hash, key) => new _HMAC(hash, key);\n return hmac_;\n})();\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\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, b, c) {\n return (a & b) ^ (~a & c);\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, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\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 class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\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) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\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)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : 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 processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\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, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, 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 buffer.fill(0);\n }\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 (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : 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 const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\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;\n }\n _cloneIntoMeta(to) {\n const { 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 (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\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/** Initial SHA256 state from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 \u00A76.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 = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state from RFC 6234 \u00A76.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 = /* @__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.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, oidNist, rotr } from \"./utils.js\";\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.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/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nclass SHA2_32B extends HashMD {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\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 set(A, B, C, D, E, F, G, H) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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)\n 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 roundClean() {\n clean(SHA256_W);\n }\n destroy() {\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/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.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// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nclass SHA2_64B extends HashMD {\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 // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\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 set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\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 _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\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 roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\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/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\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/** 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/** 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/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\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 * @param opts - Reserved hash options.\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 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n", "/**\n * Utility functions for cryptographic operations\n */\n\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { sha3_256 } from '@noble/hashes/sha3.js';\n\nfunction isDroppable(v: unknown): boolean {\n return v === undefined || typeof v === 'function' || typeof v === 'symbol';\n}\n\nfunction compareCodeUnits(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * Canonicalize a value to its RFC 8785 (JSON Canonicalization Scheme) string.\n *\n * The result is the canonical form of exactly what `JSON.stringify` would put\n * on the wire, so a signer canonicalizing an in-memory object and a verifier\n * canonicalizing the parsed JSON get the same bytes:\n * - object keys are escaped as JSON strings and sorted by UTF-16 code unit;\n * - `undefined`, functions and symbols are dropped from objects and become\n * `null` in arrays;\n * - `toJSON()` is honoured (a Date becomes its ISO string);\n * - non-finite numbers, bigints and circular references throw.\n *\n * Earlier versions interpolated keys unescaped, so `{'a\":1,\"b': 2}` and\n * `{a: 1, b: 2}` produced the same string, and emitted the bare word\n * `undefined`. Output is unchanged for every value that did not hit either\n * defect.\n */\nexport function canonicalizeJson(obj: any): string {\n return serializeCanonical(obj, new Set(), true);\n}\n\nfunction serializeCanonical(input: unknown, seen: Set<object>, top: boolean): string {\n let value = input;\n if (value !== null && typeof value === 'object' && typeof (value as any).toJSON === 'function') {\n value = (value as any).toJSON();\n }\n\n if (value === null) return 'null';\n\n const t = typeof value;\n if (t === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError(`canonicalizeJson: non-finite number ${String(value)} has no JSON representation`);\n }\n return JSON.stringify(value);\n }\n if (t === 'boolean' || t === 'string') return JSON.stringify(value);\n if (t === 'bigint') {\n throw new TypeError('canonicalizeJson: bigint has no JSON representation; carry it as a string');\n }\n if (isDroppable(value)) {\n if (top) throw new TypeError(`canonicalizeJson: ${t} is not serializable`);\n return 'null';\n }\n\n const obj = value as object;\n if (seen.has(obj)) throw new TypeError('canonicalizeJson: circular reference');\n seen.add(obj);\n let out: string;\n if (Array.isArray(obj)) {\n out = '[' + obj.map(v => serializeCanonical(v, seen, false)).join(',') + ']';\n } else {\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record)\n .filter(k => !isDroppable(record[k]))\n .sort(compareCodeUnits);\n out =\n '{' +\n keys.map(k => JSON.stringify(k) + ':' + serializeCanonical(record[k], seen, false)).join(',') +\n '}';\n }\n seen.delete(obj);\n return out;\n}\n\n/**\n * Convert string to UTF-8 bytes\n */\nexport function stringToBytes(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/**\n * Convert bytes to UTF-8 string\n */\nexport function bytesToString(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Convert bytes to hex string\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to bytes\n *\n * @throws if the string has odd length or contains a non-hex character.\n * Non-hex input used to decode silently to zero bytes.\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') {\n throw new Error('Hex input must be a string');\n }\n if (hex.length % 2 !== 0) {\n throw new Error('Hex string must have even length');\n }\n if (!/^[0-9a-fA-F]*$/.test(hex)) {\n throw new Error('Hex string contains a non-hex character');\n }\n \n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\n/**\n * Convert bytes to base64url (URL-safe base64 without padding)\n */\nexport function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=/g, '');\n}\n\n/**\n * Convert base64url to bytes\n *\n * @throws if the string is not valid unpadded-or-padded base64url\n */\nexport function base64UrlToBytes(base64url: string): Uint8Array {\n if (typeof base64url !== 'string' || !/^[A-Za-z0-9_-]*={0,2}$/.test(base64url)) {\n throw new Error('Invalid base64url string');\n }\n const unpadded = base64url.replace(/=+$/, '');\n if (unpadded.length % 4 === 1) {\n throw new Error('Invalid base64url string length');\n }\n let base64 = unpadded.replace(/-/g, '+').replace(/_/g, '/');\n const padding = base64.length % 4;\n if (padding) {\n base64 += '='.repeat(4 - padding);\n }\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Secure constant-time comparison of two byte arrays\n */\nexport function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n \n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n\n/**\n * Zero out a byte array (for secure key cleanup)\n */\nexport function zeroBytes(bytes: Uint8Array): void {\n bytes.fill(0);\n}\n\n/**\n * Create a hash of the given bytes using the specified algorithm\n *\n * Implemented with @noble/hashes so it behaves identically in Node, browsers\n * and workers; it previously imported Node's `crypto` and needed a shim to\n * bundle.\n */\nexport async function hashBytes(\n bytes: Uint8Array,\n algorithm: string\n): Promise<Uint8Array> {\n if (algorithm === 'sha256') {\n return sha256(bytes);\n } else if (algorithm === 'sha512') {\n return sha512(bytes);\n } else if (algorithm === 'sha3-256') {\n return sha3_256(bytes);\n }\n \n throw new Error(`Unsupported hash algorithm: ${algorithm}`);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\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(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\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(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable \u2014\n * throws or returns malformed bytes \u2014 so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade \u2014 a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2\u22C5size\u22121)P]; width-W wNAF uses size = 2^(W\u22122). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W\u22121); nonzero density ~1/(W+1) (a nonzero digit is followed by W\u22121 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w \u2261 0 mod 2^W: next W\u22121 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = \u03A3 digits[w]\u22C52^(w\u22C5W)` with\n * digits in `[\u22122^(W\u22121)+1, 2^(W\u22121)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P` \u2014 all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44\u22C532 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W\u22121)]\u22C52^(w\u22C5W)\u22C5P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44\u22C532 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2\u22C5(2^(W\u22121)\u22C5base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window \u2014 zero digits feed\n * the fake accumulator \u2014 and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 \u2014 never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator \u2014 its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 \u2014\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `\u03A3 scalars[i]\u22C5points[i]` via interleaved width-4 wNAF\n * (Strauss\u2013Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L\u22C5bits/5` additions instead of `L\u22C5bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1\u22C5G + u2\u22C5P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER\u22C5P \u225F O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss\u2013Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2\u22C5G + 3\u22C5(2\u22C5G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\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 * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 \u2014 but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\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(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\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)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n 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)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W\u22121)\u22121)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) \u2014 one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) \u2014 the\n * \"interleaving\" method of M\u00F6ller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L\u22C52^(W\u22122)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\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)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\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. See {@link FpFn}:\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(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && 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 = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\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 };\n}\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(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen } from \"./abstract/curve.js\";\nimport { createFROST, } from \"./abstract/frost.js\";\nimport { createHasher, isogenyMap, mapToCurveSimpleSWU, } from \"./abstract/hash-to-curve.js\";\nimport { Field, mapHashToField, pow2 } from \"./abstract/modular.js\";\nimport { ecdsa, weierstrass, } from \"./abstract/weierstrass.js\";\nimport { abytes, asciiToBytes, bytesToNumberBE, concatBytes, } from \"./utils.js\";\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\nconst secp256k1_ENDO = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fpk1 = /* @__PURE__ */ Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = Object.create(null);\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toBytes(true).slice(1);\nconst affineXToBytes = ({ x }) => Fpk1.toBytes(x);\nconst hasEven = (y) => !Fpk1.isOdd(y);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(abytes(priv, 32, 'secretKey'));\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const affine = p.toAffine();\n const scalar = hasEven(affine.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: affineXToBytes(affine) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x))\n throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.sqr(x);\n const c = Fp.add(Fp.mulN(xx, x), BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y))\n y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args) {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey) {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(message, secretKey, auxRand = randomBytes(32)) {\n const { Fn, BASE } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n if (k_ === _0n)\n throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const affine = p.toAffine();\n const k = hasEven(affine.y) ? k_ : Fn.neg(k_);\n const rx = affineXToBytes(affine);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const rBytes = sig.subarray(0, 32);\n const r = num(rBytes); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!Fp.isValidNot0(r))\n return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s))\n return false;\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(rBytes, pointToBytes(P), m);\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.mulAddUnsafe(s, P, Fn.neg(e)); // s\u22C5G + (-e)\u22C5P, joint Strauss\u2013Shamir\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || !Fp.eql(x, r))\n return false;\n return true;\n }\n catch (error) {\n return false;\n }\n}\nexport const __TEST = /* @__PURE__ */ Object.freeze({ lift_x, frostTweakPublic, frostTweakSecret });\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed) => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(abytes(seed, seedLength, 'seed'), secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU;\nconst getMapSWU = () => mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n}))();\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point, merkleRoot) {\n if (merkleRoot === undefined)\n return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t))\n throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y))\n return pub;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])),\n };\n}\nfunction frostSecretToEvenY(s, pub) {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y))\n return s;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n };\n}\nfunction frostNoncesToEvenY(groupCommitment, nonces) {\n if (hasEven(groupCommitment.y))\n return nonces;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n };\n}\nfunction frostTweakSecret(s, pub, merkleRoot) {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n };\n}\nfunction frostTweakPublic(pub, merkleRoot) {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n // Disabled TapTweak (t=0): return the even-Y-normalized package as-is. multiply() rejects\n // zero scalars, and adding [0]G would be a no-op anyway.\n if (t === _0n)\n return PKPackage;\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes());\n const verifyingShares = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n };\n}\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32)\n return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33)\n return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1),\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx),\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n}))();\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + 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 { abool, abytes, aInRange, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, mulAddUnsafe, normalizeZ, probeRandomBytes, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { DER } from \"./der.js\";\nimport { getMinHashLength, invertCt, mapHashToField } from \"./modular.js\";\n// DER codec lives in der.ts; re-exported here because ECDSA signatures are its main consumer.\nexport { DER, DERErr } from \"./der.js\";\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, den) => (num + (num >= 0 ? den : -den) / _2n) / den;\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k, basis, n) {\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 \u2261 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)\n k1 = -k1;\n if (k2neg)\n k2 = -k2;\n // Double check that resulting scalar is less than half bits of N: the wNAF pair walk\n // relies on the halves being short. 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}\nfunction validateSigFormat(format) {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format;\n}\nfunction validateSigOpts(opts, def) {\n validateObject(opts);\n const optsn = {};\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)) {\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)\n validateSigFormat(optsn.format);\n return optsn;\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 * 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(params, extraOpts = {}) {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp;\n const Fn = validated.Fn;\n let CURVE = validated.CURVE;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(extraOpts, {}, {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n randomBytes: 'function',\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 const randomBytes = extraOpts.randomBytes === undefined ? wcRandomBytes : extraOpts.randomBytes;\n if (endo) {\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 const lengths = getWLengths(Fp, Fn);\n function assertCompressionIsSupported() {\n if (!Fp.isOdd)\n throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n // Implements IEEE P1363 point encoding\n function pointToBytes(_c, point, isCompressed) {\n // SEC 1 v2.0 \u00A72.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())\n return Uint8Array.of(0);\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);\n }\n else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y));\n }\n }\n function pointFromBytes(bytes) {\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)\n return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.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))\n throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n }\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)\n y = Fp.neg(y);\n return { x, y };\n }\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))\n throw new Error('bad point: is not on curve');\n return { x, y };\n }\n else {\n throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);\n }\n }\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n // Hoisted from double() / add(): curve params never change after construction.\n // Koblitz curves (a=0, e.g. secp256k1) skip the three a-multiplications per operation;\n // the selection depends only on public curve constants.\n const b3 = Fp.mul(CURVE.b, _3n);\n const mulA = Fp.is0(CURVE.a) ? (_) => Fp.ZERO : (x) => Fp.mul(CURVE.a, x);\n function weierstrassEquation(x) {\n const x2 = Fp.sqr(x);\n const x3 = Fp.mul(x2, x);\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x, y) {\n const left = Fp.sqr(y);\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\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\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 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)))\n throw new Error('bad curve params: a or b');\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title, n, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n)))\n throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n function aprjpoint(other) {\n if (!(other instanceof Point))\n throw new Error('Weierstrass Point expected');\n }\n function splitEndoScalarN(k) {\n if (!endo || !endo.basises)\n throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n /**\n * Appends a (point, scalar) pair to the inputs of a vartime wNAF walk\n * ({@link mulAddUnsafe}). With GLV endomorphism the scalar is split into two half-width\n * pairs against P and \u03C8(P) = (\u03B2\u22C5x, y), halving the walk's shared doubling chain;\n * split signs fold into the points.\n */\n function pushWnafPair(points, scalars, p, k) {\n if (!Fn.isValid(k))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(k);\n const psi = new Point(Fp.mul(p.X, endo.beta), p.Y, p.Z);\n points.push(k1neg ? p.negate() : p, k2neg ? psi.negate() : psi);\n scalars.push(k1, k2);\n }\n else {\n points.push(p);\n scalars.push(k);\n }\n }\n // Successful assertValidity() results are cached: Point instances are frozen at construction,\n // so on-curve + subgroup facts cannot change afterwards. Only success is cached \u2014 invalid\n // points re-throw on every call. This matters most for pairing curves, where subgroup checks\n // cost a scalar multiplication and the same instance is re-validated across layers\n // (signature fromBytes, pairingBatch) or across repeated verifies with a cached public key.\n const validityCache = new WeakSet();\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (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 {\n static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\n static Fn = Fn;\n X;\n Y;\n Z;\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X, Y, Z) {\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 static CURVE() {\n return CURVE;\n }\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n 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))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n static fromBytes(bytes) {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n static fromHex(hex) {\n return Point.fromBytes(hexToBytes(hex));\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * @param isLazy - true will defer table computation until the first multiplication\n */\n precompute(windowSize = 6, isLazy = true) {\n wnaf.setWindowSize(this, windowSize);\n if (!isLazy)\n this.multiply(_3n); // random number\n return this;\n }\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity() {\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 if (validityCache.has(p))\n return;\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))\n throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y))\n throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n validityCache.add(p);\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n /** Compare one point to another. */\n equals(other) {\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 /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate() {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\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 { 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 = mulA(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 = mulA(t2);\n t3 = Fp.sub(t0, t2);\n t3 = mulA(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 // 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) {\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 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 = mulA(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 = mulA(t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = mulA(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 subtract(other) {\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 is0() {\n return this.equals(Point.ZERO);\n }\n /**\n * Constant time multiplication.\n * Uses precomputed tables (signed fixed-window wNAF) when available.\n * Uses scalar blinding and avoids endomorphism splitting in the secret-scalar path.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\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))\n throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);\n return normalize([p, f])[0];\n }\n /**\n * Non-constant-time multiplication. Uses width-4 wNAF with GLV endomorphism splitting\n * when available (two half-width scalars sharing one halved doubling chain).\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) {\n const p = this;\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))\n throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0())\n return Point.ZERO;\n if (sc === _1n)\n return p;\n if (wnaf.hasWindowSize(this))\n return wnaf.mulUnsafe(p, sc, normalize); // precomputes\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, p, sc);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Non-constant-time double-scalar multiplication `a\u22C5this + b\u22C5other` (Strauss\u2013Shamir).\n * Both walks share one doubling chain via {@link mulAddUnsafe}, and GLV endomorphism\n * (when available) halves the chain again by splitting each scalar into two half-width\n * parts. Used by ECDSA verification and public-key recovery for `R = u1\u22C5G + u2\u22C5P`.\n * Only for public scalars.\n */\n mulAddUnsafe(a, other, b) {\n aprjpoint(other);\n const points = [];\n const scalars = [];\n pushWnafPair(points, scalars, this, a);\n pushWnafPair(points, scalars, other, b);\n return mulAddUnsafe(Point, points, scalars);\n }\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n if (iz != null && !Fp.isValid(iz))\n throw new RangeError('\"invertedZ\" expected valid field element');\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE))\n 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)\n 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)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\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() {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n)\n return true;\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n // unsafe() will use the uncached wNAF path internally, since CURVE_ORDER >= Fn.ORDER\n return wnaf.mulUnsafe(this, CURVE_ORDER).is0();\n }\n clearCofactor() {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\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 isSmallOrder() {\n if (cofactor === _1n)\n return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n toBytes(isCompressed = true) {\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 toHex(isCompressed = true) {\n return bytesToHex(this.toBytes(isCompressed));\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY) {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03);\n}\nfunction getWLengths(Fp, Fn) {\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 * 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(Point, ecdhOpts = {}) {\n validatePointCons(Point);\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 function isValidSecretKey(secretKey) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n }\n catch (error) {\n return false;\n }\n }\n function isValidPublicKey(publicKey, isCompressed) {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp)\n return false;\n if (isCompressed === false && l !== publicKeyUncompressed)\n return false;\n return !!Point.fromBytes(publicKey);\n }\n catch (error) {\n return false;\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) {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER);\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, isCompressed = true) {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\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) {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = Fn._lengths;\n if (!isBytes(item))\n 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)\n return undefined;\n return isPub;\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(secretKeyA, publicKeyB, isCompressed = true) {\n if (isProbPub(secretKeyA) === true)\n throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false)\n 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 const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\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(Point, hash, ecdsaOpts = {}) {\n validatePointCons(Point);\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash;\n ahash(hash_);\n validateObject(ecdsaOpts, {}, {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n });\n const opts = Object.assign({}, ecdsaOpts);\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const hmac = opts.hmac === undefined\n ? (key, msg) => nobleHmac(hash_, key, msg)\n : opts.hmac;\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n // Nonce-inversion blinding in k2sig draws `getMinHashLength(n)` bytes per sign. Probe the RNG\n // once (see {@link probeRandomBytes}, shared with ScalarMultiplier): in environments without\n // working randomness, signing downgrades to Fermat inversion (invertCt) instead of throwing on\n // every sign(). The shape of returned bytes is still validated (by mapHashToField) on every\n // blinded call, where breakage fails closed.\n const blindLength = getMinHashLength(CURVE_ORDER);\n const csprng = probeRandomBytes(randomBytes, blindLength);\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, opts);\n const defaultSigOpts = {\n prehash: true,\n lowS: typeof opts.lowS === 'boolean' ? opts.lowS : true,\n format: 'compact',\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 function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title, num) {\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 assertFieldSignIsSupported() {\n if (!Fp.isOdd)\n throw new Error(\"Field doesn't support isOdd\");\n }\n // Recovery id of an affine point (x, y) whose x reduces to signature `r` mod n:\n // bit 0 = y parity, bit 1 = x overflowed the group order (x = r + n).\n function getRecoveryBit(x, y, r) {\n assertFieldSignIsSupported();\n return (x === r ? 0 : 2) | Number(Fp.isOdd(y));\n }\n function assertRecoverableCurve() {\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, format) {\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 * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature {\n r;\n s;\n recovery;\n constructor(r, s, recovery) {\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))\n throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n static fromBytes(bytes, format = defaultSigOpts.format) {\n validateSigLength(bytes, format);\n let recid;\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 static fromHex(hex, format) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n assertRecovery() {\n const { recovery } = this;\n if (recovery == null)\n throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\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) {\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))\n 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.mulAddUnsafe(u1, R, u2);\n if (Q.is0())\n throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n toBytes(format = defaultSigOpts.format) {\n validateSigFormat(format);\n if (format === 'der')\n return hexToBytes(DER.hexFromSig(this));\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);\n }\n return concatBytes(rb, sb);\n }\n toHex(format) {\n return bytesToHex(this.toBytes(format));\n }\n }\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\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 = opts.bits2int === undefined\n ? function bits2int_def(bytes) {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192)\n 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 : opts.bits2int;\n const bits2int_modN = opts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes) {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : opts.bits2int_modN;\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) {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num);\n }\n function validateMsgAndHash(message, prehash) {\n abytes(message, undefined, 'message');\n return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message);\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(message, secretKey, opts) {\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))\n throw new Error('invalid private key');\n const seedArgs = [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); // 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\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // The nonce inversion is blinded: with random b \u2208 [1,n\u22121], s = (bk)^-1(bm + bdr) per\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. Fn.inv()'s extended-Euclidean\n // loop count depends on its input (cf. Minerva), but here it only ever sees b\u00B7k \u2014 uniformly\n // random, independent of k \u2014 so its timing reveals nothing about the nonce; b also masks d in\n // the products. Without a CSPRNG (probed in ecdsa()) we fall back to Fermat inversion\n // (invertCt), whose control flow is data-independent, at ~4x the inversion cost.\n function k2sig(kBytes) {\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))\n return; // Valid scalars (including k) must be in 1..N-1\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n let s;\n if (csprng !== undefined) {\n // mapHashToField maps 1.5x-order-length uniform bytes into [1, n-1], negligible bias.\n const b = bytesToNumberBE(mapHashToField(csprng(blindLength), CURVE_ORDER));\n const ibk = Fn.inv(Fn.mul(b, k)); // (bk)^-1: inversion input is decorrelated from k\n const bm = Fn.mul(b, m);\n const bd = Fn.mul(b, d);\n s = Fn.create(ibk * Fn.create(bm + bd * r)); // s = (bk)^-1(bm + bdr) = k^-1(m + rd) mod n\n }\n else {\n const ik = invertCt(k, CURVE_ORDER); // k^-1 mod n with data-independent control flow\n s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n }\n if (s === _0n)\n return;\n let recovery = getRecoveryBit(q.x, q.y, r); // 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 * 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 \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(message, secretKey, opts = {}) {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(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 * 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\u22C5G + u2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, message, publicKey, opts = {}) {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature)) {\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())\n 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.mulAddUnsafe(u1, P, u2); // u1\u22C5G + u2\u22C5P, joint Strauss\u2013Shamir\n if (R.is0())\n return false;\n const q = R.toAffine();\n const v = Fn.create(q.x); // v = R.x mod n\n if (v !== r)\n return false;\n // R is the exact point `recoverPublicKey(r, recid)` reconstructs (sR = hG + rP),\n // so binding the signature to its recovery id only needs R's parity/overflow bits.\n if (format === 'recovered' && sig.recovery !== getRecoveryBit(q.x, q.y, r))\n return false;\n return true;\n }\n catch (e) {\n return false;\n }\n }\n function recoverPublicKey(signature, message, opts = {}) {\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 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 });\n}\n", "/**\n * ASN.1 DER (Distinguished Encoding Rules) helpers for ECDSA signatures.\n * Only implements the tiny subset needed for `SEQUENCE(INTEGER r, INTEGER s)`.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abignumber, abytes, asafenumber, astring, bytesToNumberBE, numberToHexUnpadded, validateObject, } from \"../utils.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\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// Plain const so the freezes can live inside the pure initializer of the `DER` export below:\n// bare top-level `Object.freeze(...)` calls would defeat tree-shaking for every importer.\nconst _DER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag, data) => {\n const { Err: E } = _DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255)\n throw new E('tlv.encode: wrong tag');\n astring(data, '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)\n 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)\n 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, data) {\n const { Err: E } = _DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255)\n throw new E('tlv.decode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag)\n 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)\n length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen)\n throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4)\n throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen)\n throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0)\n throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes)\n length = (length << 8) | b;\n pos += lenLen;\n if (length < 128)\n throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length)\n throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) };\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) {\n const { Err: E } = _DER;\n abignumber(num);\n if (num < _0n)\n 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)\n hex = '00' + hex;\n if (hex.length & 1)\n throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data) {\n const { Err: E } = _DER;\n if (data.length < 1)\n throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000)\n 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) {\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)\n 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)\n throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig) {\n const { _tlv: tlv, _int: int } = _DER;\n validateObject(sig, { r: 'bigint', s: 'bigint' }, {}, 'sig');\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};\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 = /* @__PURE__ */ (() => {\n Object.freeze(_DER._tlv);\n Object.freeze(_DER._int);\n return Object.freeze(_DER);\n})();\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from \"./_md.js\";\nimport { clean, createHasher, rotl } from \"./utils.js\";\n/** Initial SHA-1 state from RFC 3174 \u00A76.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD {\n A = SHA1_IV[0] | 0;\n B = SHA1_IV[1] | 0;\n C = SHA1_IV[2] | 0;\n D = SHA1_IV[3] | 0;\n E = SHA1_IV[4] | 0;\n constructor() {\n super(64, 20, 8, false);\n }\n get() {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n set(A, B, C, D, E) {\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 }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n }\n else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n }\n else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n }\n else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n roundClean() {\n clean(SHA1_W);\n }\n destroy() {\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);\n clean(this.buffer);\n }\n}\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n// RFC 1321 \u00A73.4 per-round rotate amounts, flattened to 64 entries so the round loop\n// avoids allocating a 4-element array literal every round (measured ~5% of md5).\nconst MD5_SHIFTS = /* @__PURE__ */ (() => {\n const S = [\n [7, 12, 17, 22],\n [5, 9, 14, 20],\n [4, 11, 16, 23],\n [6, 10, 15, 21],\n ];\n return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);\n})();\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD {\n A = MD5_IV[0] | 0;\n B = MD5_IV[1] | 0;\n C = MD5_IV[2] | 0;\n D = MD5_IV[3] | 0;\n constructor() {\n super(64, 16, 8, true);\n }\n get() {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n set(A, B, C, D) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n }\n else if (i < 32) {\n // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n }\n else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n }\n else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, MD5_SHIFTS[i]);\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 this.set(A, B, C, D);\n }\n roundClean() {\n clean(MD5_W);\n }\n destroy() {\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);\n clean(this.buffer);\n }\n}\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5 = /* @__PURE__ */ createHasher(() => new _MD5());\n// RIPEMD-160\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++)\n for (let j of res)\n j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n if (group === 1)\n return (x & y) | (~x & z);\n if (group === 2)\n return (x | ~y) ^ z;\n if (group === 3)\n return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD {\n h0 = 0x67452301 | 0;\n h1 = 0xefcdab89 | 0;\n h2 = 0x98badcfe | 0;\n h3 = 0x10325476 | 0;\n h4 = 0xc3d2e1f0 | 0;\n constructor() {\n super(64, 20, 8, true);\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n clean(BUF_160);\n }\n destroy() {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n", "/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const base58key = root.privateExtendedKey;\n * const restored = HDKey.fromExtendedKey(base58key);\n * const fromJson = HDKey.fromJSON({ xpriv: base58key });\n * const child = fromJson.derive(\"m/0/2147483647'/1\");\n * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));\n *\n * // props\n * [root.depth, root.index, root.chainCode];\n * [restored.privateKey, restored.publicKey];\n * const sig = child.sign(msgHash);\n * child.verify(msgHash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\nconst Point = /* @__PURE__ */ (() => secp.Point)();\nconst Fn = /* @__PURE__ */ (() => Point.Fn)();\nconst base58check = /* @__PURE__ */ createBase58check(sha256);\nconst MASTER_SECRET = /* @__PURE__ */ (() => {\n return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n})();\nconst BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened child index offset from BIP32. */\nexport const HARDENED_OFFSET = 0x80000000;\nconst hash160 = (data) => ripemd160(sha256(data));\nconst fromU32 = (data) => createView(data).getUint32(0, false);\nconst toU32 = (n, title = 'number') => {\n if (typeof n !== 'number')\n throw new TypeError(`\"${title}\" expected number, got type=${typeof n}`);\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)\n throw new RangeError(`\"${title}\" expected integer in range 0..2**32-1, got ${n}`);\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\nconst validateVersions = (versions, title = 'versions') => {\n if (!(typeof versions === 'object' && versions !== null))\n throw new Error('versions must be an object');\n toU32(versions.private, `${title}.private`);\n toU32(versions.public, `${title}.public`);\n return versions;\n};\n/**\n * HDKey from BIP32\n * @param opt - Node fields used to construct one HDKey instance.\n * @example\n * ```js\n * import { HDKey } from '@scure/bip32';\n * import { randomBytes } from '@noble/hashes/utils.js';\n *\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const account0 = root.derive(\"m/0/1'\");\n * account0.publicKey;\n * ```\n */\nexport class HDKey {\n get fingerprint() {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier() {\n return this.pubHash;\n }\n get pubKeyHash() {\n return this.pubHash;\n }\n // Returns the live private key buffer for this instance.\n // Copy it first if you need an immutable snapshot.\n get privateKey() {\n return this._privateKey || null;\n }\n get publicKey() {\n return this._publicKey || null;\n }\n get privateExtendedKey() {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv)));\n }\n get publicExtendedKey() {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) {\n abytes(seed);\n versions = validateVersions(versions);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new RangeError('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length);\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) {\n versions = validateVersions(versions);\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n }\n else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n static fromJSON(json) {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n versions;\n depth = 0;\n index = 0;\n chainCode = null;\n parentFingerprint = 0;\n _privateKey;\n _publicKey;\n pubHash;\n constructor(opt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions ? validateVersions(opt.versions) : BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey))\n throw new Error('Invalid private key');\n // Don't alias caller-owned secret buffers.\n this._privateKey = Uint8Array.from(opt.privateKey);\n this._publicKey = secp.getPublicKey(this._privateKey, true);\n }\n else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n }\n else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n derive(path) {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n /**\n * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.\n */\n deriveChild(index, _I) {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index, 'index');\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n }\n else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const out = _I || hmac(sha512, this.chainCode, data);\n abytes(out, 64);\n const childTweak = out.slice(0, 32);\n const chainCode = out.slice(32);\n const opt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n // Fail early instead of re-trying different index\n if (opt.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n try {\n const ctweak = Fn.fromBytes(childTweak);\n // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.\n // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.\n // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n }\n else {\n const point = Point.fromBytes(this._publicKey);\n const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n }\n catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n sign(hash) {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n verify(hash, signature) {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n wipePrivateData() {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON() {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n serialize(version, key) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(toU32(version, 'version'), new Uint8Array([this.depth]), toU32(this.parentFingerprint, 'parentFingerprint'), toU32(this.index, 'index'), this.chainCode, key);\n }\n}\nexport const __TESTS = /* @__PURE__ */ Object.freeze({\n deriveChildWithI(key, index, I) {\n // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.\n return key.deriveChild(index, I);\n },\n});\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Freeze the result of a thunk. `/* @__PURE__ */ freeze(() => expr)` keeps the whole\n// initializer tree-shakable: the annotated call's only argument is a function literal,\n// so bundlers drop everything (inner chain()/alphabet() calls included) when unused.\nconst freeze = (fn) => Object.freeze(fn());\nfunction isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n // fallback on byte-oriented views.\n return (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/** Asserts something is Uint8Array. */\nfunction abytes(b) {\n if (!isBytes(b))\n throw new TypeError('Uint8Array expected');\n}\nfunction isArrayOf(isString, arr) {\n if (!Array.isArray(arr))\n return false;\n if (arr.length === 0)\n return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n }\n else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\nfunction afn(input) {\n if (typeof input !== 'function')\n throw new TypeError('function expected');\n return true;\n}\nfunction astr(label, input) {\n if (typeof input !== 'string')\n throw new TypeError(`${label}: string expected`);\n return true;\n}\nfunction anumber(n, title = 'number') {\n if (typeof n !== 'number')\n throw new TypeError(`${title}: expected number, got ${typeof n}`);\n if (!Number.isSafeInteger(n))\n throw new RangeError(`${title}: expected safe integer, got ${n}`);\n}\nfunction anumArr(label, input) {\n if (!isArrayOf(false, input))\n throw new TypeError(`${label}: array of numbers expected`);\n}\nfunction chain(...args) {\n const id = (a) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a, b) => (c) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\nfunction normalize(fn) {\n afn(fn);\n return { encode: (from) => from, decode: (to) => fn(to) };\n}\nconst powers = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++)\n res.push(2 ** i);\n return res;\n})();\n// Indexed copy loops instead of Array.from / Uint8Array.from: those go through the\n// iterator protocol on typed arrays, which is ~10x slower and would swamp the fast\n// links' gains on the conversion boundaries.\nfunction u8ToNumArr(u8, len = u8.length) {\n const res = new Array(len);\n for (let i = 0; i < len; i++)\n res[i] = u8[i];\n return res;\n}\n// UTF-8 TextDecoder builds a string from ASCII codes 2x faster than `TextDecoder('latin1')`\n// (4x on freshly allocated, our exact case).\n// All codes here are < 128 (range is validated elsewhere): UTF-8 agrees with ASCII byte-for-byte.\n// UTF-8 needs no ICU, so the probe only guards runtimes without TextDecoder at all (Hermes).\nconst asciiDecoder = /* @__PURE__ */ (() => {\n try {\n const decoder = new TextDecoder();\n // Self-check on the domain we use (codes < 128): reject broken polyfills at\n // probe time instead of producing corrupted codec output later.\n return decoder.decode(Uint8Array.of(0x41, 0x30, 0x2b, 0x7f)) === 'A0+\\x7f'\n ? decoder\n : undefined;\n }\n catch (e) {\n return undefined;\n }\n})();\nconst B2S_CHUNK = 8192; // char codes per String.fromCharCode call, avoids arg-count limits\nfunction charcodesToString(codes) {\n const len = codes.length;\n // Measured crossover: the TextDecoder's per-call setup dominates below ~12 chars,\n // where String.fromCharCode wins (bech32 checksums, base58xmr blocks).\n if (asciiDecoder !== undefined && len >= 12)\n return asciiDecoder.decode(codes);\n if (len <= B2S_CHUNK)\n return String.fromCharCode.apply(null, codes);\n let res = '';\n for (let i = 0; i < len; i += B2S_CHUNK)\n res += String.fromCharCode.apply(null, codes.subarray(i, i + B2S_CHUNK));\n return res;\n}\n/**\n * Linear 8 <-> bits regrouping (radix2Slow semantics), with Uint8Array digits and\n * preallocated output.\n */\nfunction radix2(bits) {\n anumber(bits);\n if (bits <= 0 || bits > 8)\n throw new RangeError('radix2: bits should be in (0..8]');\n const mask = powers[bits] - 1;\n return {\n encode: (bytes) => {\n abytes(bytes);\n const len = bytes.length;\n // 8->bits with zero-bit padding of the last digit, like convertRadix2(padding=true)\n const res = new Uint8Array(Math.ceil((len * 8) / bits));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len;) {\n // At most 7 residual bits plus 24 new bits fit in the signed 32-bit carry.\n if (i + 2 < len) {\n carry = (carry << 24) | (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n pos += 24;\n i += 3;\n }\n else {\n // Constant mask instead of convertRadix2's exact powers[pos]-1 cleanup: with\n // bits <= 8 the residual is pos <= 7 bits, so carry needs at most pos + 8 <= 15\n // meaningful bits. Stale bits in [pos, 16) shift to >= bits on extraction and\n // are removed by `& mask` there and in the tail below.\n carry = ((carry << 8) | bytes[i]) & 0xffff;\n pos += 8;\n i++;\n }\n // Each input adds at least `bits`, so the first extraction is unconditional.\n for (;;) {\n pos -= bits;\n res[j++] = (carry >> pos) & mask;\n if (pos < bits)\n break;\n }\n }\n if (pos > 0)\n res[j] = (carry << (bits - pos)) & mask;\n return res;\n },\n decode: (digits) => {\n // bits->8, strict canonical form, like convertRadix2(padding=false):\n // rejects leftover whole input words and non-zero pad bits.\n const len = digits.length;\n const res = new Uint8Array(Math.floor((len * bits) / 8));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // Same constant-mask carry bound as encode: pos <= 7 residual plus bits <= 8\n // incoming keeps meaningful carry within 15 bits; stale bits above pos are\n // masked out on extraction and in the tail check below.\n carry = ((carry << bits) | digits[i]) & 0xffff;\n pos += bits;\n for (; pos >= 8; pos -= 8)\n res[j++] = (carry >> (pos - 8)) & 0xff;\n }\n carry = (carry << (8 - pos)) & 0xff;\n if (pos >= bits)\n throw new Error('Excess padding');\n if (carry > 0)\n throw new Error(`Non-zero padding: ${carry}`);\n return res;\n },\n };\n}\n/**\n * Digit <-> letter mapping fused with string join (chain(alphabetSlow(letters), join(''))\n * semantics), via char-code lookup tables.\n */\nfunction alphabet(letters, aliases) {\n const len = letters.length;\n // Larger indexes would wrap in the Int8Array reverse table and decode to wrong digits.\n if (len > 128)\n throw new Error('alphabet: max 128 letters');\n const encTable = new Uint8Array(len);\n const decTable = new Int8Array(128).fill(-1);\n for (let i = 0; i < len; i++) {\n const code = letters.charCodeAt(i);\n if (letters.codePointAt(i) !== code || code > 127)\n throw new Error('alphabet: single-char ASCII letters only');\n encTable[i] = code;\n decTable[code] = i;\n }\n // Aliases decode like their canonical letter (e.g. hex case-folding), without a\n // separate normalization pass over the input string.\n if (aliases !== undefined) {\n for (const alias of Object.keys(aliases)) {\n const code = alias.charCodeAt(0);\n const target = decTable[aliases[alias].charCodeAt(0)];\n if (alias.length !== 1 || code > 127 || target === undefined || target === -1)\n throw new Error(`alphabet: invalid alias ${alias}`);\n decTable[code] = target;\n }\n }\n return {\n encode: (digits) => {\n const codes = new Uint8Array(digits.length);\n for (let i = 0; i < digits.length; i++) {\n const d = digits[i];\n const code = encTable[d];\n // Reuse the table lookup's bounds result for the required per-digit range check.\n // Chained radix2 always emits digits < 2**bits === len; check anyway so a\n // mismatched chain throws (like alphabetSlow) instead of silently emitting letter 0.\n if (code === undefined)\n throw new Error(`alphabet.encode: invalid digit ${d}`);\n codes[i] = code;\n }\n return charcodesToString(codes);\n },\n decode: (input) => {\n // Uniform label: this is the decode entry link for nopad codecs, padding for padded\n // ones. Keeps \"decode: string expected\" identical across all built-in codecs\n // (released 2.x said \"join.decode: string expected\").\n astr('decode', input);\n const slen = input.length;\n const digits = new Uint8Array(slen);\n for (let i = 0; i < slen; i++) {\n const code = input.charCodeAt(i);\n const digit = code < 128 ? decTable[code] : -1;\n if (digit === -1)\n throw new Error(`Unknown letter \"${input[i]}\". Allowed: ${letters}`);\n digits[i] = digit;\n }\n return digits;\n },\n };\n}\n/**\n * Pad / unpad (paddingSlow semantics), on the joined string.\n */\nfunction padding(bits, chr = '=') {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data) {\n while ((data.length * bits) % 8)\n data += chr;\n return data;\n },\n decode(input) {\n // Uniform label, see alphabet.decode above.\n astr('decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid length');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const byte = (end - 1) * bits;\n if (byte % 8 === 0)\n throw new Error('padding: excess padding');\n }\n return input.slice(0, end);\n },\n };\n}\nfunction unsafeWrapper(fn) {\n afn(fn);\n return function (...args) {\n // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n // Do not wrap code that needs to preserve exception details.\n try {\n return fn.apply(null, args);\n }\n catch (e) { }\n };\n}\nfunction checksum(len, fn) {\n anumber(len);\n // Reject degenerate zero-byte checksums up front so callers don't accidentally\n // build a no-op checksum stage.\n if (len <= 0)\n throw new RangeError(`checksum length must be positive: ${len}`);\n afn(fn);\n const _fn = fn;\n // Uses the first `len` bytes of fn(data) in both directions.\n // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n return {\n encode(data) {\n abytes(data);\n const sum = _fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data) {\n abytes(data);\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = _fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i])\n throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n// RFC 4648 aka RFC 3548\n// ---------------------\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 \u00A78 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16 = /* @__PURE__ */ freeze(() => chain(radix2(4), alphabet('0123456789ABCDEF')));\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 \u00A76 Table 3 uses uppercase letters, and RFC 4648 \u00A73.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32 = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')));\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 \u00A77 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5)));\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV')));\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford = /* @__PURE__ */ freeze(() => chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), normalize((s) => {\n astr('base32crockford.decode', s);\n return s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1');\n})));\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' &&\n typeof Uint8Array.fromBase64 === 'function')();\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 \u00A73.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\nconst decodeBase64Builtin = (s, isUrl) => {\n astr('base64', s);\n const alphabet = isUrl ? 'base64url' : 'base64';\n // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n // And checking just for whitespace makes decoding about 3x faster than a full range check.\n // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n if (s.length > 0 && ASCII_WHITESPACE.test(s))\n throw new Error('invalid base64');\n return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n/** base64 from RFC 4648. Padded. Pure JS version */\nconst base64Fallback = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6)));\n/**\n * base64 from RFC 4648. Padded.\n * Alternative variants: `base64nopad`, `base64url`, `base64urlnopad`.\n * Utilizes native `Uint8Array.fromBase64` builtin, otherwise falls back to `base64fallback` when it's unavailable.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64 = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : base64Fallback);\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url = /* @__PURE__ */ freeze(() => hasBase64Builtin ? {\n encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6)));\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad = /* @__PURE__ */ freeze(() => chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_')));\n// base58 code\n// -----------\n// Base conversion 256 <-> 58 done on 16-bit limbs, five base58 digits (one divmod by\n// 58**5) per pass, ~10x fewer inner-loop iterations than digit-at-a-time conversion.\n// Exactness: every intermediate is a non-negative integer below 2**53, so float64\n// arithmetic (including Math.floor of the quotients) is exact:\n// - encode: carry * 2**16 + limb < 58**5 * 2**16 < 2**46\n// - decode: limb * 58**5 + carry < 2**16 * 58**5 + 2**30 < 2**46\n// Still O(n^2) overall like any positional-base conversion \u2014 see the base58 DoS note.\nconst B58_GROUP = 656356768; // 58**5 < 2**30; literal (not `58 ** 5`) so bundlers can drop it as dead code\nconst radix58 = {\n encode: (bytes) => {\n abytes(bytes);\n const blen = bytes.length;\n if (blen === 0)\n return new Uint8Array(0);\n // Leading zero bytes map 1:1 to leading zero digits (at most blen-1 explicit zeros;\n // an all-zero value still contributes one digit below).\n let zeros = 0;\n while (zeros < blen - 1 && bytes[zeros] === 0)\n zeros++;\n // Pack big-endian 16-bit limbs; odd length makes the top limb a single byte.\n const nlimbs = Math.ceil(blen / 2);\n const limbs = new Uint16Array(nlimbs);\n const odd = blen & 1;\n if (odd)\n limbs[0] = bytes[0];\n for (let i = odd, j = odd; i < blen; i += 2, j++)\n limbs[j] = (bytes[i] << 8) | bytes[i + 1];\n // Repeated divmod by 58**5; each pass emits one 5-digit group, least significant\n // first. No carry-overflow guard like convertRadix had: that one faced arbitrary\n // caller-chosen bases, while these bounds are static and proven exact above.\n const groups = [];\n let pos = 0; // limbs before pos are known zero\n while (pos < nlimbs) {\n let carry = 0;\n for (let i = pos; i < nlimbs; i++) {\n const cur = carry * 0x10000 + limbs[i];\n const q = Math.floor(cur / B58_GROUP);\n carry = cur - q * B58_GROUP;\n limbs[i] = q;\n if (q === 0 && i === pos)\n pos++;\n }\n groups.push(carry);\n }\n // The top group is nonzero unless the whole value is zero, so total significant\n // digit count is 5 per full group plus the top group's own width. (Writing 5 digits\n // per group and trimming via subarray is smaller code, but the offset view slows\n // encode ~25% and base58xmr 2x \u2014 measured.)\n const top = groups.length - 1;\n let sig = top * 5;\n for (let v = groups[top];; v = Math.floor(v / 58)) {\n sig++;\n if (v < 58)\n break;\n }\n const res = new Uint8Array(zeros + sig); // leading zero digits are already 0\n let j = res.length - 1;\n for (let g = 0; g < top; g++) {\n let v = groups[g];\n for (let k = 0; k < 5; k++) {\n res[j--] = v % 58;\n v = Math.floor(v / 58);\n }\n }\n for (let v = groups[top]; j >= zeros; v = Math.floor(v / 58))\n res[j--] = v % 58;\n return res;\n },\n decode: (digits) => {\n abytes(digits);\n const dlen = digits.length;\n if (dlen === 0)\n return new Uint8Array(0);\n if (dlen >= 65536)\n throw new Error('invalid length');\n let zeros = 0;\n while (zeros < dlen - 1 && digits[zeros] === 0)\n zeros++;\n // Multiply-accumulate 16-bit limbs (little-endian, `used` live) group by group,\n // most significant group first; the first group may be shorter than 5 digits, and\n // its 58**group factor falls out of the digit fold.\n const limbs = new Uint16Array(Math.ceil((dlen * 6) / 16) + 1);\n let used = 0;\n let i = 0;\n let group = dlen % 5 || 5;\n while (i < dlen) {\n let gval = 0;\n let factor = 1;\n for (const end = i + group; i < end; i++) {\n const d = digits[i];\n // Unreachable through the public chain (alphabet emits digits < 58); guards\n // internal misuse from silently corrupting output.\n if (d >= 58)\n throw new Error(`invalid integer: ${d}`);\n gval = gval * 58 + d;\n factor *= 58;\n }\n group = 5;\n let carry = gval;\n for (let k = 0; k < used; k++) {\n const cur = limbs[k] * factor + carry;\n carry = Math.floor(cur / 0x10000);\n limbs[k] = cur - carry * 0x10000;\n }\n for (; carry > 0; carry = Math.floor(carry / 0x10000))\n limbs[used++] = carry % 0x10000;\n }\n // used === 0 means the value is zero: it still contributes one byte, like a lone\n // zero digit does.\n const valueBytes = used === 0 ? 1 : used * 2 - (limbs[used - 1] < 256 ? 1 : 0);\n const res = new Uint8Array(zeros + valueBytes); // leading zero bytes are already 0\n let j = res.length - 1;\n for (let k = 0; k < used; k++) {\n const limb = limbs[k];\n res[j--] = limb & 0xff;\n if (j >= zeros)\n res[j--] = limb >> 8;\n }\n return res;\n },\n};\nconst genBase58 = (abc) => chain(radix58, alphabet(abc));\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58 = /* @__PURE__ */ freeze(() => genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'));\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr = /* @__PURE__ */ freeze(() => genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'));\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp = /* @__PURE__ */ freeze(() => genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz'));\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1');\n }\n return res;\n },\n decode(str) {\n astr('base58xmr.decode', str);\n const strLen = str.length;\n // Only the last block may be short, and only to one of the XMR_BLOCK_LEN widths \u2014\n // so the output length is known up front and blocks write into place. Growing a\n // number[] via concat per block was quadratic; this keeps decode linear like the\n // block encoding always intended.\n const tailChars = strLen % 11;\n const tailBytes = tailChars === 0 ? 0 : XMR_BLOCK_LEN.indexOf(tailChars);\n if (tailBytes === -1)\n throw new Error(`base58xmr: invalid block length ${tailChars}`);\n const res = new Uint8Array(Math.floor(strLen / 11) * 8 + tailBytes);\n let w = 0;\n for (let i = 0; i < strLen; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = slice.length === 11 ? 8 : tailBytes;\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0)\n throw new Error('base58xmr: wrong padding');\n }\n for (let j = block.length - blockLen; j < block.length; j++)\n res[w++] = block[j];\n }\n return res;\n },\n}));\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256) => {\n // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n afn(sha256);\n const _sha256 = sha256;\n return chain(checksum(4, (data) => _sha256(_sha256(data))), base58);\n};\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check = createBase58check;\n// BIP 173 character table.\n// Callers adapt the public number[] words API to Uint8Array at the edges (wordsToU8 below):\n// feeding number[] into alphabet.encode would work at runtime, but it turns the shared\n// hot loop polymorphic and measurably slows the RFC 4648 codecs using the same literal.\nconst BECH_ALPHABET = /* @__PURE__ */ alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l');\n// Range-checks while packing: a plain copy would silently wrap out-of-range words\n// (256 -> 0 would encode to a valid letter). Same message the old slow alphabet threw.\nfunction wordsToU8(words) {\n const len = words.length;\n const res = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = words[i];\n if (w < 0 || w >= 32)\n throw new Error(`alphabet.encode: invalid digit ${w}`);\n res[i] = w;\n }\n return res;\n}\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre) {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1)\n chk ^= POLYMOD_GENERATORS[i];\n }\n return chk;\n}\nfunction bechChecksum(prefix, words, encodingConst = 1) {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126)\n throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++)\n chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words)\n chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++)\n chk = bech32Polymod(chk);\n // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n chk ^= encodingConst;\n const sum = new Uint8Array(6);\n for (let i = 0; i < 6; i++)\n sum[i] = (chk >>> (5 * (5 - i))) & 31;\n return BECH_ALPHABET.encode(sum);\n}\nfunction genBech32(encoding) {\n // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n // Public API words are number[], so adapt the fast radix2's Uint8Array protocol at the edge.\n const _words = radix2(5);\n const toWords = (from) => {\n abytes(from);\n // Dedicated 8->5 regrouping (radix2(5).encode semantics) writing the public number[]\n // directly; encode-into-Uint8Array plus a copy loop measurably regressed this hot path.\n const len = from.length;\n const res = new Array(Math.ceil((len * 8) / 5));\n let carry = 0;\n let pos = 0;\n let j = 0;\n for (let i = 0; i < len; i++) {\n // No carry cleanup needed: stale bits sit above pos and every extraction (including\n // the tail below) masks with `& 31`, so they never reach the output. Masking carry\n // here measurably slowed the loop.\n carry = (carry << 8) | from[i];\n pos += 8;\n for (; pos >= 5; pos -= 5)\n res[j++] = (carry >> (pos - 5)) & 31;\n }\n if (pos > 0)\n res[j] = (carry << (5 - pos)) & 31;\n return res;\n };\n const fromWords = (to) => {\n anumArr('radix2.decode', to);\n // Range-check while packing into the byte buffer: a plain copy would silently\n // truncate out-of-range words. Rejecting negatives is a deliberate fix \u2014 the old\n // convertRadix2 path silently corrupted output for them.\n const len = to.length;\n const digits = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n const w = to[i];\n if (w < 0 || w >= 32)\n throw new Error(`convertRadix2: invalid word=${w}`);\n digits[i] = w;\n }\n return _words.decode(digits);\n };\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n function encode(prefix, words, limit = 90) {\n astr('bech32.encode prefix', prefix);\n if (limit !== false)\n anumber(limit, 'limit');\n if (isBytes(words))\n words = u8ToNumArr(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0)\n throw new TypeError(`Invalid prefix length ${plen}`);\n // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(wordsToU8(words))}${sum}`;\n }\n function decode(str, limit = 90) {\n astr('bech32.decode input', str);\n if (limit !== false)\n anumber(limit, 'limit');\n const slen = str.length;\n // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length ${slen}, expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`mixed-case string not allowed`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`invalid separator \"1\"`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6)\n throw new Error('invalid data length');\n const digits = BECH_ALPHABET.decode(data);\n const words = u8ToNumArr(digits, digits.length - 6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum))\n throw new Error(`Invalid checksum in ${str}`);\n return { prefix, words };\n }\n const decodeUnsafe = unsafeWrapper(decode);\n function decodeToBytes(str) {\n // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n const { prefix, words } = decode(str, false);\n return {\n prefix,\n words,\n bytes: fromWords(words),\n };\n }\n function encodeFromBytes(prefix, bytes) {\n // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n return encode(prefix, toWords(bytes));\n }\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32 = /* @__PURE__ */ freeze(() => genBech32('bech32'));\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m = /* @__PURE__ */ freeze(() => genBech32('bech32m'));\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n for (let i = 0; i < data.length; i++) {\n const byte = data[i];\n // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n // Latin-1/UTF-8. Validating up front keeps the error position exact while the\n // string itself is built in bulk (~3x faster at 1KB than per-char concat).\n if (byte > 127)\n throw new RangeError(`non-ASCII byte ${byte} at ${i}`);\n }\n return charcodesToString(data);\n },\n decode(str) {\n if (typeof str !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof str);\n const res = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n // exact error positions.\n const charCode = str.charCodeAt(i);\n if (charCode > 127)\n throw new RangeError(`non-ASCII char \"${str[i]}\" (${charCode}) at ${i}`);\n res[i] = charCode;\n }\n return res;\n },\n}));\nconst _isWellFormedShim = (str) => {\n // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n // isWellFormed on our tests/fuzz corpus.\n try {\n return encodeURI(str) !== null;\n }\n catch {\n return false;\n }\n};\nconst _isWellFormed = /* @__PURE__ */ (() => \n// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\ntypeof ''.isWellFormed === 'function'\n ? (str) => str.isWellFormed()\n : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8err = (i) => new TypeError(`invalid utf8 at byte ${i}`);\nconst utf8Fallback = /* @__PURE__ */ freeze(() => ({\n encode(data) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length;) {\n const a = data[i++];\n if (a < 0b1000_0000) {\n res += String.fromCharCode(a);\n continue;\n }\n if (a < 0b1100_0010 || i >= data.length)\n throw utf8err(i - 1);\n const b = data[i++];\n if ((b & 0b1100_0000) !== 0b1000_0000)\n throw utf8err(i - 1);\n let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n if (a >= 0b1110_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const c = data[i++];\n if ((c & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1110_0000 && b < 0b1010_0000) ||\n (a === 0xed && b >= 0b1010_0000))\n throw utf8err(i - 1);\n cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n if (a >= 0b1111_0000) {\n if (i >= data.length)\n throw utf8err(i - 1);\n const d = data[i++];\n if (a > 0b1111_0100 ||\n (d & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1111_0000 && b < 0b1001_0000) ||\n (a === 0b1111_0100 && b >= 0b1001_0000))\n throw utf8err(i - 1);\n cp =\n ((a & 7) << 18) |\n ((b & 0b0011_1111) << 12) |\n ((c & 0b0011_1111) << 6) |\n (d & 0b0011_1111);\n }\n }\n if (cp < 0x10000)\n res += String.fromCharCode(cp);\n else {\n cp -= 0x10000;\n res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n }\n }\n return res;\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n // large Node inputs.\n const res = new Uint8Array(str.length * 3);\n let pos = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0b1000_0000) {\n res[pos++] = c;\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n const d = str.charCodeAt(++i);\n c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n }\n if (c >= 0x10000) {\n res[pos++] = (c >> 18) | 0b1111_0000;\n res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n }\n else if (c >= 0x800)\n res[pos++] = (c >> 12) | 0b1110_0000;\n else\n res[pos++] = (c >> 6) | 0b1100_0000;\n if (c >= 0x800)\n res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n }\n return res.subarray(0, pos);\n },\n}));\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n * throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n * lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8 = /* @__PURE__ */ freeze(() => {\n let _utf8Encoder;\n let _utf8Decoder;\n const utf8Builtin = {\n // ignoreBOM preserves an explicit leading U+FEFF;\n // fatal rejects invalid UTF-8 bytes instead of replacing them.\n encode(data) {\n abytes(data);\n return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data);\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str))\n throw new TypeError('utf8 expected well-formed string');\n return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n },\n };\n return {\n // Select each direction once at module init, since\n // TextEncoder and TextDecoder can exist independently.\n encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n };\n});\n// Keep internal parity probes behind a test-only export.\nexport const __TESTS = /* @__PURE__ */ freeze(() => ({\n alphabet: alphabet,\n base64Fallback: base64Fallback,\n radix2: radix2,\n radix58: radix58,\n checksum: checksum,\n utf8Fallback: utf8Fallback,\n _isWellFormedShim: _isWellFormedShim,\n}));\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// Require both directions before enabling the native hex path so encode/decode stay symmetric.\ntypeof Uint8Array.from([]).toHex === 'function' &&\n typeof Uint8Array.fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin = {\n // Keep local type guards so the native path preserves library-level input errors.\n // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n encode(data) { abytes(data); return data.toHex(); },\n // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n decode(s) { astr('hex', s); return Uint8Array.fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex = /* @__PURE__ */ freeze(() => hasHexBuiltin\n ? hexBuiltin\n : chain(radix2(4), \n // Case-insensitive decode via table aliases instead of a toLowerCase pass.\n alphabet('0123456789abcdef', { A: 'a', B: 'b', C: 'c', D: 'd', E: 'e', F: 'f' }), normalize((s) => {\n // astr first: same non-string message as the native path, and no `s.length`\n // access on null / undefined while building the error.\n astr('hex', s);\n if (s.length % 2 !== 0)\n throw new TypeError(`hex.decode: odd-length string (${s.length})`);\n return s;\n })));\n", "/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from \"./hmac.js\";\n// prettier-ignore\nimport { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from \"./utils.js\";\n// Common validation and per-call state setup for sync/async functions.\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1)\n throw new Error('\"c\" (iterations) must be >= 1');\n // RFC 8018 \u00A75.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1)\n throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 \u00A75.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen)\n throw new Error('derived key too long');\n const p = kdfInputToBytes(_password, 'password');\n const s = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n const { iHash, oHash, outputLen } = hmac.create(hash, p);\n // Drive keyed hashes directly; the wrapper is only needed to initialize their HMAC midstates.\n const u = new Uint8Array(outputLen);\n const eng = pbkdf2Engine(iHash, oHash, s, u);\n return { c, dkLen, asyncTick, DK, outputLen, eng };\n}\n// Per-call PRF driver writes U1 into both `u` and `Ti`, then later digests into `u`;\n// shared by the sync and async variants.\nfunction pbkdf2Engine(iHash, oHash, salt, u) {\n const counter = new Uint8Array(4);\n const view = createView(counter);\n // Full clones retain tree/config state; absorb salt before async yields without cloning input.\n const salted = iHash._cloneInto().update(salt);\n // u1() overwrites the worker before reading it. Seed from the outer midstate so a long salt\n // cannot pre-populate a tree stack that the first reset would abandon without wiping.\n const work = oHash._cloneInto();\n const iClone = iHash._cloneInto; // Capture before mixed feedback can materialize state tuples.\n const oClone = oHash._cloneInto;\n return {\n u1: (ti, Ti) => {\n view.setInt32(0, ti, false);\n salted._cloneInto(work).update(counter).digestInto(u);\n oHash._cloneInto(work).update(u).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n },\n // Whole `F` inner loop for the sync variant: one optimized function owns the hot loop.\n rounds: (c, Ti) => {\n for (let ui = 1; ui < c; ui++) {\n iClone.call(iHash, work).update(u).digestInto(u);\n oClone.call(oHash, work).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n },\n output: (DK) => {\n // Keyed templates and derived worker states are secret material.\n iHash.destroy();\n oHash.destroy();\n salted.destroy();\n work.destroy();\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n clean(u);\n return DK;\n },\n };\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n // Uc = PRF(Password, Uc\u22121); Ti ^= Uc\n eng.rounds(c, Ti);\n }\n return eng.output(DK);\n}\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n * @example\n * Tune the async PBKDF2 scheduler for short UI tasks.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', {\n * dkLen: 32,\n * c: 32,\n * asyncTick: 1,\n * });\n * ```\n */\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, outputLen, eng } = pbkdf2Init(hash, password, salt, opts);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + outputLen);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n eng.u1(ti, Ti);\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc\u22121)\n eng.rounds(2, Ti); // c=2 runs exactly one PRF iteration per callback.\n });\n }\n return eng.output(DK);\n}\n", "/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\n// Japanese wordlist\n// The canonical BIP-39 Japanese wordlist starts with \u3042\u3044\u3053\u304F\u3057\u3093.\n// Use that sentinel so generated phrases use U+3000 ideographic spaces.\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\n// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.\n// It also applies NFKD to the \"mnemonic\" + passphrase salt.\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\n// BIP-39 mnemonics are consumed in NFKD form.\n// They must contain 12, 15, 18, 21, or 24 words before checksum validation.\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\n// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new RangeError('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist - Imported wordlist for a specific language.\n * @param strength - Mnemonic strength, from 128 to 256 bits.\n * @returns 12-24 word mnemonic phrase.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new English mnemonic.\n * ```ts\n * import { generateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnemonic = generateMnemonic(wordlist, 128);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new RangeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\n// BIP-39 checksum is the first ENT/32 bits of SHA-256(entropy).\n// Returned as a byte with checksum bits on the left and zeroes on the right.\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return (sha256(entropy)[0] >> bitsLeft) << bitsLeft;\n};\nfunction awordlist(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new TypeError('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new TypeError('wordlist: non-string element: ' + i);\n });\n}\n// BIP-39 appends checksum bits to entropy,\n// then splits the bitstream into 11-bit indexes for a 2048-word list.\nfunction encodeWords(entropy, wordlist) {\n awordlist(wordlist);\n const bytes = new Uint8Array(entropy.length + 1); // entropy || checksum byte\n bytes.set(entropy);\n bytes[entropy.length] = calcChecksum(entropy);\n const words = [];\n let carry = 0; // bit accumulator, holds < 19 bits\n let bits = 0;\n for (const byte of bytes) {\n carry = (carry << 8) | byte;\n bits += 8;\n if (bits >= 11) {\n bits -= 11;\n words.push(wordlist[(carry >>> bits) & 0x7ff]);\n carry &= (1 << bits) - 1;\n }\n }\n // Bits still in carry are the zero right bits of the checksum byte; drop them.\n return words;\n}\n// Reverse of encodeWords: repacks 11-bit indexes into bytes and verifies checksum.\nfunction decodeWords(words, wordlist) {\n awordlist(wordlist);\n const entLen = (words.length / 3) * 4; // every 3 words hold 32 entropy bits + 1 checksum bit\n const bytes = new Uint8Array(entLen + 1); // entropy || checksum byte\n let carry = 0; // bit accumulator, holds < 19 bits\n let bits = 0;\n let pos = 0;\n for (const word of words) {\n const index = wordlist.indexOf(word);\n if (index === -1)\n throw new Error('Unknown word: ' + word);\n carry = (carry << 11) | index;\n bits += 11;\n while (bits >= 8) {\n bits -= 8;\n bytes[pos++] = (carry >>> bits) & 0xff;\n }\n carry &= (1 << bits) - 1;\n }\n // Left-align leftover checksum bits, matching calcChecksum output.\n if (bits > 0)\n bytes[pos] = carry << (8 - bits);\n const entropy = bytes.subarray(0, entLen);\n if (bytes[entLen] !== calcChecksum(entropy))\n throw new Error('Invalid checksum');\n return Uint8Array.from(entropy);\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns Raw entropy bytes.\n * @throws If the mnemonic shape or checksum is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode a mnemonic back into its original entropy bytes.\n * ```ts\n * import { mnemonicToEntropy } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const entropy = mnemonicToEntropy(mnem, wordlist);\n * // Produces the original 16-byte entropy payload.\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n * ```\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = decodeWords(words, wordlist);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy - Byte array.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns 12-24 words.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Convert raw entropy into an English mnemonic.\n * ```ts\n * import { entropyToMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * const mnemonic = entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = encodeWords(entropy, wordlist);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns `true` when mnemonic checksum and words are valid.\n * @example\n * Validate one English mnemonic.\n * ```ts\n * import { validateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ok = validateMnemonic(\n * 'legal winner thank year wave sausage worth useful legal winner thank yellow',\n * wordlist\n * );\n * // => true\n * ```\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\n// BIP-39 salts PBKDF2 with the UTF-8 NFKD string \"mnemonic\" + passphrase.\nconst psalt = (passphrase) => {\n if (typeof passphrase !== 'string')\n throw new TypeError('invalid passphrase type: ' + typeof passphrase);\n return nfkd('mnemonic' + passphrase);\n};\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the async PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeed(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\n// BIP-39 seed derivation is independent from mnemonic generation.\n// These helpers normalize the phrase but do not verify checksum or wordlist membership.\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the sync PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = mnemonicToSeedSync(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed with the native WebCrypto PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n", "/** English BIP39 wordlist. */\nexport const wordlist = /* @__PURE__ */ Object.freeze(`abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n'));\n", "/**\n * BIP32 Hierarchical Deterministic (HD) wallet derivation\n * \n * Implements standard Bitcoin wallet derivation (BIP32/BIP44/BIP84)\n * for ECDSA secp256k1 keys.\n * \n * Supports:\n * - BIP39 mnemonic → seed conversion\n * - BIP32 path derivation (e.g., \"m/44'/0'/0'/0/0\")\n * - Standard Bitcoin wallet paths\n * \n * References:\n * - BIP32: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki\n * - BIP39: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki\n * - BIP44: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki\n */\n\nimport { HDKey } from '@scure/bip32';\nimport {\n mnemonicToSeedSync,\n validateMnemonic,\n generateMnemonic as generateBIP39Mnemonic,\n} from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english.js';\nimport type { DerivationCapability, DerivationContext, Keypair } from '../types.js';\n\n/**\n * BIP32 derivation implementation for HD wallets.\n * \n * Usage:\n * ```typescript\n * const derivation = new BIP32Derivation();\n * \n * // From mnemonic\n * const mnemonic = \"abandon abandon abandon...\";\n * const keypair = await derivation.deriveKeypair({\n * seed: derivation.mnemonicToSeed(mnemonic),\n * path: \"m/44'/0'/0'/0/0\"\n * });\n * \n * // From existing seed\n * const keypair = await derivation.deriveKeypair({\n * seed: myExistingSeed,\n * path: \"m/44'/0'/0'/0/1\"\n * });\n * ```\n */\nexport class BIP32Derivation implements DerivationCapability {\n /**\n * Derive a keypair from BIP32 path.\n * \n * @param context Must include `seed` and `path`\n * @returns Secp256k1 keypair (compressed public key)\n * @throws If seed or path is missing, or path is invalid\n */\n async deriveKeypair(context: DerivationContext): Promise<Keypair> {\n if (!context.seed) {\n throw new Error('BIP32 derivation requires a seed');\n }\n \n if (!context.path) {\n throw new Error('BIP32 derivation requires a path (e.g., \"m/44\\'/0\\'/0\\'/0/0\")');\n }\n \n try {\n // Create HD key from seed\n const masterKey = HDKey.fromMasterSeed(context.seed);\n \n // Derive child key at path\n const childKey = masterKey.derive(context.path);\n \n if (!childKey.privateKey) {\n throw new Error(`Failed to derive private key at path ${context.path}`);\n }\n \n if (!childKey.publicKey) {\n throw new Error(`Failed to derive public key at path ${context.path}`);\n }\n \n return {\n privateKey: childKey.privateKey,\n publicKey: childKey.publicKey, // Already compressed (33 bytes)\n };\n } catch (error) {\n throw new Error(\n `BIP32 derivation failed at path ${context.path}: ${\n error instanceof Error ? error.message : String(error)\n }`\n );\n }\n }\n \n /**\n * Convert BIP39 mnemonic to BIP32 seed.\n * \n * @param mnemonic 12, 15, 18, 21, or 24 word mnemonic\n * @param passphrase Optional BIP39 passphrase\n * @returns 64-byte seed suitable for BIP32\n */\n mnemonicToSeed(mnemonic: string, passphrase?: string): Uint8Array {\n // mnemonicToSeedSync does not check the words or the checksum: any string\n // of the right word count yields a seed. A single mistyped word would\n // silently derive a different wallet, so validate first.\n if (typeof mnemonic !== 'string' || !validateMnemonic(mnemonic, wordlist)) {\n throw new Error(\n 'Invalid BIP39 mnemonic: unknown word, wrong word count, or checksum mismatch'\n );\n }\n return mnemonicToSeedSync(mnemonic, passphrase);\n }\n \n /**\n * Generate a new BIP39 mnemonic.\n * \n * @param strength Entropy bits: 128 (12 words), 256 (24 words), etc.\n * @returns Space-separated mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n return generateBIP39Mnemonic(wordlist, strength);\n }\n \n /**\n * Standard BIP44 path for Bitcoin.\n * \n * @param account Account index (default: 0)\n * @param change 0 = external (receive), 1 = internal (change)\n * @param index Address index\n * @returns BIP44 path string\n */\n static bitcoinPath(account = 0, change = 0, index = 0): string {\n return `m/44'/0'/${account}'/${change}/${index}`;\n }\n \n /**\n * BIP44 path for an explicit SLIP-44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type decides which wallets will find the keys again: Bitcoin\n * (BTC) is 0, Bitcoin SV is 236. There is deliberately no default.\n */\n static bip44Path(coinType: number, account = 0, change = 0, index = 0): string {\n for (const [name, v] of Object.entries({ coinType, account, change, index })) {\n if (!Number.isInteger(v) || v < 0 || v > 0x7fffffff) {\n throw new Error(`BIP44 ${name} must be an integer in [0, 2^31 - 1], got ${String(v)}`);\n }\n }\n if (change !== 0 && change !== 1) {\n throw new Error(`BIP44 change must be 0 (external) or 1 (internal), got ${change}`);\n }\n return `m/44'/${coinType}'/${account}'/${change}/${index}`;\n }\n\n /**\n * Standard BIP84 path for Bitcoin SegWit (native).\n * \n * @param account Account index (default: 0)\n * @param change 0 = external (receive), 1 = internal (change)\n * @param index Address index\n * @returns BIP84 path string\n */\n static bitcoinSegWitPath(account = 0, change = 0, index = 0): string {\n return `m/84'/0'/${account}'/${change}/${index}`;\n }\n}\n", "/**\n * Bitcoin WIF (Wallet Import Format) utilities\n * \n * Encodes/decodes private keys in Bitcoin's standard format.\n * Supports both compressed and uncompressed formats.\n * \n * Reference: https://en.bitcoin.it/wiki/Wallet_import_format\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\n\n// Base58 alphabet (Bitcoin)\nconst BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/**\n * Encode bytes to Base58.\n */\nfunction base58Encode(data: Uint8Array): string {\n let num = 0n;\n for (const byte of data) {\n num = num * 256n + BigInt(byte);\n }\n \n let encoded = '';\n while (num > 0n) {\n const remainder = Number(num % 58n);\n encoded = BASE58_ALPHABET[remainder] + encoded;\n num = num / 58n;\n }\n \n // Preserve leading zeros\n for (const byte of data) {\n if (byte !== 0) break;\n encoded = '1' + encoded;\n }\n \n return encoded;\n}\n\n/**\n * Decode Base58 string to bytes.\n */\nfunction base58Decode(str: string): Uint8Array {\n let num = 0n;\n for (const char of str) {\n const index = BASE58_ALPHABET.indexOf(char);\n if (index === -1) {\n throw new Error(`Invalid Base58 character: ${char}`);\n }\n num = num * 58n + BigInt(index);\n }\n \n // Convert to bytes\n const bytes: number[] = [];\n while (num > 0n) {\n bytes.unshift(Number(num % 256n));\n num = num / 256n;\n }\n \n // Preserve leading zeros\n for (const char of str) {\n if (char !== '1') break;\n bytes.unshift(0);\n }\n \n return new Uint8Array(bytes);\n}\n\n/**\n * Encode a private key to WIF format.\n * \n * @param privateKey 32-byte private key\n * @param compressed Whether to indicate compressed public key (default: true)\n * @param network 'mainnet' or 'testnet' (default: 'mainnet')\n * @returns WIF-encoded private key string\n */\nexport function encodeWIF(\n privateKey: Uint8Array,\n compressed = true,\n network: 'mainnet' | 'testnet' = 'mainnet'\n): string {\n if (privateKey.length !== 32) {\n throw new Error('Private key must be 32 bytes');\n }\n \n // Version byte: 0x80 for mainnet, 0xEF for testnet\n const version = network === 'mainnet' ? 0x80 : 0xEF;\n \n // Build payload: version + key + (optional compression flag)\n const payload = new Uint8Array(compressed ? 34 : 33);\n payload[0] = version;\n payload.set(privateKey, 1);\n if (compressed) {\n payload[33] = 0x01; // Compression flag\n }\n \n // Checksum: first 4 bytes of double SHA256\n const hash1 = sha256(payload);\n const hash2 = sha256(hash1);\n const checksum = hash2.slice(0, 4);\n \n // Combine payload + checksum\n const data = new Uint8Array(payload.length + 4);\n data.set(payload);\n data.set(checksum, payload.length);\n \n return base58Encode(data);\n}\n\n/**\n * Decode a WIF-encoded private key.\n * \n * @param wif WIF string\n * @returns Object with privateKey, compressed flag, and network\n * @throws If WIF is invalid or checksum fails\n */\nexport function decodeWIF(wif: string): {\n privateKey: Uint8Array;\n compressed: boolean;\n network: 'mainnet' | 'testnet';\n} {\n const data = base58Decode(wif);\n \n if (data.length !== 37 && data.length !== 38) {\n throw new Error('Invalid WIF length');\n }\n \n // Extract checksum\n const payload = data.slice(0, -4);\n const checksum = data.slice(-4);\n \n // Verify checksum\n const hash1 = sha256(payload);\n const hash2 = sha256(hash1);\n const expectedChecksum = hash2.slice(0, 4);\n \n if (!checksum.every((byte, i) => byte === expectedChecksum[i])) {\n throw new Error('Invalid WIF checksum');\n }\n \n // Extract version\n const version = payload[0];\n const network = version === 0x80 ? 'mainnet' : version === 0xEF ? 'testnet' : null;\n if (!network) {\n throw new Error(`Invalid WIF version byte: 0x${version.toString(16)}`);\n }\n \n // Extract private key and compression flag\n const compressed = payload.length === 34 && payload[33] === 0x01;\n const privateKey = payload.slice(1, 33);\n \n return {\n privateKey,\n compressed,\n network,\n };\n}\n", "import * as secp256k1 from '@noble/secp256k1';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { SignatureSuite, Keypair, SignOptions } from '../types.js';\nimport { bytesToHex, hexToBytes, bytesToBase64Url, base64UrlToBytes } from '../utils.js';\nimport { BIP32Derivation } from '../derivation/bip32.js';\nimport { encodeWIF, decodeWIF } from '../derivation/wif.js';\n\n// Wire the synchronous hashes @noble/secp256k1 v3 needs. v2 took a single\n// `etc.hmacSha256Sync`; v3 replaced it with a `hashes` object and also requires sha256,\n// because RFC 6979 nonce derivation and the optional message prehash both go through it.\nsecp256k1.hashes.sha256 = (msg: Uint8Array) => sha256(msg);\nsecp256k1.hashes.hmacSha256 = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n\n/** A secp256k1 secret key must be a scalar in [1, n - 1]. */\nfunction assertValidSecretKey(bytes: Uint8Array): void {\n if (!secp256k1.utils.isValidSecretKey(bytes)) {\n throw new Error('Private key is not a valid secp256k1 scalar');\n }\n}\n\n/**\n * BSV ECDSA signature suite using secp256k1\n * Compatible with Bitcoin SV / smartledger-bsv\n * \n * Supports BIP32 HD wallet derivation for deterministic key generation.\n */\nexport class BsvEcdsaSuite implements SignatureSuite {\n readonly suiteId = 'bsv-ecdsa-secp256k1';\n readonly version = '1.0.0';\n readonly capabilities = {\n derivation: new BIP32Derivation(),\n };\n\n async generateKeypair(): Promise<Keypair> {\n const privateKey = secp256k1.utils.randomSecretKey();\n const publicKey = secp256k1.getPublicKey(privateKey, true); // compressed\n \n return {\n privateKey,\n publicKey,\n };\n }\n\n async sign(privateKey: Uint8Array, message: Uint8Array, options: SignOptions = {}): Promise<Uint8Array> {\n // ECDSA has no context string. Quietly ignoring one would let a caller\n // believe a signature is domain-separated when it is not.\n if (options.context !== undefined && !(options.context instanceof Uint8Array && options.context.length === 0)) {\n throw new Error('BsvEcdsaSuite: ECDSA has no context string; bind the context into the message instead');\n }\n try {\n // Deterministic signature (RFC 6979).\n //\n // `prehash: false` IS LOAD-BEARING. @noble/secp256k1 v3 hashes the message with\n // SHA-256 by default; v2 did not, and this suite's contract — like the rest of this\n // library and like Bitcoin tooling generally — is that the caller passes the\n // 32-byte DIGEST. Leaving the default on would SHA-256 the digest a second time:\n // every signature would differ from every one issued before, and no previously\n // issued signature would verify. Nothing would throw.\n //\n // v3 also returns compact 64-byte bytes directly (`format` defaults to 'compact'),\n // so the v2 `.toCompactRawBytes()` call is gone rather than renamed.\n return secp256k1.sign(message, privateKey, { prehash: false });\n } catch (error) {\n throw new Error(`BsvEcdsaSuite signing failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async verify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n options: SignOptions = {}\n ): Promise<boolean> {\n if (options.context !== undefined && !(options.context instanceof Uint8Array && options.context.length === 0)) return false;\n try {\n // `prehash: false` for the same reason as sign(): the message is already a digest.\n // If sign and verify ever disagree on this, verification silently fails for every\n // signature rather than erroring.\n return secp256k1.verify(signature, message, publicKey, { prehash: false }) === true;\n } catch (error) {\n // Invalid signature format or other errors count as verification failure\n return false;\n }\n }\n\n exportPublicKey(pub: Uint8Array): string {\n // Export as hex (standard format)\n return bytesToHex(pub);\n }\n\n importPublicKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n // Must decode to a point on the curve (33-byte compressed or 65-byte\n // uncompressed). Any hex string used to be accepted here.\n if (!secp256k1.utils.isValidPublicKey(bytes)) {\n throw new Error('Invalid secp256k1 public key');\n }\n return bytes;\n }\n\n exportPrivateKey(priv: Uint8Array): string {\n // Export as Bitcoin WIF format for maximum compatibility\n return encodeWIF(priv, true, 'mainnet');\n }\n\n importPrivateKey(encoded: string): Uint8Array {\n // Support both hex and WIF formats\n if (encoded.length === 64) {\n // Hex format (64 hex chars = 32 bytes)\n const bytes = hexToBytes(encoded);\n if (bytes.length !== 32) {\n throw new Error('Private key must be 32 bytes');\n }\n assertValidSecretKey(bytes);\n return bytes;\n } else {\n // WIF format (starts with '5', 'K', or 'L' for mainnet compressed)\n try {\n const { privateKey } = decodeWIF(encoded);\n assertValidSecretKey(privateKey);\n return privateKey;\n } catch (error) {\n throw new Error(`Invalid private key format: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n}\n", "import { SignatureSuite, Keypair } from '../types.js';\nimport { bytesToHex, hexToBytes } from '../utils.js';\nimport type { SignOptions } from '../types.js';\nimport type { DSA } from '@noble/post-quantum/ml-dsa.js';\n\n// Lazy-load the noble ML-DSA implementations\nlet ml_dsa44_lib: DSA | null = null;\nlet ml_dsa65_lib: DSA | null = null;\nlet ml_dsa87_lib: DSA | null = null;\n\nasync function getMlDsa44(): Promise<DSA> {\n if (!ml_dsa44_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa44_lib = module.ml_dsa44;\n }\n return ml_dsa44_lib;\n}\n\nasync function getMlDsa65(): Promise<DSA> {\n if (!ml_dsa65_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa65_lib = module.ml_dsa65;\n }\n return ml_dsa65_lib;\n}\n\nasync function getMlDsa87(): Promise<DSA> {\n if (!ml_dsa87_lib) {\n const module = await import('@noble/post-quantum/ml-dsa.js');\n ml_dsa87_lib = module.ml_dsa87;\n }\n return ml_dsa87_lib;\n}\n\n/**\n * Key sizes for each ML-DSA variant (NIST FIPS 204)\n */\ninterface MlDsaSizes {\n publicKey: number;\n privateKey: number;\n signature: number;\n}\n\n/** The library's options for a context string, validated; nothing for the empty context. */\nfunction contextOption(options: SignOptions): { context: Uint8Array } | undefined {\n const context = options.context;\n if (context === undefined) return undefined;\n // Type first: a string or array here must not be read as \"no context\".\n if (!(context instanceof Uint8Array)) throw new Error('context must be a Uint8Array');\n if (context.length > 255) throw new Error('context must be at most 255 bytes');\n return context.length === 0 ? undefined : { context };\n}\n\nconst ML_DSA_SIZES: Record<string, MlDsaSizes> = {\n 'ml-dsa-44': { publicKey: 1312, privateKey: 2560, signature: 2420 },\n 'ml-dsa-65': { publicKey: 1952, privateKey: 4032, signature: 3309 },\n // FIPS 204 Table 2. (4,864 was the round-3 Dilithium5 size, not ML-DSA-87.)\n 'ml-dsa-87': { publicKey: 2592, privateKey: 4896, signature: 4627 },\n};\n\n/**\n * Base ML-DSA implementation using @noble/post-quantum\n * Provides proper FIPS 204 compliant implementations for all three parameter sets\n */\nabstract class BaseMlDsaSuite implements SignatureSuite {\n abstract readonly suiteId: string;\n readonly version = '2.0.0'; // Bumped for proper implementation\n readonly capabilities = {};\n\n protected abstract get sizes(): MlDsaSizes;\n protected abstract getLib(): Promise<DSA>;\n\n async generateKeypair(): Promise<Keypair> {\n try {\n const lib = await this.getLib();\n const keypair = lib.keygen();\n \n return {\n publicKey: keypair.publicKey,\n privateKey: keypair.secretKey,\n };\n } catch (error) {\n throw new Error(`${this.suiteId} key generation failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async sign(privateKey: Uint8Array, message: Uint8Array, options: SignOptions = {}): Promise<Uint8Array> {\n try {\n const lib = await this.getLib();\n // FIPS 204 ML-DSA.Sign (pure mode, hedged). With no context this is the\n // empty context, exactly as before.\n return lib.sign(message, privateKey, contextOption(options));\n } catch (error) {\n throw new Error(`${this.suiteId} signing failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n async verify(\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n options: SignOptions = {}\n ): Promise<boolean> {\n try {\n const lib = await this.getLib();\n // Wrong-length inputs are rejected here rather than left to the library.\n if (publicKey.length !== this.sizes.publicKey || signature.length !== this.sizes.signature) {\n return false;\n }\n return lib.verify(signature, message, publicKey, contextOption(options)) === true;\n } catch (error) {\n // Verification failures should return false, not throw\n return false;\n }\n }\n\n exportPublicKey(pub: Uint8Array): string {\n return bytesToHex(pub);\n }\n\n importPublicKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n if (bytes.length !== this.sizes.publicKey) {\n throw new Error(`${this.suiteId} public key must be ${this.sizes.publicKey} bytes, got ${bytes.length}`);\n }\n return bytes;\n }\n\n exportPrivateKey(priv: Uint8Array): string {\n return bytesToHex(priv);\n }\n\n importPrivateKey(encoded: string): Uint8Array {\n const bytes = hexToBytes(encoded);\n if (bytes.length !== this.sizes.privateKey) {\n throw new Error(`${this.suiteId} private key must be ${this.sizes.privateKey} bytes, got ${bytes.length}`);\n }\n return bytes;\n }\n}\n\n/**\n * ML-DSA-44 Suite ✅ PROPERLY IMPLEMENTED\n * \n * NIST FIPS 204 ML-DSA-44 Specification:\n * - Security Level: 2 (equivalent to AES-128)\n * - Public key: 1,312 bytes\n * - Private key: 2,560 bytes\n * - Signature: 2,420 bytes\n * \n * Use cases:\n * - IoT devices with limited storage\n * - Mobile applications\n * - High-volume signing scenarios where size matters\n * - Systems requiring fast signing/verification\n * \n * Trade-offs:\n * - Smallest signatures (fastest to transmit)\n * - Lower security level (but still quantum-safe)\n * - Suitable for most applications until 2030\n */\nexport class MlDsa44Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-44';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-44'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa44();\n }\n}\n\n/**\n * ML-DSA-65 Suite ✅ PROPERLY IMPLEMENTED (Recommended default)\n * \n * NIST FIPS 204 ML-DSA-65 Specification:\n * - Security Level: 3 (equivalent to AES-192)\n * - Public key: 1,952 bytes\n * - Private key: 4,032 bytes\n * - Signature: 3,309 bytes\n * \n * This is the **recommended default** for most applications:\n * - Balanced security vs size trade-off\n * - Strong quantum resistance\n * - Reasonable signature sizes\n * - Good performance\n * \n * Use cases:\n * - General-purpose applications\n * - Web services and APIs\n * - Document signing\n * - Most enterprise applications\n * \n * Comparison to ML-DSA-87:\n * - 28% smaller signatures (3.3KB vs 4.6KB)\n * - 25% smaller public keys (1.9KB vs 2.6KB)\n * - Still provides strong quantum resistance\n */\nexport class MlDsa65Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-65';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-65'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa65();\n }\n}\n\n/**\n * ML-DSA-87 Suite ✅ PROPERLY IMPLEMENTED (Maximum security)\n * \n * NIST FIPS 204 ML-DSA-87 Specification:\n * - Security Level: 5 (equivalent to AES-256)\n * - Public key: 2,592 bytes\n * - Private key: 4,896 bytes\n * - Signature: 4,627 bytes\n * \n * Provides the **highest security level** in NIST FIPS 204:\n * - Maximum quantum resistance\n * - Suitable for long-term secrets (decades)\n * - Government/military grade security\n * \n * Use cases:\n * - High-security applications\n * - Long-term data protection\n * - Government/military systems\n * - Financial institutions\n * - Critical infrastructure\n * \n * Trade-offs:\n * - Largest signatures (~4.6KB)\n * - Highest computational cost\n * - Maximum security guarantee\n */\nexport class MlDsa87Suite extends BaseMlDsaSuite {\n readonly suiteId = 'ml-dsa-87';\n \n protected get sizes(): MlDsaSizes {\n return ML_DSA_SIZES['ml-dsa-87'];\n }\n\n protected async getLib(): Promise<DSA> {\n return getMlDsa87();\n }\n}\n\n/**\n * Default ML-DSA Suite (alias for ML-DSA-65)\n * \n * Use this for the recommended security level (NIST Level 3).\n * Provides the best balance between security and efficiency.\n */\nexport class MlDsaSuite extends MlDsa65Suite {\n // Inherits everything from MlDsa65Suite\n}\n", "import { SignatureSuite } from './types.js';\n\n/**\n * Registry for managing signature suite implementations\n */\nexport class SignatureSuiteRegistry {\n private suites = new Map<string, SignatureSuite>();\n\n /**\n * Register a signature suite implementation\n */\n register(suite: SignatureSuite): void {\n if (this.suites.has(suite.suiteId)) {\n throw new Error(`Signature suite already registered: ${suite.suiteId}`);\n }\n this.suites.set(suite.suiteId, suite);\n }\n\n /**\n * Get a signature suite by ID\n * @throws Error if suite is not registered\n */\n getSuite(suiteId: string): SignatureSuite {\n const suite = this.suites.get(suiteId);\n if (!suite) {\n throw new Error(`Unknown signature suite: ${suiteId}. Available: ${this.listSuites().join(', ')}`);\n }\n return suite;\n }\n\n /**\n * Check if a suite is registered\n */\n hasSuite(suiteId: string): boolean {\n return this.suites.has(suiteId);\n }\n\n /**\n * List all registered suite IDs\n */\n listSuites(): string[] {\n return [...this.suites.keys()];\n }\n\n /**\n * Get all registered suite objects\n */\n getAllSuites(): SignatureSuite[] {\n return [...this.suites.values()];\n }\n\n /**\n * Unregister a suite (primarily for testing)\n */\n unregister(suiteId: string): boolean {\n return this.suites.delete(suiteId);\n }\n\n /**\n * Clear all registered suites (primarily for testing)\n */\n clear(): void {\n this.suites.clear();\n }\n}\n\n// Global singleton instance\nexport const globalRegistry = new SignatureSuiteRegistry();\n\n// Auto-register default suites\nimport { BsvEcdsaSuite } from './suites/bsv-ecdsa.js';\nimport { MlDsa44Suite, MlDsa65Suite, MlDsa87Suite } from './suites/ml-dsa.js';\n\n// Register all standard suites by default\nglobalRegistry.register(new BsvEcdsaSuite());\nglobalRegistry.register(new MlDsa44Suite());\nglobalRegistry.register(new MlDsa65Suite());\nglobalRegistry.register(new MlDsa87Suite());\n", "/**\n * Explicit error types for SmartLedger cryptographic operations.\n * These errors provide clear, actionable feedback for debugging and auditing.\n */\n\n/**\n * Base class for all SmartLedger crypto errors.\n */\nexport class SmartLedgerCryptoError extends Error {\n constructor(message: string, public readonly code: string) {\n super(message);\n this.name = this.constructor.name;\n Error.captureStackTrace(this, this.constructor);\n }\n}\n\n/**\n * Thrown when a requested key cannot be found.\n */\nexport class KeyNotFoundError extends SmartLedgerCryptoError {\n constructor(public readonly keyId: string) {\n super(`Key not found: ${keyId}`, 'KEY_NOT_FOUND');\n }\n}\n\n/**\n * Thrown when registering a key under an ID that is already taken.\n *\n * Registration never overwrites: replacing the keypair behind an existing ID\n * would silently destroy a private key and re-point every reference to it.\n */\nexport class KeyAlreadyExistsError extends SmartLedgerCryptoError {\n constructor(public readonly keyId: string) {\n super(`Key already exists: ${keyId}`, 'KEY_ALREADY_EXISTS');\n }\n}\n\n/**\n * Thrown when attempting to use an expired key.\n */\nexport class KeyExpiredError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId: string,\n public readonly expiresAt: string\n ) {\n super(\n `Key expired: ${keyId} (expired at ${expiresAt})`,\n 'KEY_EXPIRED'\n );\n }\n}\n\n/**\n * Thrown when a key is in an invalid state for the requested operation.\n */\nexport class KeyInvalidStateError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId: string,\n public readonly currentState: string,\n public readonly requiredState: string\n ) {\n super(\n `Key in invalid state: ${keyId} (current: ${currentState}, required: ${requiredState})`,\n 'KEY_INVALID_STATE'\n );\n }\n}\n\n/**\n * Thrown when a suite is not allowed by the active compliance profile.\n */\nexport class SuiteNotAllowedError extends SmartLedgerCryptoError {\n constructor(\n public readonly suiteId: string,\n public readonly profileName?: string\n ) {\n const profileMsg = profileName ? ` in profile ${profileName}` : '';\n super(\n `Suite not allowed: ${suiteId}${profileMsg}`,\n 'SUITE_NOT_ALLOWED'\n );\n }\n}\n\n/**\n * Thrown when a requested suite cannot be found.\n */\nexport class SuiteNotFoundError extends SmartLedgerCryptoError {\n constructor(public readonly suiteId: string) {\n super(`Suite not found: ${suiteId}`, 'SUITE_NOT_FOUND');\n }\n}\n\n/**\n * Thrown when signature verification fails.\n */\nexport class InvalidSignatureError extends SmartLedgerCryptoError {\n constructor(\n public readonly keyId?: string,\n message: string = 'Signature verification failed'\n ) {\n super(message, 'INVALID_SIGNATURE');\n }\n}\n\n/**\n * Thrown when a cryptographic operation fails.\n */\nexport class CryptoOperationError extends SmartLedgerCryptoError {\n constructor(\n public readonly operation: string,\n message: string,\n public readonly cause?: Error\n ) {\n super(\n `Cryptographic operation failed (${operation}): ${message}`,\n 'CRYPTO_OPERATION_FAILED'\n );\n }\n}\n\n/**\n * Thrown when key parameters are invalid.\n */\nexport class InvalidKeyParametersError extends SmartLedgerCryptoError {\n constructor(message: string) {\n super(`Invalid key parameters: ${message}`, 'INVALID_KEY_PARAMETERS');\n }\n}\n\n/**\n * Thrown when a compliance profile violation is detected.\n */\nexport class ComplianceViolationError extends SmartLedgerCryptoError {\n constructor(\n public readonly profileName: string,\n public readonly violation: string\n ) {\n super(\n `Compliance violation in profile ${profileName}: ${violation}`,\n 'COMPLIANCE_VIOLATION'\n );\n }\n}\n", "/**\n * Key Registry for managing cryptographic keypairs across signature suites.\n * \n * Handles:\n * - Key lifecycle (creation, rotation, expiration, revocation)\n * - Storage abstraction (the only backend shipped here is in-memory)\n * - Key metadata tracking (suiteId, usage, timestamps)\n */\n\nimport { Keypair, KeyMeta } from './types.js';\nimport {\n KeyAlreadyExistsError,\n KeyExpiredError,\n KeyInvalidStateError,\n KeyNotFoundError,\n InvalidKeyParametersError,\n} from './errors.js';\n\n/**\n * Storage adapter interface for keypair persistence.\n */\nexport interface KeyStorage {\n /**\n * Store a keypair with associated metadata.\n */\n store(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<void>;\n\n /**\n * Store a keypair only if no key exists under `keyId`, as ONE atomic step.\n * Resolves `true` if it stored, `false` if the ID was already taken.\n *\n * Optional for backward compatibility. Without it KeyRegistry falls back to\n * load-then-store, which two writers sharing a backend can interleave; a\n * backend that is shared between processes should implement this.\n */\n storeIfAbsent?(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<boolean>;\n \n /**\n * Retrieve a keypair by ID.\n * Returns null if not found.\n */\n load(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null>;\n \n /**\n * List all key IDs matching optional filter.\n */\n list(filter?: Partial<KeyMeta>): Promise<KeyMeta[]>;\n \n /**\n * Delete a keypair (use with caution).\n */\n delete(keyId: string): Promise<void>;\n \n /**\n * Update metadata without changing keypair.\n */\n updateMeta(keyId: string, meta: Partial<KeyMeta>): Promise<void>;\n}\n\n/**\n * The agent a key ID belongs to: everything before its last ':'.\n *\n * Key IDs are `<agentId>:<local part>`, and the local part never contains a\n * ':'. Ownership is this exact split, not a prefix test — with a prefix test\n * agent `a` also \"owned\" every key of agent `a:b`.\n *\n * @returns the agent ID, or null if `keyId` has no ':' separator\n */\nexport function agentIdOfKey(keyId: string): string | null {\n if (typeof keyId !== 'string') return null;\n const i = keyId.lastIndexOf(':');\n if (i <= 0 || i === keyId.length - 1) return null;\n return keyId.slice(0, i);\n}\n\n/** Copy metadata so a caller cannot reach the stored record through it. */\nexport function cloneKeyMeta(meta: KeyMeta): KeyMeta {\n return {\n ...meta,\n usage: [...meta.usage],\n ...(meta.derivation ? { derivation: { ...meta.derivation } } : {}),\n };\n}\n\nfunction cloneKeypair(keypair: Keypair): Keypair {\n return {\n publicKey: Uint8Array.from(keypair.publicKey),\n privateKey: Uint8Array.from(keypair.privateKey),\n };\n}\n\n/**\n * Whether `meta` may be used to create new signatures at `now`.\n *\n * A key is usable only if its status is active (or absent, for records written\n * before status existed) AND it has not passed `expiresAt`. Status alone is not\n * enough: nothing flips an expired key's status unless `markExpiredKeys()` is\n * run, so the date has to be checked wherever the key is used.\n */\nexport function isKeyUsable(meta: KeyMeta, now: Date = new Date()): boolean {\n if (meta.status && meta.status !== 'active') return false;\n if (meta.expiresAt !== undefined) {\n const expires = new Date(meta.expiresAt).getTime();\n // An unparseable date is treated as expired, never as \"no expiry\".\n if (Number.isNaN(expires) || expires <= now.getTime()) return false;\n }\n return true;\n}\n\n/**\n * Throw unless `meta` may be used to create new signatures at `now`.\n *\n * @throws {KeyInvalidStateError} if the key is rotated, revoked or marked expired\n * @throws {KeyExpiredError} if the key is past `expiresAt`\n */\nexport function assertKeyUsable(meta: KeyMeta, now: Date = new Date()): void {\n if (meta.status && meta.status !== 'active') {\n throw new KeyInvalidStateError(meta.keyId, meta.status, 'active');\n }\n if (!isKeyUsable(meta, now)) {\n throw new KeyExpiredError(meta.keyId, String(meta.expiresAt));\n }\n}\n\nfunction assertValidExpiry(expiresAt: string | undefined): void {\n if (expiresAt === undefined) return;\n if (typeof expiresAt !== 'string' || Number.isNaN(new Date(expiresAt).getTime())) {\n throw new InvalidKeyParametersError(\n `expiresAt must be an ISO 8601 date, got ${JSON.stringify(expiresAt)}`\n );\n }\n}\n\n/**\n * In-memory key storage (for testing/development only).\n *\n * Private keys are held unencrypted and are lost when the process exits.\n *\n * Records are copied on the way in and on the way out. Handing out the stored\n * objects themselves let any caller holding a KeyRecord edit the registry's\n * state in place — setting `meta.status = 'active'` on a revoked key made it\n * sign again.\n */\nexport class InMemoryKeyStorage implements KeyStorage {\n private keys = new Map<string, { keypair: Keypair; meta: KeyMeta }>();\n \n async store(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<void> {\n this.keys.set(keyId, { keypair: cloneKeypair(keypair), meta: cloneKeyMeta(meta) });\n }\n\n async storeIfAbsent(keyId: string, keypair: Keypair, meta: KeyMeta): Promise<boolean> {\n // No await between the check and the set, so this is atomic on one event loop.\n if (this.keys.has(keyId)) return false;\n this.keys.set(keyId, { keypair: cloneKeypair(keypair), meta: cloneKeyMeta(meta) });\n return true;\n }\n \n async load(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null> {\n const found = this.keys.get(keyId);\n if (!found) return null;\n return { keypair: cloneKeypair(found.keypair), meta: cloneKeyMeta(found.meta) };\n }\n \n async list(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n const allMeta = Array.from(this.keys.values()).map(k => cloneKeyMeta(k.meta));\n \n if (!filter) {\n return allMeta;\n }\n \n return allMeta.filter(meta => {\n return Object.entries(filter).every(([key, value]) => {\n if (key === 'usage' && Array.isArray(value)) {\n // Check if any usage matches\n return value.some(u => meta.usage.includes(u));\n }\n return meta[key as keyof KeyMeta] === value;\n });\n });\n }\n \n async delete(keyId: string): Promise<void> {\n const found = this.keys.get(keyId);\n if (found) {\n // The stored copy is ours alone, so it can be wiped before it is dropped.\n found.keypair.privateKey.fill(0);\n }\n this.keys.delete(keyId);\n }\n \n async updateMeta(keyId: string, updates: Partial<KeyMeta>): Promise<void> {\n const existing = this.keys.get(keyId);\n if (!existing) {\n throw new KeyNotFoundError(keyId);\n }\n \n this.keys.set(keyId, {\n keypair: existing.keypair,\n meta: cloneKeyMeta({ ...existing.meta, ...updates }),\n });\n }\n \n /**\n * Clear all keys (testing only).\n */\n clear(): void {\n for (const { keypair } of this.keys.values()) {\n keypair.privateKey.fill(0);\n }\n this.keys.clear();\n }\n}\n\n/** Options accepted by {@link KeyRegistry.registerKey}. */\nexport interface RegisterKeyOptions {\n expiresAt?: string;\n usage?: KeyMeta['usage'];\n cryptoProfileVersion?: string;\n status?: KeyMeta['status'];\n /** ID of the key this one replaces. */\n rotatedFrom?: string;\n /** How the key was derived, if it was (never the seed). */\n derivation?: KeyMeta['derivation'];\n}\n\n/** Options accepted by {@link KeyRegistry.rotateKey}. */\nexport interface RotateKeyOptions {\n /**\n * Expiry of the NEW key.\n * - omitted: the old key's lifetime (`expiresAt - createdAt`) is granted\n * again, counted from now; no expiry if the old key had none.\n * - an ISO 8601 string: that instant.\n * - `null`: the new key does not expire.\n */\n expiresAt?: string | null;\n /** Derivation record for the new key, if it was derived. */\n derivation?: KeyMeta['derivation'];\n}\n\n/**\n * KeyRegistry manages the lifecycle of cryptographic keys.\n * \n * Features:\n * - Register new keypairs with metadata\n * - Retrieve keys by ID or filter\n * - Key rotation with audit trail\n * - Expiration and revocation\n * - Storage backend abstraction\n */\nexport class KeyRegistry {\n constructor(private storage: KeyStorage = new InMemoryKeyStorage()) {}\n \n /**\n * Register a new keypair with metadata.\n *\n * @throws {KeyAlreadyExistsError} if `keyId` is already registered. A key is\n * never overwritten; delete it explicitly first if that is really intended.\n * @throws {InvalidKeyParametersError} if `keyId` is empty or `expiresAt` is\n * not a parseable date\n */\n async registerKey(\n keyId: string,\n keypair: Keypair,\n suiteId: string,\n options: RegisterKeyOptions = {}\n ): Promise<KeyMeta> {\n if (typeof keyId !== 'string' || keyId.length === 0) {\n throw new InvalidKeyParametersError('keyId must be a non-empty string');\n }\n assertValidExpiry(options.expiresAt);\n\n const meta: KeyMeta = {\n keyId,\n suiteId,\n createdAt: new Date().toISOString(),\n expiresAt: options.expiresAt,\n usage: options.usage ? [...options.usage] : ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n status: options.status || 'active',\n ...(options.rotatedFrom !== undefined ? { rotatedFrom: options.rotatedFrom } : {}),\n ...(options.derivation ? { derivation: { ...options.derivation } } : {}),\n };\n\n if (this.storage.storeIfAbsent) {\n const stored = await this.storage.storeIfAbsent(keyId, keypair, meta);\n if (!stored) throw new KeyAlreadyExistsError(keyId);\n } else {\n // Best effort for backends without an atomic primitive.\n if (await this.storage.load(keyId)) throw new KeyAlreadyExistsError(keyId);\n await this.storage.store(keyId, keypair, meta);\n }\n return cloneKeyMeta(meta);\n }\n \n /**\n * Get a keypair and its metadata.\n */\n async getKey(keyId: string): Promise<{ keypair: Keypair; meta: KeyMeta } | null> {\n return await this.storage.load(keyId);\n }\n \n /**\n * Get only the public key (no private key).\n */\n async getPublicKey(keyId: string): Promise<{ publicKey: Uint8Array; meta: KeyMeta } | null> {\n const result = await this.storage.load(keyId);\n if (!result) return null;\n \n return {\n // Copied even if the backend did not, so the caller never holds a\n // reference into the stored record.\n publicKey: Uint8Array.from(result.keypair.publicKey),\n meta: cloneKeyMeta(result.meta),\n };\n }\n \n /**\n * List all keys matching optional filter.\n */\n async listKeys(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n return await this.storage.list(filter);\n }\n \n /**\n * List only active, non-expired keys.\n */\n async listActiveKeys(filter?: Partial<KeyMeta>): Promise<KeyMeta[]> {\n const allKeys = await this.storage.list(filter);\n const now = new Date();\n return allKeys.filter(meta => isKeyUsable(meta, now));\n }\n \n /**\n * Rotate a key: register `newKeypair` under `newKeyId` and mark the old key\n * 'rotated'.\n *\n * The new key is registered BEFORE the old one is retired, so a failure\n * (for example a duplicate `newKeyId`) leaves the old key active rather\n * than leaving the owner with no usable key. If retiring the old key then\n * fails, the new key is removed again.\n *\n * This is two storage operations, not a transaction: two concurrent\n * rotations of the same key on a shared backend can both succeed. Serialise\n * rotation per key if several writers share the storage.\n *\n * @throws {KeyInvalidStateError} if the old key is revoked or already rotated\n *\n * The new key does not inherit the old key's expiry instant — that made a\n * freshly rotated key die on its predecessor's date. See\n * {@link RotateKeyOptions.expiresAt}.\n * \n * Returns the new key's metadata.\n */\n async rotateKey(\n oldKeyId: string,\n newKeyId: string,\n newKeypair: Keypair,\n options: RotateKeyOptions = {}\n ): Promise<KeyMeta> {\n const oldKey = await this.storage.load(oldKeyId);\n if (!oldKey) {\n throw new Error(`Cannot rotate: key not found: ${oldKeyId}`);\n }\n // A revoked key must not come back as a fresh active successor, and a key\n // that was already rotated must not get a second one. An expired key may\n // be rotated: that is how it is renewed.\n if (oldKey.meta.status === 'revoked' || oldKey.meta.status === 'rotated') {\n throw new KeyInvalidStateError(oldKeyId, oldKey.meta.status, 'active or expired');\n }\n\n let expiresAt: string | undefined;\n if (options.expiresAt === null) {\n expiresAt = undefined;\n } else if (options.expiresAt !== undefined) {\n expiresAt = options.expiresAt;\n } else if (oldKey.meta.expiresAt !== undefined) {\n const lifetime =\n new Date(oldKey.meta.expiresAt).getTime() - new Date(oldKey.meta.createdAt).getTime();\n if (Number.isFinite(lifetime) && lifetime > 0) {\n expiresAt = new Date(Date.now() + lifetime).toISOString();\n } else {\n throw new InvalidKeyParametersError(\n `cannot infer a lifetime for the replacement of ${oldKeyId} ` +\n `(createdAt ${oldKey.meta.createdAt}, expiresAt ${oldKey.meta.expiresAt}); ` +\n `pass options.expiresAt`\n );\n }\n }\n\n const newMeta = await this.registerKey(newKeyId, newKeypair, oldKey.meta.suiteId, {\n usage: oldKey.meta.usage,\n cryptoProfileVersion: oldKey.meta.cryptoProfileVersion,\n expiresAt,\n status: 'active',\n rotatedFrom: oldKeyId,\n derivation: options.derivation,\n });\n\n try {\n await this.storage.updateMeta(oldKeyId, {\n status: 'rotated',\n });\n } catch (error) {\n // Do not leave predecessor and successor both active.\n await this.storage.delete(newKeyId).catch(() => undefined);\n throw error;\n }\n\n return newMeta;\n }\n \n /**\n * Revoke a key (marks as unusable, but doesn't delete).\n */\n async revokeKey(keyId: string, reason?: string): Promise<void> {\n await this.storage.updateMeta(keyId, {\n status: 'revoked',\n revokedAt: new Date().toISOString(),\n });\n }\n \n /**\n * Delete a key permanently (use with caution).\n */\n async deleteKey(keyId: string): Promise<void> {\n await this.storage.delete(keyId);\n }\n \n /**\n * Mark expired keys as 'expired' status.\n * Returns count of keys marked expired.\n */\n async markExpiredKeys(): Promise<number> {\n const allKeys = await this.storage.list();\n const now = new Date();\n let count = 0;\n \n for (const meta of allKeys) {\n if (meta.status === 'active' && !isKeyUsable(meta, now)) {\n await this.storage.updateMeta(meta.keyId, {\n status: 'expired',\n });\n count++;\n }\n }\n \n return count;\n }\n \n /**\n * Cleanup: delete keys that have been revoked/expired for longer than retention period.\n * \n * @param retentionDays How many days to keep revoked/expired keys (default: 90)\n */\n async pruneOldKeys(retentionDays: number = 90): Promise<number> {\n const allKeys = await this.storage.list();\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - retentionDays);\n \n let count = 0;\n \n for (const meta of allKeys) {\n const shouldPrune = \n (meta.status === 'revoked' && meta.revokedAt && new Date(meta.revokedAt) < cutoffDate) ||\n (meta.status === 'expired' && meta.expiresAt && new Date(meta.expiresAt) < cutoffDate);\n \n if (shouldPrune) {\n await this.storage.delete(meta.keyId);\n count++;\n }\n }\n \n return count;\n }\n}\n", "/**\n * Default implementation of KeySDK.\n * \n * Integrates KeyRegistry and SignatureSuiteRegistry to provide\n * a clean, high-level API for key operations.\n */\n\nimport {\n KeyRegistry,\n SignatureSuiteRegistry,\n KeyMeta,\n Keypair,\n CryptoProfile,\n hashBytes,\n assertKeyUsable,\n isKeyUsable,\n cloneKeyMeta,\n agentIdOfKey,\n KeyAlreadyExistsError,\n BIP32Derivation,\n InMemoryKeyStorage,\n BsvEcdsaSuite,\n MlDsa44Suite,\n MlDsa65Suite,\n MlDsa87Suite,\n} from '@smartledger/crypto';\nimport {\n KeySDK,\n KeyRecord,\n CreateKeyOptions,\n AgentKeyConfig,\n MultiSignatureResult,\n MultiVerificationResult,\n SuiteSignature,\n SuiteVerificationResult,\n KeyStatusPolicy,\n VerifySignatureOptions,\n VerifyWithSuitesOptions,\n SignatureScheme,\n RotateAgentKeysOptions,\n WalletKeyPath,\n} from './types.js';\n\n/**\n * Configuration for DefaultKeySDK.\n */\nexport interface KeySDKConfig {\n /** Key registry instance */\n keyRegistry: KeyRegistry;\n \n /** Signature suite registry instance */\n suiteRegistry: SignatureSuiteRegistry;\n\n /**\n * Context string for ML-DSA signatures (FIPS 204), 1 to 255 bytes. An\n * ML-DSA signature verifies only under the context it was made with, so\n * two deployments with different contexts cannot have ML-DSA signatures\n * replayed between them. It does NOT enter an ECDSA signature: ECDSA has\n * no context, and the same ECDSA key and message verify in any deployment.\n * Default: `@smartledger/keys/4`.\n */\n signingContext?: string | Uint8Array;\n}\n\n/** The default ML-DSA context string of this major version. */\nexport const DEFAULT_SIGNING_CONTEXT = '@smartledger/keys/4';\n\nexport { agentIdOfKey };\n\nconst COUNTER_SUFFIX = /^pk-[^:-]+-(\\d+)$/;\nconst MAX_KEY_ID_ATTEMPTS = 8;\n\nfunction assertAgentId(agentId: unknown): asserts agentId is string {\n if (typeof agentId !== 'string' || agentId.length === 0) {\n throw new Error('agentId must be a non-empty string');\n }\n}\n\nfunction toRecord(meta: KeyMeta, publicKey: Uint8Array): KeyRecord {\n // Copies, so a caller cannot reach registry state through a KeyRecord even\n // when a custom storage backend hands out its own objects.\n return { meta: cloneKeyMeta(meta), publicKey: Uint8Array.from(publicKey) };\n}\n\nfunction statusAllows(meta: KeyMeta, policy: KeyStatusPolicy): boolean {\n if (policy === 'any') return true;\n if (policy === 'not-revoked') return meta.status !== 'revoked';\n return isKeyUsable(meta);\n}\n\n/**\n * Default KeySDK implementation.\n * \n * Provides a simple, safe API for key operations while hiding complexity.\n */\nexport class DefaultKeySDK implements KeySDK {\n private keyRegistry: KeyRegistry;\n private suiteRegistry: SignatureSuiteRegistry;\n private keyCounter = new Map<string, number>(); // agentId -> counter\n private counterInitialized = new Set<string>();\n private counterInitPromises = new Map<string, Promise<void>>();\n private getOrCreateInFlight = new Map<string, Promise<KeyRecord>>();\n \n private signingContext: Uint8Array;\n\n constructor(config: KeySDKConfig) {\n this.keyRegistry = config.keyRegistry;\n this.suiteRegistry = config.suiteRegistry;\n const context = config.signingContext ?? DEFAULT_SIGNING_CONTEXT;\n const bytes = typeof context === 'string' ? new TextEncoder().encode(context) : Uint8Array.from(context);\n if (bytes.length < 1 || bytes.length > 255) {\n throw new Error('signingContext must be 1 to 255 bytes');\n }\n this.signingContext = bytes;\n }\n \n /**\n * Create a new key for an agent.\n */\n async createKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n\n // Get suite\n const suite = this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n \n // Generate keypair (with optional derivation)\n let keypair;\n \n if (options.derivationContext) {\n // Check if suite supports derivation\n if (!suite.capabilities?.derivation) {\n const available = this.getSuitesWithCapability('derivation');\n throw new Error(\n `Suite '${suite.suiteId}' does not support key derivation.\\n` +\n (available.length > 0\n ? `Suites with derivation capability: ${available.join(', ')}\\n` +\n `Consider using one of these suites or remove the derivationContext option.`\n : `No suites currently support derivation. Remove the derivationContext option.`)\n );\n }\n \n // Use derivation capability\n keypair = await suite.capabilities.derivation.deriveKeypair(options.derivationContext);\n } else {\n // Standard random key generation\n keypair = await suite.generateKeypair();\n }\n \n const meta = await this.registerUnderFreshId(agentId, profile.primarySignatureSuite, keyId =>\n this.keyRegistry.registerKey(keyId, keypair, profile.primarySignatureSuite, {\n expiresAt: options.expiresAt,\n usage: options.usage || ['signing'],\n cryptoProfileVersion: options.cryptoProfileVersion || '1.0.0',\n // Record that (and where) the key was derived. Never the seed.\n derivation: options.derivationContext\n ? { path: options.derivationContext.path ?? '' }\n : undefined,\n })\n );\n \n return toRecord(meta, keypair.publicKey);\n }\n \n /**\n * Get an existing key.\n */\n async getKey(keyId: string): Promise<KeyRecord | null> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return null;\n }\n \n return toRecord(result.meta, result.publicKey);\n }\n \n /**\n * Sign with a key (private key never exposed).\n *\n * @throws if the key is unknown, not active, past its `expiresAt`, or not\n * registered for signing\n */\n async signWithKey(\n keyId: string,\n message: Uint8Array\n ): Promise<Uint8Array> {\n // Get full keypair (private access)\n const result = await this.keyRegistry.getKey(keyId);\n \n if (!result) {\n throw new Error(`Key not found: ${keyId}`);\n }\n \n if (result.meta.status && result.meta.status !== 'active') {\n throw new Error(`Key is not active: ${keyId} (status: ${result.meta.status})`);\n }\n // Status alone is not enough: an expired key keeps status 'active' until\n // markExpiredKeys() runs, and used to go on signing in the meantime.\n assertKeyUsable(result.meta);\n\n if (!result.meta.usage.some(u => u === 'signing' || u === 'both')) {\n throw new Error(\n `Key is not registered for signing: ${keyId} (usage: ${result.meta.usage.join(', ')})`\n );\n }\n \n // Get suite and sign\n const suite = this.suiteRegistry.getSuite(result.meta.suiteId);\n const { input, options } = await this.signingInput(result.meta.suiteId, message, 'v4');\n return await suite.sign(result.keypair.privateKey, input, options);\n }\n\n /**\n * What a key of `suiteId` signs for `message` under a scheme.\n *\n * v4: ML-DSA signs the message itself in FIPS 204 pure mode with this SDK's\n * context string, so a standard verifier needs only the message and the\n * context, and the signature is not limited by an outside digest. ECDSA\n * signs SHA-256(message): ECDSA signs a digest by definition and has no\n * context, so callers who need domain separation for it put the purpose in\n * the message.\n *\n * v3-digest: what 3.x signed \u2014 SHA3-256(message) for ML-DSA, empty context.\n */\n private async signingInput(\n suiteId: string,\n message: Uint8Array,\n scheme: SignatureScheme\n ): Promise<{ input: Uint8Array; options?: { context: Uint8Array } }> {\n if (scheme !== 'v4' && scheme !== 'v3-digest') {\n throw new Error(`Unknown signature scheme: ${String(scheme)}`);\n }\n if (suiteId.startsWith('ml-dsa')) {\n return scheme === 'v4'\n ? { input: message, options: { context: this.signingContext } }\n : { input: await hashBytes(message, 'sha3-256') };\n }\n return { input: await hashBytes(message, 'sha256') };\n }\n \n /**\n * Verify a signature.\n *\n * By default this is the cryptographic check only: a signature made by a\n * key that has since been rotated, expired or revoked still verifies, which\n * is what verifying a historical signature needs. Pass `keyStatus` to also\n * require something of the key's state now.\n */\n async verifySignature(\n keyId: string,\n message: Uint8Array,\n signature: Uint8Array,\n options: VerifySignatureOptions = {}\n ): Promise<boolean> {\n const result = await this.keyRegistry.getPublicKey(keyId);\n \n if (!result) {\n return false;\n }\n\n if (!statusAllows(result.meta, options.keyStatus ?? 'any')) {\n return false;\n }\n\n return this.verifyAgainst(result.meta, result.publicKey, message, signature, options.scheme ?? 'v4');\n }\n\n /** The cryptographic check alone. Anything but a strict `true` is a failure. */\n private async verifyAgainst(\n meta: KeyMeta,\n publicKey: Uint8Array,\n message: Uint8Array,\n signature: Uint8Array,\n scheme: SignatureScheme = 'v4'\n ): Promise<boolean> {\n try {\n const suite = this.suiteRegistry.getSuite(meta.suiteId);\n const { input, options } = await this.signingInput(meta.suiteId, message, scheme);\n return (await suite.verify(publicKey, input, signature, options)) === true;\n } catch {\n return false;\n }\n }\n \n /**\n * List keys for an agent.\n */\n async listKeysForAgent(\n agentId: string,\n activeOnly: boolean = true\n ): Promise<KeyRecord[]> {\n assertAgentId(agentId);\n\n const keys = activeOnly\n ? await this.keyRegistry.listActiveKeys()\n : await this.keyRegistry.listKeys();\n \n // Exact ownership, not a prefix match (see agentIdOfKey)\n const agentKeys = keys.filter(meta => agentIdOfKey(meta.keyId) === agentId);\n \n // Convert to KeyRecords\n const records: KeyRecord[] = [];\n \n for (const meta of agentKeys) {\n const result = await this.keyRegistry.getPublicKey(meta.keyId);\n if (result) {\n records.push(toRecord(result.meta, result.publicKey));\n }\n }\n \n return records;\n }\n \n /**\n * Get active crypto profile for an agent.\n */\n async getActiveCryptoProfile(agentId: string): Promise<CryptoProfile | null> {\n const keys = await this.listKeysForAgent(agentId, true);\n \n if (keys.length === 0) {\n return null;\n }\n \n // Group by suite\n const sorted = this.sortKeysByCreatedAt(keys);\n const suites = new Set(sorted.map(k => k.meta.suiteId));\n const suiteArray = Array.from(suites);\n \n // Assume first is primary, second is secondary\n return {\n primarySignatureSuite: suiteArray[0],\n secondarySignatureSuite: suiteArray[1],\n };\n }\n \n /**\n * Rotate all keys for an agent.\n *\n * Each replacement gets its predecessor's lifetime again, counted from now\n * (or `options.expiresAt`); it does not inherit the old expiry instant.\n *\n * A key derived from a seed cannot be re-derived here, because the SDK does\n * not keep seeds. By default the call refuses, before changing anything,\n * rather than silently swapping a recoverable key for a random one. See\n * {@link RotateAgentKeysOptions.derivedKeys}.\n */\n async rotateAgentKeys(\n agentId: string,\n options: RotateAgentKeysOptions = {}\n ): Promise<KeyRecord[]> {\n const derivedPolicy = options.derivedKeys ?? 'error';\n const activeKeys = await this.listKeysForAgent(agentId, true);\n\n // Decide everything before changing anything.\n const toRotate: KeyRecord[] = [];\n for (const keyRecord of activeKeys) {\n // Resolves the suite now, so an unknown suite fails before any rotation.\n this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n if (keyRecord.meta.derivation) {\n if (derivedPolicy === 'error') {\n throw new Error(\n `Key ${keyRecord.meta.keyId} was derived from a seed ` +\n `(path ${keyRecord.meta.derivation.path || 'unknown'}). Rotating it here would ` +\n `replace it with a random key that the mnemonic cannot recover. Derive the ` +\n `successor yourself with createKeyFromMnemonic at a new path, or pass ` +\n `{ derivedKeys: 'skip' } or { derivedKeys: 'randomize' }. No keys were rotated.`\n );\n }\n if (derivedPolicy === 'skip') continue;\n }\n toRotate.push(keyRecord);\n }\n\n // Generate every replacement before committing any, so a failing suite\n // cannot leave the agent half rotated. The commits below are then one\n // registry rotation per key; they are not a single transaction, so a\n // storage failure part-way through leaves the earlier keys rotated.\n const replacements: Keypair[] = [];\n for (const keyRecord of toRotate) {\n const suite = this.suiteRegistry.getSuite(keyRecord.meta.suiteId);\n replacements.push(await suite.generateKeypair());\n }\n\n const newKeys: KeyRecord[] = [];\n \n for (const [i, keyRecord] of toRotate.entries()) {\n const newKeypair = replacements[i];\n \n const newMeta = await this.registerUnderFreshId(agentId, keyRecord.meta.suiteId, newKeyId =>\n this.keyRegistry.rotateKey(keyRecord.meta.keyId, newKeyId, newKeypair, {\n expiresAt: options.expiresAt,\n })\n );\n \n newKeys.push(toRecord(newMeta, newKeypair.publicKey));\n }\n \n return newKeys;\n }\n \n /**\n * Get or create key (idempotent).\n *\n * Concurrent calls on this SDK instance for the same agent and suite share\n * one creation. Two SDK instances (or processes) on one storage backend can\n * still each create a key; that needs a lock in the backend.\n */\n async getOrCreateKey(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n assertAgentId(agentId);\n const slot = JSON.stringify([agentId, profile.primarySignatureSuite]);\n\n const pending = this.getOrCreateInFlight.get(slot);\n if (pending) {\n const record = await pending;\n return toRecord(record.meta, record.publicKey);\n }\n\n const work = (async () => {\n // Check if key exists\n const existingKeys = await this.listKeysForAgent(agentId, true);\n const primaryKey = existingKeys.find(\n k => k.meta.suiteId === profile.primarySignatureSuite\n );\n \n if (primaryKey) {\n return primaryKey;\n }\n \n // Create new key\n return await this.createKey(agentId, profile, options);\n })();\n\n this.getOrCreateInFlight.set(slot, work);\n try {\n return await work;\n } finally {\n this.getOrCreateInFlight.delete(slot);\n }\n }\n\n /**\n * Create both primary and secondary keys for an agent.\n */\n async createDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.createKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Idempotent creation of both primary and secondary keys.\n */\n async getOrCreateDualSignatureKeys(\n agentId: string,\n profile: CryptoProfile,\n options: CreateKeyOptions = {}\n ): Promise<{ primaryKey: KeyRecord; secondaryKey: KeyRecord }> {\n if (!profile.secondarySignatureSuite) {\n throw new Error('secondarySignatureSuite is required to create dual signature keys');\n }\n this.assertDualProfile(profile);\n\n const primaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.primarySignatureSuite,\n }, options);\n\n const secondaryKey = await this.getOrCreateKey(agentId, {\n primarySignatureSuite: profile.secondarySignatureSuite,\n }, options);\n\n return { primaryKey, secondaryKey };\n }\n\n /**\n * Fail before creating either key if the pair could not be a hybrid pair:\n * an unknown suite, or the same suite twice (two ECDSA keys are not a\n * classical + post-quantum pair, whatever the profile calls them).\n */\n private assertDualProfile(profile: CryptoProfile): void {\n this.suiteRegistry.getSuite(profile.primarySignatureSuite);\n this.suiteRegistry.getSuite(profile.secondarySignatureSuite!);\n if (profile.primarySignatureSuite === profile.secondarySignatureSuite) {\n throw new Error(\n `Dual signature keys need two different suites; both are ${profile.primarySignatureSuite}`\n );\n }\n }\n\n /**\n * Sign with one or more suites for an agent.\n */\n async signWithSuites(\n agentId: string,\n message: Uint8Array,\n suites?: string[]\n ): Promise<MultiSignatureResult> {\n const activeKeys = this.sortKeysByCreatedAt(await this.listKeysForAgent(agentId, true));\n\n if (activeKeys.length === 0) {\n throw new Error(`No active keys found for agent: ${agentId}`);\n }\n\n const suitesToUse = Array.from(\n new Set(suites?.length ? suites : activeKeys.map(k => k.meta.suiteId))\n );\n const signatures: SuiteSignature[] = [];\n\n for (const suiteId of suitesToUse) {\n const key = activeKeys.find(k => k.meta.suiteId === suiteId);\n if (!key) {\n throw new Error(`No active key for suite '${suiteId}' and agent '${agentId}'`);\n }\n\n const signature = await this.signWithKey(key.meta.keyId, message);\n signatures.push({ suiteId, keyId: key.meta.keyId, signature });\n }\n\n return { signatures };\n }\n\n /**\n * Verify a set of signatures as a hybrid (multi-suite) signature by `agentId`.\n *\n * `allValid` is true only when ALL of these hold:\n * - at least one signature was supplied;\n * - every supplied signature is by a key that belongs to `agentId`, names\n * that key's real suite, passes the key-status policy, and verifies;\n * - every REQUIRED suite has such a signature.\n *\n * The required suites come from the verifier: `options.requiredSuites`, or\n * by default the suites of the agent's currently usable keys in this SDK's\n * registry. They are never read from `signatures`. The check walks the\n * required suites and looks each one up among the valid signatures, so an\n * empty list, or one that merely omits the post-quantum signature, is\n * refused instead of passing because everything in it happens to be valid.\n */\n async verifyWithSuites(\n agentId: string,\n message: Uint8Array,\n signatures: SuiteSignature[],\n options: VerifyWithSuitesOptions = {}\n ): Promise<MultiVerificationResult> {\n assertAgentId(agentId);\n const keyStatus = options.keyStatus ?? 'not-revoked';\n\n const requiredSuites = Array.from(\n new Set(\n options.requiredSuites ??\n (await this.listKeysForAgent(agentId, true)).map(k => k.meta.suiteId)\n )\n );\n\n const refuse = (error: string, results: SuiteVerificationResult[] = []): MultiVerificationResult => ({\n results,\n allValid: false,\n requiredSuites,\n missingSuites: requiredSuites.filter(s => !results.some(r => r.valid && r.suiteId === s)),\n error,\n });\n\n if (!Array.isArray(signatures)) {\n return refuse('signatures must be an array');\n }\n\n const results: SuiteVerificationResult[] = [];\n\n for (const entry of signatures) {\n const suiteId = String(entry?.suiteId);\n const keyId = String(entry?.keyId);\n const fail = (error: string) => results.push({ suiteId, keyId, valid: false, error });\n\n try {\n if (agentIdOfKey(keyId) !== agentId) {\n fail(`Key does not belong to agent '${agentId}'`);\n continue;\n }\n const key = await this.keyRegistry.getPublicKey(keyId);\n if (!key) {\n fail('Key not found');\n continue;\n }\n if (key.meta.suiteId !== suiteId) {\n fail(`Suite mismatch: key is ${key.meta.suiteId}, signature claims ${suiteId}`);\n continue;\n }\n if (!statusAllows(key.meta, keyStatus)) {\n fail(`Key status not accepted (status: ${key.meta.status ?? 'active'}, policy: ${keyStatus})`);\n continue;\n }\n if (!(entry.signature instanceof Uint8Array)) {\n fail('Signature must be a Uint8Array');\n continue;\n }\n const valid = await this.verifyAgainst(key.meta, key.publicKey, message, entry.signature, options.scheme ?? 'v4');\n if (valid) {\n results.push({ suiteId, keyId, valid: true });\n } else {\n fail('Signature verification failed');\n }\n } catch (error) {\n fail(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (requiredSuites.length === 0) {\n return refuse(\n `No required suites: agent '${agentId}' has no usable keys and options.requiredSuites was not given`,\n results\n );\n }\n if (results.length === 0) {\n return refuse('No signatures supplied', results);\n }\n\n // Walk the REQUIRED suites and look each up among the valid signatures.\n const missingSuites = requiredSuites.filter(\n required => !results.some(r => r.valid && r.suiteId === required)\n );\n const everySuppliedValid = results.every(r => r.valid === true);\n\n return {\n results,\n allValid: everySuppliedValid && missingSuites.length === 0,\n requiredSuites,\n missingSuites,\n ...(missingSuites.length > 0\n ? { error: `No valid signature for required suite(s): ${missingSuites.join(', ')}` }\n : {}),\n };\n }\n \n /**\n * Generate a new BIP39 mnemonic phrase.\n * \n * @param strength 128 (12 words) or 256 (24 words)\n * @returns Mnemonic phrase\n */\n generateMnemonic(strength: 128 | 256 = 256): string {\n const bip32 = new BIP32Derivation();\n return bip32.generateMnemonic(strength);\n }\n \n /**\n * Create a key from a BIP39 mnemonic using HD derivation.\n * \n * Only works with suites that support BIP32 derivation (e.g., bsv-ecdsa-secp256k1).\n * \n * @param agentId Agent identifier\n * @param profile Crypto profile (must use derivation-capable suite)\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path BIP32 derivation path (default: \"m/44'/0'/0'/0/0\")\n * @param passphrase Optional BIP39 passphrase\n * @param options Additional key creation options\n * @returns KeyRecord with derived key\n * @throws if the mnemonic has an unknown word, a wrong word count or a bad checksum\n */\n async createKeyFromMnemonic(\n agentId: string,\n profile: CryptoProfile,\n mnemonic: string,\n path: string = BIP32Derivation.bitcoinPath(0, 0, 0),\n passphrase?: string,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const bip32 = new BIP32Derivation();\n const seed = bip32.mnemonicToSeed(mnemonic, passphrase);\n \n try {\n return await this.createKey(agentId, profile, {\n ...options,\n derivationContext: {\n seed,\n path,\n },\n });\n } finally {\n // The seed is the root of every key in the wallet; do not leave it behind.\n seed.fill(0);\n }\n }\n \n /**\n * Get available capabilities for a specific suite.\n * \n * @param suiteId Suite identifier\n * @returns Array of capability names\n */\n getCapabilities(suiteId: string): string[] {\n const suite = this.suiteRegistry.getSuite(suiteId);\n const caps: string[] = [];\n \n if (suite.capabilities?.derivation) caps.push('derivation');\n if ((suite.capabilities as any)?.encryption) caps.push('encryption');\n if ((suite.capabilities as any)?.threshold) caps.push('threshold');\n \n return caps;\n }\n \n /**\n * Get all suite IDs that support a specific capability.\n * \n * @param capability Capability name\n * @returns Array of suite IDs\n */\n getSuitesWithCapability(capability: 'derivation' | 'encryption' | 'threshold'): string[] {\n const allSuites = this.suiteRegistry.getAllSuites();\n return allSuites\n .filter(suite => !!(suite.capabilities as any)?.[capability])\n .map(suite => suite.suiteId);\n }\n\n /**\n * Create a wallet key from a mnemonic at an explicit BIP44 coin type:\n * `m/44'/coinType'/account'/change/index`.\n *\n * The coin type is required and has no default. It decides which wallets\n * will find the key again: Bitcoin (BTC) is 0, Bitcoin SV is 236.\n *\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase (words and checksum are validated)\n * @param path Coin type and position in the BIP44 tree\n * @param options Additional key creation options\n * @returns KeyRecord with the derived secp256k1 key\n */\n async createWalletKey(\n agentId: string,\n mnemonic: string,\n path: WalletKeyPath,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n if (!path || typeof path.coinType !== 'number') {\n throw new Error(\n 'createWalletKey requires path.coinType (SLIP-44: Bitcoin is 0, Bitcoin SV is 236)'\n );\n }\n const derivationPath = BIP32Derivation.bip44Path(\n path.coinType,\n path.account ?? 0,\n path.change ? 1 : 0,\n path.index ?? 0\n );\n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n derivationPath,\n path.passphrase,\n options\n );\n }\n \n /**\n * Create a wallet key from mnemonic at the Bitcoin (BTC) BIP44 path:\n * m/44'/0'/account'/change/addressIndex\n *\n * NOTE: coin type 0 is BTC. A Bitcoin SV wallet restoring the same mnemonic\n * looks under coin type 236 and will not find this key. The path is left\n * as it is because changing it would move every key already created with\n * this method. For new code use {@link createWalletKey}, which makes the\n * coin type explicit.\n * \n * @deprecated Use createWalletKey(agentId, mnemonic, { coinType, ... }).\n * @param agentId Agent identifier\n * @param mnemonic BIP39 mnemonic phrase\n * @param accountIndex Account index (default: 0)\n * @param addressIndex Address index (default: 0)\n * @param isChange Use change address path (default: false)\n * @param options Additional key creation options\n * @returns KeyRecord with Bitcoin-compatible key\n */\n async createBitcoinWalletKey(\n agentId: string,\n mnemonic: string,\n accountIndex: number = 0,\n addressIndex: number = 0,\n isChange: boolean = false,\n options: CreateKeyOptions = {}\n ): Promise<KeyRecord> {\n const path = BIP32Derivation.bitcoinPath(accountIndex, isChange ? 1 : 0, addressIndex);\n \n return this.createKeyFromMnemonic(\n agentId,\n { primarySignatureSuite: 'bsv-ecdsa-secp256k1' },\n mnemonic,\n path,\n undefined,\n options\n );\n }\n \n /**\n * Helper: register a key under the agent's next free key ID.\n *\n * The counter is cached per SDK instance, so another instance (or process)\n * on the same storage can have taken the ID already. The registry refuses\n * to overwrite; on that refusal the counter is re-read from storage and the\n * next ID is tried. Before, the second writer silently replaced the first\n * writer's private key.\n */\n private async registerUnderFreshId(\n agentId: string,\n suiteId: string,\n register: (keyId: string) => Promise<KeyMeta>\n ): Promise<KeyMeta> {\n // 'ml' for every ml-dsa suite, 'bsv' for bsv-ecdsa-secp256k1\n const suiteName = suiteId.split('-')[0].replace(/[^A-Za-z0-9]/g, '') || 'key';\n\n for (let attempt = 0; attempt < MAX_KEY_ID_ATTEMPTS; attempt++) {\n const counter = await this.getNextCounter(agentId);\n const keyId = `${agentId}:pk-${suiteName}-${counter}`;\n try {\n return await register(keyId);\n } catch (error) {\n if (!(error instanceof KeyAlreadyExistsError)) throw error;\n // Someone else holds that ID: forget the cached counter and re-read.\n this.counterInitialized.delete(agentId);\n this.keyCounter.delete(agentId);\n }\n }\n throw new Error(\n `Could not allocate a key ID for agent '${agentId}' after ${MAX_KEY_ID_ATTEMPTS} attempts`\n );\n }\n \n /**\n * Helper: Get next counter for an agent.\n */\n private async getNextCounter(agentId: string): Promise<number> {\n if (!this.counterInitialized.has(agentId)) {\n if (!this.counterInitPromises.has(agentId)) {\n const initPromise = (async () => {\n try {\n const existing = await this.keyRegistry.listKeys();\n const max = existing.reduce((acc, meta) => {\n if (agentIdOfKey(meta.keyId) !== agentId) return acc;\n const local = meta.keyId.slice(agentId.length + 1);\n const match = COUNTER_SUFFIX.exec(local);\n if (!match) return acc;\n const num = parseInt(match[1], 10);\n return Number.isSafeInteger(num) ? Math.max(acc, num) : acc;\n }, 0);\n // A counter handed out while this scan ran must not be reused.\n this.keyCounter.set(agentId, Math.max(max, this.keyCounter.get(agentId) || 0));\n this.counterInitialized.add(agentId);\n } finally {\n this.counterInitPromises.delete(agentId);\n }\n })();\n this.counterInitPromises.set(agentId, initPromise);\n }\n\n const pendingInit = this.counterInitPromises.get(agentId);\n if (pendingInit) {\n await pendingInit;\n }\n }\n\n const current = this.keyCounter.get(agentId) || 0;\n const next = current + 1;\n this.keyCounter.set(agentId, next);\n return next;\n }\n\n /**\n * Helper: sort keys deterministically by createdAt then keyId.\n */\n private sortKeysByCreatedAt(keys: KeyRecord[]): KeyRecord[] {\n return [...keys].sort((a, b) => {\n const aTime = new Date(a.meta.createdAt).getTime();\n const bTime = new Date(b.meta.createdAt).getTime();\n if (aTime !== bTime) return aTime - bTime;\n const priorityDiff = this.getSuitePriority(a.meta.suiteId) - this.getSuitePriority(b.meta.suiteId);\n if (priorityDiff !== 0) return priorityDiff;\n return a.meta.keyId.localeCompare(b.meta.keyId);\n });\n }\n\n private getSuitePriority(suiteId: string): number {\n if (suiteId.startsWith('ml-dsa')) return 0;\n if (suiteId.includes('ecdsa')) return 1;\n return 2;\n }\n}\n\n/**\n * Create a KeySDK instance with default configuration\n * \n * Uses in-memory storage and registers both ECDSA and ML-DSA suites.\n * For custom storage or different suites, instantiate DefaultKeySDK directly.\n * \n * @example\n * ```typescript\n * import { createKeySDK } from '@smartledger/keys';\n * \n * const sdk = createKeySDK();\n * const key = await sdk.createKey('my-agent', { primarySignatureSuite: 'ml-dsa-87' });\n * ```\n */\nexport function createKeySDK(config?: Partial<KeySDKConfig>): KeySDK {\n const keyRegistry = config?.keyRegistry || new KeyRegistry(new InMemoryKeyStorage());\n const suiteRegistry = config?.suiteRegistry || new SignatureSuiteRegistry();\n \n // Register default suites if not provided.\n //\n // All three ML-DSA levels are registered, not just 87. The README documents\n // ml-dsa-65 as the recommended default and ml-dsa-44 for constrained\n // devices; registering only 87 made every one of those examples throw\n // `Unknown signature suite` at runtime, with no way for a caller to fix it\n // -- SignatureSuiteRegistry is not re-exported from this package.\n if (!config?.suiteRegistry) {\n suiteRegistry.register(new BsvEcdsaSuite());\n suiteRegistry.register(new MlDsa44Suite());\n suiteRegistry.register(new MlDsa65Suite());\n suiteRegistry.register(new MlDsa87Suite());\n }\n \n return new DefaultKeySDK({\n keyRegistry,\n suiteRegistry,\n signingContext: config?.signingContext,\n });\n}\n"],
|
|
5
|
+
"mappings": "0nBAUO,SAASA,GAAQC,EAAG,CAKvB,OAAQA,aAAa,YAChB,YAAY,OAAOA,CAAC,GACjBA,EAAE,YAAY,OAAS,cACvB,sBAAuBA,GACvBA,EAAE,oBAAsB,CACpC,CAiBO,SAASC,GAAQC,EAAGC,EAAQ,GAAI,CACnC,GAAI,OAAOD,GAAM,SACb,MAAM,IAAI,UAAUE,GAAOD,CAAK,EAAI,wBAA0B,OAAOD,CAAC,EAC1E,GAAI,CAAC,OAAO,cAAcA,CAAC,GAAKA,EAAI,EAChC,MAAM,IAAI,WAAWE,GAAOD,CAAK,EAAI,8BAAgCD,CAAC,EAC1E,OAAOA,CACX,CAaO,SAASG,GAAMC,EAAOH,EAAQ,GAAI,CACrC,GAAI,OAAOG,GAAU,UACjB,MAAM,IAAI,UAAUF,GAAOD,CAAK,EAAI,8BAAgC,OAAOG,CAAK,EACpF,OAAOA,CACX,CAeO,SAASC,EAAOD,EAAOE,EAAQL,EAAQ,GAAI,CAG9C,GAAIJ,GAAQO,CAAK,IAAME,IAAW,QAAaF,EAAM,SAAWE,GAC5D,OAAOF,EAEPE,IAAW,QACXP,GAAQO,EAAQ,QAAQ,EAC5B,IAAMC,EAAQV,GAAQO,CAAK,EACrBI,EAAQF,IAAW,OAAY,cAAcA,CAAM,GAAK,GACxDG,EAAMF,EAAQ,UAAUH,EAAM,MAAM,GAAK,QAAQ,OAAOA,CAAK,GAC7DM,EAAUR,GAAOD,CAAK,EAAI,sBAAwBO,EAAQ,SAAWC,EAC3E,MAAKF,EAEC,IAAI,WAAWG,CAAO,EADlB,IAAI,UAAUA,CAAO,CAEnC,CAgCO,SAASC,GAAMC,EAAG,CACrB,GAAI,OAAOA,GAAM,YAAc,OAAOA,EAAE,QAAW,WAC/C,MAAM,IAAI,UA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AAC,CAIH,CAKA,IAAOC,GAAQ,CACb,aAAAP,EACF,EAGI,OAAO,OAAW,MACnB,OAAe,UAAY,CAC1B,aAAAA,EACF",
|
|
6
|
+
"names": ["isBytes", "a", "anumber", "n", "title", "atitle", "abool", "value", "abytes", "length", "bytes", "ofLen", "got", "message", "ahash", "h", "aexists", "instance", "checkFinished", "aoutput", "out", "min", "u32", "arr", "clean", "arrays", "i", "createView", "rotr", "word", "shift", "rotl", "byteSwap", "byteSwap32", "bytesToHex", "hasHexBuiltin", "hex", "hexes", "asciiToBase16", "ch", "hexToBytes", "error", "hl", "al", "array", "ai", "hi", "n1", "n2", "char", "utf8ToBytes", "str", "kdfInputToBytes", "data", "errorTitle", "concatBytes", "sum", "res", "pad", "checkOpts", "defaults", "opts", "aobject", "createHasher", "hashCons", "info", "hashC", "msg", "tmp", "randomBytes", "bytesLength", "cr", "isLE", "swap32IfBE", "oidNist", "init_utils", "__esmMin", "label", "u", "_", "suffix", "fromBig", "n", "le", "U32_MASK64", "_32n", "split", "lst", "len", "Ah", "Al", "i", "h", "l", "setU64FromNum", "view", "byteOffset", "isLE", "fromNumH", "fromNumL", "add", "Bh", "Bl", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "add3L", "add3H", "add4L", "add4H", "add5L", "add5H", "init_u64", "__esmMin", "_l", "s", "Cl", "low", "Ch", "Dl", "Dh", "El", "Eh", "keccakP", "s", "rounds", "anumber", "round", "x", "B", "idx1", "idx0", "B0", "B1", "Th", "rotlH", "Tl", "rotlL", "y", "curH", "curL", "t", "shift", "SHA3_ROTL", "PI", "SHA3_PI", "b0", "b1", "b2", "b3", "SHA3_IOTA_H", "SHA3_IOTA_L", "clean", "_0n", "_1n", "_2n", "_7n", "_256n", "_0x71n", "_SHA3_IOTA", "IOTAS", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "Keccak", "genKeccak", "sha3_256", "genShake", "shake128", "shake256", "init_sha3", "__esmMin", "init_u64", "init_utils", "R", "j", "split", "h", "l", "_Keccak", "blockLen", "suffix", "outputLen", "enableXOF", "__publicField", "abool", "u32", "swap32IfBE", "data", "aexists", "abytes", "state", "state32", "len", "canUseU32", "blockLen32", "data32", "pos", "i", "o", "take", "out", "bufferOut", "bytes", "aoutput", "to", "info", "createHasher", "oidNist", "opts", "checkOpts", "aarray", "item", "title", "inner", "i", "astring", "value", "prefix", "aobject", "afunction", "abool", "atitle", "abignumber", "n", "isPosBig", "anumber", "asafenumber", "numberToHexUnpadded", "num", "hex", "hexToNumber", "_0n", "bytesToNumberBE", "bytes", "bytesToHex", "bytesToNumberLE", "copyBytes", "abytes", "numberToBytesBE", "len", "expectedLen", "hexToBytes", "numberToBytesLE", "inRange", "min", "max", "aInRange", "bitLen", "createHmacDrbg", "hashLen", "qByteLen", "hmacFn", "u8n", "NULL", "byte0", "byte1", "_maxDrbgIters", "v", "k", "reset", "h", "msgs", "concatBytes", "reseed", "seed", "gen", "out", "sl", "pred", "res", "validateObject", "object", "fields", "optFields", "checkField", "fieldName", "expectedType", "isOpt", "label", "val", "current", "iter", "f", "isBytes", "randomBytes", "_1n", "bitMask", "init_utils", "__esmMin", "length", "arrays", "bytesLength", "mod", "a", "b", "_0n", "result", "pow", "num", "power", "modulo", "_1n", "d", "POW_WINDOWED_MIN", "p", "digits", "_15n", "_4n", "table", "i", "w", "digit", "pow2", "x", "res", "invert", "number", "u", "q", "r", "m", "invertCt", "prime", "an", "inverse", "_2n", "assertIsSquare", "Fp", "root", "n", "F", "aoddModulus", "order", "fnName", "sqrt3mod4", "p1div4", "sqrt5mod8", "p5div8", "_5n", "_8n", "n2", "v", "nv", "sqrt9mod16", "P", "Fp_", "Field", "tn", "tonelliShanks", "c1", "c2", "c3", "c4", "_7n", "_16n", "tv1", "tv2", "tv3", "tv4", "e1", "e2", "e3", "_3n", "Q", "S", "Z", "_Fp", "FpLegendre", "cc", "Q1div2", "M", "c", "t", "R", "t_tmp", "exponent", "FpSqrt", "_9n", "validateField", "field", "aobject", "asafenumber", "name", "FIELD_FIELDS", "afunction", "FpInvertBatch", "nums", "passZero", "aarray", "abool", "inverted", "multipliedAcc", "acc", "invertedAcc", "p1mod2", "powered", "yes", "zero", "no", "nLength", "nBitLength", "anumber", "bits", "bitLen", "_nBitLength", "nByteLength", "ORDER", "opts", "_Field", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "abytes", "len", "fieldLen", "minLen", "bytesToNumberLE", "bytesToNumberBE", "reduced", "numberToBytesLE", "numberToBytesBE", "FIELD_SQRT", "init_modular", "__esmMin", "init_utils", "__publicField", "_nbitLength", "lhs", "rhs", "sqrt", "bytes", "skipValidation", "allowedLengths", "BYTES", "modFromBytes", "padded", "scalar", "lst", "condition", "checkU32", "n", "title", "isPowerOfTwo", "x", "reverseBits", "bits", "reversed", "i", "log2", "bitReversalInplace", "values", "j", "tmp", "FFTCore", "init_fft", "__esmMin", "init_utils", "F", "coreOpts", "validateObject", "N", "roots", "dit", "invertButterflies", "skipStages", "brp", "maxSkipStages", "isDit", "g", "s", "m", "m2", "stride", "k", "grp", "rootPos", "i0", "i1", "omega", "b", "a", "t", "aarray", "item", "title", "inner", "i", "aobject", "value", "equalBytes", "a", "b", "abytes", "diff", "validateOpts", "opts", "isBytes", "validateVerOpts", "validateSigOpts", "splitCoder", "label", "lengths", "getLength", "c", "bytesLen", "sum", "bufs", "res", "pos", "l", "buf", "vecCoder", "vecLen", "coder", "u", "uArr", "r", "cleanBytes", "list", "t", "getMask", "bits", "anumber", "getMessage", "msg", "ctx", "EMPTY", "concatBytes", "checkHash", "hash", "requiredStrength", "ahash", "oid", "oidNistP", "collisionResistance", "getMessagePrehash", "hashed", "abytesDoc", "randomBytes", "init_utils", "__esmMin", "genCrystals", "createXofShake", "XOF128", "XOF256", "init_crystals", "__esmMin", "init_fft", "init_sha3", "init_utils", "opts", "newPoly", "N", "Q", "F", "ROOT_OF_UNITY", "brvBits", "isKyber", "mod", "a", "modulo", "result", "smod", "r", "getZettas", "out", "i", "b", "reverseBits", "p", "nttZetas", "inv", "_a", "field", "nttOpts", "dif", "FFTCore", "dit", "NTT", "d", "c", "bufLen", "getMask", "mask", "bytesLen", "poly_", "poly", "buf", "pos", "bytes", "shake", "seed", "blockLen", "_seed", "seedLen", "h", "calls", "xofs", "x", "y", "cleanBytes", "shake128", "shake256", "ml_dsa_exports", "__export", "PARAMS", "ml_dsa44", "ml_dsa65", "ml_dsa87", "validateInternalOpts", "opts", "validateOpts", "abool", "RejNTTPoly", "xof_", "xof", "newPoly", "N", "j", "b", "i", "t", "Q", "getDilithium", "opts_", "K", "L", "GAMMA1", "GAMMA2", "TAU", "ETA", "OMEGA", "CRH_BYTES", "TR_BYTES", "C_TILDE_BYTES", "XOF128", "XOF256", "securityLevel", "GAMMA2_1", "GAMMA2_2", "BETA", "decompose", "r", "rPlus", "crystals", "r0", "HighBits", "LowBits", "MakeHint", "z", "HINT_M", "UseHint", "h", "r1", "Power2Round", "D", "hintCoder", "h_", "res", "k", "buf", "hi", "ETACoder", "polyCoder", "T0Coder", "T1Coder", "ZCoder", "W1Coder", "W1Vec", "vecCoder", "publicCoder", "splitCoder", "secretCoder", "sigCoder", "CoefFromHalfByte", "n", "RejBoundedPoly", "d1", "d2", "SampleInBall", "seed", "pre", "s", "shake256", "masks", "pos", "maskPos", "maskBit", "polyPowerRound", "p_", "p", "res0", "res1", "polyUseHint", "u_", "u", "polyMakeHint", "a_", "b_", "a", "v", "cnt", "signRandBytes", "seedCoder", "internal", "seedDst", "randSeed", "randomBytes", "abytesDoc", "cleanBytes", "rho", "rhoPrime", "K_", "xofPrime", "s1", "s2", "s1Hat", "t0", "t1", "aij", "polyAdd", "MultiplyNTTs", "publicKey", "tr", "secretKey", "_K", "_tr", "_t0", "tmp", "msg", "validateSigOpts", "random", "externalMu", "ownRnd", "rnd", "decoded", "error", "A", "pv", "mu", "rhoprime", "x256", "main_loop", "kappa", "y", "w", "wi", "w1", "cTilde", "cHat", "cs1", "polyChknorm", "cs2", "polySub", "ct0", "hint", "sig", "c", "zNtt", "wTick1", "ct12d", "polyShiftl", "Az", "wApprox", "c2", "acc", "equalBytes", "M", "getMessage", "validateVerOpts", "hash", "checkHash", "rawHash", "getMessagePrehash", "ROOT_OF_UNITY", "F", "id", "init_ml_dsa", "__esmMin", "init_utils", "init_sha3", "init_crystals", "genCrystals", "d", "compress", "verify", "B", "browser_exports", "__export", "InMemoryKeyStorage", "KeyRegistry", "createKeySDK", "browser_default", "secp256k1_CURVE", "P", "N", "Gx", "Gy", "_b", "L", "L2", "lengths", "err", "message", "E", "e", "captureStackTrace", "isBytes", "a", "abytes", "value", "length", "title", "bytes", "len", "needsLen", "prefix", "ofLen", "got", "msg", "u8n", "padh", "n", "pad", "bytesToHex", "b", "hex", "C", "_ch", "ch", "hexToBytes", "hl", "al", "array", "ai", "hi", "n1", "n2", "subtle", "concatBytes", "arrs", "randomBytes", "big", "arange", "min", "max", "M", "modN", "invert", "num", "md", "x", "y", "u", "v", "q", "r", "m", "callHash", "name", "fn", "hashes", "gh", "gha", "apoint", "p", "Point", "err", "koblitz", "x", "M", "_b", "FpIsValid", "n", "arange", "P", "FpIsValidNot0", "FnIsValidNot0", "N", "isEven", "y", "u8of", "getPrefix", "lift_x", "c", "num", "e", "_Point", "X", "Y", "Z", "__publicField", "FpIsValid", "FpIsValidNot0", "secp256k1_CURVE", "ap", "x", "y", "I", "bytes", "abytes", "comp", "uncomp", "lengths", "p", "length", "head", "tail", "sliceBytesNumBE", "L", "lift_x", "M", "L2", "err", "hex", "hexToBytes", "other", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "apoint", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "a", "b", "_b", "X3", "Y3", "Z3", "b3", "t0", "t1", "t2", "t3", "t4", "t5", "n", "safe", "FnIsValidNot0", "G", "wNAF", "f", "d", "scalar", "z", "iz", "invert", "P", "koblitz", "isCompressed", "x32b", "numTo32b", "concatBytes", "getPrefix", "u8of", "bytesToHex", "Point", "Gx", "Gy", "doubleScalarMulUns", "R", "u1", "u2", "bytesToNumBE", "big", "from", "to", "B256", "num", "padh", "arange", "secretKeyToScalar", "secretKey", "N", "highS", "getPublicKey", "privKey", "isValidSecretKey", "isValidPublicKey", "publicKey", "publicKeyUncompressed", "l", "assertRecoveryBit", "recovery", "assertSigFormat", "format", "SIG_DER", "SIG_COMPACT", "SIG_RECOVERED", "assertSigLength", "sig", "len", "Signature", "_Signature", "r", "s", "rec", "bit", "res", "bits2int", "delta", "bits2int_modN", "modN", "_sha", "hashes", "key", "message", "subtle", "name", "k", "u8n", "msg", "prepMsg", "opts", "async_", "gha", "gh", "NULL", "byte0", "byte1", "_maxDrbgIters", "_drbgErr", "hmacDrbg", "seed", "pred", "v", "i", "reset", "h", "reseed", "gen", "_sign", "messageHash", "secretKey", "opts", "hmacDrbg", "lowS", "extraEntropy", "int2octets", "numTo32b", "h1i", "bits2int_modN", "h1o", "d", "secretKeyToScalar", "seedArgs", "e", "randomBytes", "L", "abytes", "seed", "concatBytes", "m", "kBytes", "k", "bits2int", "N", "ik", "invert", "q", "G", "r", "modN", "s", "recovery", "normS", "highS", "Signature", "_verify", "sig", "publicKey", "format", "err", "assertSigLength", "h", "P", "Point", "is", "u1", "u2", "R", "doubleScalarMulUns", "setDefaults", "SIG_COMPACT", "sign", "message", "assertSigFormat", "msg", "prepMsg", "verify", "signature", "message", "publicKey", "opts", "setDefaults", "msg", "prepMsg", "_verify", "randomSecretKey", "seed", "randomBytes", "lengths", "abytes", "err", "num", "M", "bytesToNumBE", "N", "numTo32b", "utils", "isValidSecretKey", "isValidPublicKey", "randomSecretKey", "W", "scalarBits", "pwindows", "pwindowSize", "precompute", "points", "p", "G", "b", "w", "i", "Gpows", "ctneg", "cnd", "n", "wNAF", "comp", "I", "f", "pow_2_w", "maxNum", "mask", "big", "shiftBy", "wbits", "off", "offF", "offP", "isEven", "isNeg", "err", "init_utils", "_HMAC", "hash", "key", "__publicField", "ahash", "abytes", "blockLen", "pad", "i", "clean", "buf", "aexists", "out", "aoutput", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "canXOF", "hmac", "hmac_", "message", "init_u64", "init_utils", "Chi", "a", "b", "c", "Maj", "HashMD", "blockLen", "outputLen", "padOffset", "isLE", "__publicField", "createView", "data", "aexists", "abytes", "view", "buffer", "len", "processed", "pos", "take", "dataView", "out", "aoutput", "setU64FromNum", "oview", "outLen", "state", "i", "res", "to", "length", "finished", "destroyed", "SHA256_IV", "SHA512_IV", "init_u64", "init_utils", "SHA256_K", "SHA256_W", "SHA2_32B", "HashMD", "outputLen", "IV", "__publicField", "A", "B", "C", "D", "E", "F", "G", "H", "to", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "clean", "_SHA256", "SHA256_IV", "K512", "split", "n", "SHA512_Kh", "SHA512_Kl", "SHA512_W_H", "SHA512_W_L", "SHA2_64B", "HashMD", "outputLen", "IV", "__publicField", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "to", "view", "offset", "i", "W15h", "W15l", "s0h", "rotrSH", "shrSH", "s0l", "rotrSL", "shrSL", "W2h", "W2l", "s1h", "rotrBH", "s1l", "rotrBL", "SUMl", "add4L", "SUMh", "add4H", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "add5L", "T1h", "add5H", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "add", "All", "add3L", "add3H", "clean", "_SHA512", "SHA512_IV", "sha256", "createHasher", "_SHA256", "oidNist", "sha512", "createHasher", "_SHA512", "oidNist", "init_sha3", "bytesToHex", "bytes", "b", "hexToBytes", "hex", "i", "hashBytes", "bytes", "algorithm", "sha256", "sha512", "sha3_256", "init_utils", "init_modular", "_0n", "_1n", "_4n", "BLIND_BYTES", "BLIND_BITS", "FW_WINDOW", "TABLE_BYTES_MAX", "validatePointCons", "Point", "pc", "afunction", "aobject", "validateField", "normalizeZ", "c", "points", "validateMSMPoints", "invertedZs", "FpInvertBatch", "p", "i", "validateW", "W", "bits", "min", "validateTableBytes", "numPoints", "fpBytes", "bytes", "probeRandomBytes", "randomBytes", "length", "probe", "isBytes", "aarray", "validateMSMScalars", "scalars", "field", "maxScalar", "s", "isPosBig", "pointWindowSizes", "getWindowSize", "P", "oddMultiples", "size", "dbl", "t", "j", "wnafDigits", "n", "half", "mask", "d", "w", "signedWindowDigits", "windows", "shiftBy", "v", "wnafWalk", "zero", "tables", "digits", "max", "acc", "bit", "item", "ScalarMultiplier", "__publicField", "point", "comp", "base", "precomputes", "digit", "start", "idx", "sel", "neg", "transform", "entries", "entry", "scalar", "inRange", "blind", "bytesToNumberBE", "bitMask", "table", "window", "cofactor", "mulAddUnsafe", "allowOversized", "abool", "createField", "order", "field", "isLE", "validateField", "Field", "createCurveFields", "type", "CURVE", "curveOpts", "FpFnLE", "validateObject", "p", "val", "isPosBig", "_0n", "Fp", "Fn", "params", "createKeygen", "randomSecretKey", "getPublicKey", "seed", "secretKey", "init_modular", "init_utils", "init_utils", "_0n", "DERErr", "m", "_DER", "tag", "data", "E", "asafenumber", "astring", "dataLen", "len", "numberToHexUnpadded", "lenLen", "abytes", "pos", "first", "isLong", "length", "lengthBytes", "b", "v", "num", "abignumber", "hex", "bytesToNumberBE", "bytes", "int", "tlv", "seqBytes", "seqLeftBytes", "rBytes", "rLeftBytes", "sBytes", "sLeftBytes", "sig", "validateObject", "rs", "ss", "seq", "DER", "init_modular", "divNearest", "num", "den", "_2n", "_splitEndoScalar", "k", "basis", "n", "aInRange", "_0n", "a1", "b1", "a2", "b2", "c1", "c2", "k1", "k2", "k1neg", "k2neg", "MAX_NUM", "bitMask", "bitLen", "_1n", "validateSigFormat", "format", "validateSigOpts", "opts", "def", "validateObject", "optsn", "optName", "abool", "_3n", "_4n", "weierstrass", "params", "extraOpts", "validated", "createCurveFields", "Fp", "Fn", "CURVE", "cofactor", "CURVE_ORDER", "endo", "allowInfinityPoint", "randomBytes", "lengths", "getWLengths", "assertCompressionIsSupported", "pointToBytes", "_c", "point", "isCompressed", "x", "y", "bx", "hasEvenY", "concatBytes", "pprefix", "pointFromBytes", "bytes", "abytes", "comp", "uncomp", "length", "head", "tail", "y2", "weierstrassEquation", "sqrtError", "err", "evenY", "L", "isValidXY", "encodePoint", "decodePoint", "b3", "mulA", "_", "x2", "x3", "left", "right", "_4a3", "_27b2", "acoord", "title", "banZero", "aprjpoint", "other", "Point", "splitEndoScalarN", "pushWnafPair", "points", "scalars", "p", "psi", "validityCache", "_Point", "X", "Y", "Z", "__publicField", "P", "hex", "hexToBytes", "windowSize", "isLazy", "wnaf", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "scalar", "f", "normalize", "sc", "mulAddUnsafe", "a", "b", "invertedZ", "iz", "is0", "zz", "isTorsionFree", "clearCofactor", "bytesToHex", "normalizeZ", "ScalarMultiplier", "ecdh", "ecdhOpts", "validatePointCons", "randomBytes_", "getMinHashLength", "isValidSecretKey", "secretKey", "isValidPublicKey", "publicKey", "publicKeyUncompressed", "l", "randomSecretKey", "seed", "mapHashToField", "getPublicKey", "isProbPub", "item", "allowedLengths", "isBytes", "isPub", "isSec", "getSharedSecret", "secretKeyA", "publicKeyB", "s", "utils", "keygen", "createKeygen", "ecdsa", "hash", "ecdsaOpts", "hash_", "ahash", "hmac", "key", "msg", "fnBits", "blindLength", "csprng", "probeRandomBytes", "defaultSigOpts", "hasLargeRecoveryLifts", "isBiggerThanHalfOrder", "number", "HALF", "validateRS", "assertFieldSignIsSupported", "getRecoveryBit", "r", "assertRecoverableCurve", "validateSigLength", "size", "sizer", "Signature", "recovery", "recid", "DER", "messageHash", "radj", "R", "ir", "h", "bits2int_modN", "u1", "u2", "Q", "rb", "sb", "bits2int", "bytesToNumberBE", "delta", "ORDER_MASK", "int2octets", "validateMsgAndHash", "message", "prehash", "prepSig", "lowS", "extraEntropy", "h1int", "d", "seedArgs", "e", "m", "k2sig", "kBytes", "q", "ibk", "bm", "bd", "ik", "invertCt", "normS", "sign", "createHmacDrbg", "verify", "signature", "end", "sig", "is", "recoverPublicKey", "secp256k1_CURVE", "secp256k1_ENDO", "_2n", "sqrtMod", "y", "P", "secp256k1_CURVE", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fpk1", "Field", "Pointk1", "weierstrass", "secp256k1_ENDO", "secp256k1", "ecdsa", "sha256", "init_utils", "Rho160", "Id160", "_", "i", "Pi160", "idxLR", "res", "j", "k", "idxL", "idxR", "shifts160", "shiftsL160", "idx", "shiftsR160", "Kl160", "Kr160", "ripemd_f", "group", "x", "y", "z", "BUF_160", "_RIPEMD160", "HashMD", "__publicField", "h0", "h1", "h2", "h3", "h4", "to", "view", "offset", "al", "ar", "bl", "br", "cl", "cr", "dl", "dr", "el", "er", "rGroup", "hbl", "hbr", "rl", "rr", "sl", "sr", "tl", "rotl", "tr", "clean", "ripemd160", "createHasher", "init_utils", "freeze", "fn", "isBytes", "a", "abytes", "b", "afn", "input", "astr", "label", "anumber", "n", "title", "chain", "args", "id", "a", "wrap", "b", "c", "encode", "x", "decode", "asciiDecoder", "decoder", "B2S_CHUNK", "charcodesToString", "codes", "len", "res", "i", "alphabet", "letters", "aliases", "len", "encTable", "decTable", "i", "code", "alias", "target", "digits", "codes", "d", "charcodesToString", "input", "astr", "slen", "digit", "checksum", "len", "fn", "anumber", "afn", "_fn", "data", "abytes", "sum", "res", "payload", "oldChecksum", "newChecksum", "i", "B58_GROUP", "radix58", "bytes", "abytes", "blen", "zeros", "nlimbs", "limbs", "odd", "i", "j", "groups", "pos", "carry", "cur", "q", "top", "sig", "v", "res", "g", "k", "digits", "dlen", "used", "group", "gval", "factor", "end", "d", "valueBytes", "limb", "genBase58", "abc", "chain", "alphabet", "base58", "freeze", "createBase58check", "sha256", "afn", "_sha256", "chain", "checksum", "data", "base58", "Point", "secp256k1", "Fn", "base58check", "createBase58check", "sha256", "MASTER_SECRET", "char", "BITCOIN_VERSIONS", "HARDENED_OFFSET", "hash160", "data", "ripemd160", "fromU32", "createView", "toU32", "n", "title", "buf", "validateVersions", "versions", "HDKey", "_HDKey", "opt", "__publicField", "priv", "concatBytes", "seed", "abytes", "I", "hmac", "sha512", "privateKey", "chainCode", "base58key", "keyBuffer", "keyView", "version", "key", "isPriv", "json", "path", "parts", "child", "c", "m", "m1", "idx", "index", "_I", "out", "childTweak", "ctweak", "added", "point", "hash", "signature", "init_utils", "pbkdf2Init", "hash", "_password", "_salt", "_opts", "ahash", "opts", "checkOpts", "c", "dkLen", "asyncTick", "anumber", "p", "kdfInputToBytes", "s", "DK", "iHash", "oHash", "outputLen", "hmac", "u", "eng", "pbkdf2Engine", "salt", "counter", "view", "createView", "salted", "work", "iClone", "oClone", "ti", "Ti", "ui", "i", "clean", "pbkdf2", "password", "pos", "init_utils", "isJapanese", "wordlist", "nfkd", "str", "normalize", "norm", "words", "aentropy", "ent", "abytes", "generateMnemonic", "strength", "anumber", "entropyToMnemonic", "randomBytes", "calcChecksum", "entropy", "bitsLeft", "sha256", "awordlist", "i", "encodeWords", "bytes", "carry", "bits", "byte", "decodeWords", "entLen", "pos", "word", "index", "mnemonicToEntropy", "mnemonic", "validateMnemonic", "psalt", "passphrase", "mnemonicToSeedSync", "mnemonic", "passphrase", "pbkdf2", "sha512", "normalize", "psalt", "wordlist", "BIP32Derivation", "context", "childKey", "HDKey", "error", "mnemonic", "passphrase", "validateMnemonic", "wordlist", "mnemonicToSeedSync", "strength", "generateMnemonic", "account", "change", "index", "coinType", "name", "v", "BASE58_ALPHABET", "base58Encode", "data", "num", "byte", "encoded", "remainder", "base58Decode", "str", "char", "index", "bytes", "encodeWIF", "privateKey", "compressed", "network", "version", "payload", "hash1", "sha256", "checksum", "decodeWIF", "wif", "expectedChecksum", "i", "hashes", "msg", "sha256", "key", "hmac", "assertValidSecretKey", "bytes", "utils", "BsvEcdsaSuite", "__publicField", "BIP32Derivation", "privateKey", "publicKey", "getPublicKey", "message", "options", "sign", "error", "signature", "verify", "pub", "bytesToHex", "encoded", "hexToBytes", "priv", "encodeWIF", "decodeWIF", "ml_dsa44_lib", "ml_dsa65_lib", "ml_dsa87_lib", "getMlDsa44", "getMlDsa65", "getMlDsa87", "contextOption", "options", "context", "ML_DSA_SIZES", "BaseMlDsaSuite", "__publicField", "keypair", "error", "privateKey", "message", "publicKey", "signature", "lib", "pub", "bytesToHex", "encoded", "bytes", "hexToBytes", "priv", "MlDsa44Suite", "MlDsa65Suite", "MlDsa87Suite", "SignatureSuiteRegistry", "__publicField", "suite", "suiteId", "globalRegistry", "BsvEcdsaSuite", "MlDsa44Suite", "MlDsa65Suite", "MlDsa87Suite", "SmartLedgerCryptoError", "message", "code", "__publicField", "KeyNotFoundError", "keyId", "KeyAlreadyExistsError", "KeyExpiredError", "expiresAt", "KeyInvalidStateError", "currentState", "requiredState", "InvalidKeyParametersError", "SmartLedgerCryptoError", "message", "agentIdOfKey", "keyId", "i", "cloneKeyMeta", "meta", "cloneKeypair", "keypair", "isKeyUsable", "now", "expires", "assertKeyUsable", "KeyInvalidStateError", "KeyExpiredError", "assertValidExpiry", "expiresAt", "InvalidKeyParametersError", "InMemoryKeyStorage", "__publicField", "found", "filter", "allMeta", "k", "key", "value", "u", "updates", "existing", "KeyNotFoundError", "KeyRegistry", "storage", "suiteId", "options", "KeyAlreadyExistsError", "result", "allKeys", "oldKeyId", "newKeyId", "newKeypair", "oldKey", "lifetime", "newMeta", "error", "reason", "count", "retentionDays", "cutoffDate", "DEFAULT_SIGNING_CONTEXT", "COUNTER_SUFFIX", "MAX_KEY_ID_ATTEMPTS", "assertAgentId", "agentId", "toRecord", "meta", "publicKey", "cloneKeyMeta", "statusAllows", "policy", "isKeyUsable", "DefaultKeySDK", "config", "context", "DEFAULT_SIGNING_CONTEXT", "bytes", "profile", "options", "suite", "keypair", "available", "keyId", "result", "message", "assertKeyUsable", "u", "input", "suiteId", "scheme", "hashBytes", "signature", "activeOnly", "agentKeys", "agentIdOfKey", "records", "keys", "sorted", "suites", "k", "suiteArray", "derivedPolicy", "activeKeys", "toRotate", "keyRecord", "replacements", "newKeys", "i", "newKeypair", "newMeta", "newKeyId", "slot", "pending", "record", "work", "primaryKey", "secondaryKey", "suitesToUse", "signatures", "key", "keyStatus", "requiredSuites", "refuse", "error", "results", "s", "r", "entry", "fail", "missingSuites", "required", "everySuppliedValid", "strength", "BIP32Derivation", "mnemonic", "path", "passphrase", "seed", "caps", "capability", "derivationPath", "accountIndex", "addressIndex", "isChange", "register", "suiteName", "attempt", "counter", "KeyAlreadyExistsError", "initPromise", "max", "acc", "local", "match", "num", "pendingInit", "next", "a", "b", "aTime", "bTime", "priorityDiff", "createKeySDK", "config", "keyRegistry", "KeyRegistry", "InMemoryKeyStorage", "DefaultKeySDK", "globalRegistry", "browser_default"]
|
|
7
7
|
}
|