@honeybbq/teamspeak-client 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/command/index.cjs +1 -1
  2. package/dist/command/index.mjs +2 -2
  3. package/dist/{command-caXc4h0n.js → command-CTDmBXd_.js} +1 -1
  4. package/dist/{command-caXc4h0n.js.map → command-CTDmBXd_.js.map} +1 -1
  5. package/dist/{command-Cu2v-5-K.cjs → command-CUPNiKRl.cjs} +2 -2
  6. package/dist/{command-Cu2v-5-K.cjs.map → command-CUPNiKRl.cjs.map} +1 -1
  7. package/dist/crypt-handshake-D2Rsi2e3.cjs +2 -0
  8. package/dist/{crypt-handshake-Dbj2cSBZ.cjs.map → crypt-handshake-D2Rsi2e3.cjs.map} +1 -1
  9. package/dist/crypt-handshake-DIj51kno.js +55 -0
  10. package/dist/{crypt-handshake-CHmvZ2qs.js.map → crypt-handshake-DIj51kno.js.map} +1 -1
  11. package/dist/{crypt-init2-DWX7Tp-_.js → crypt-init2-C2X9oK4i.js} +24 -26
  12. package/dist/{crypt-init2-DWX7Tp-_.js.map → crypt-init2-C2X9oK4i.js.map} +1 -1
  13. package/dist/crypt-init2-CazdFwqF.cjs +2 -0
  14. package/dist/{crypt-init2-C2oihZ7e.cjs.map → crypt-init2-CazdFwqF.cjs.map} +1 -1
  15. package/dist/crypto/index.cjs +1 -1
  16. package/dist/crypto/index.mjs +2 -2
  17. package/dist/{crypto-VC7n6YJb.js → crypto-CwIMggQG.js} +4 -4
  18. package/dist/{crypto-VC7n6YJb.js.map → crypto-CwIMggQG.js.map} +1 -1
  19. package/dist/{crypto-2veVY1fC.cjs → crypto-IbzNNTgO.cjs} +2 -2
  20. package/dist/{crypto-2veVY1fC.cjs.map → crypto-IbzNNTgO.cjs.map} +1 -1
  21. package/dist/discovery/index.cjs +1 -1
  22. package/dist/discovery/index.mjs +1 -1
  23. package/dist/handler-BJdwhtkp.cjs +2 -0
  24. package/dist/{handler-CqCD93f0.cjs.map → handler-BJdwhtkp.cjs.map} +1 -1
  25. package/dist/{handler-C_JhqGTd.js → handler-BP38rMNl.js} +18 -18
  26. package/dist/{handler-C_JhqGTd.js.map → handler-BP38rMNl.js.map} +1 -1
  27. package/dist/handshake/index.cjs +1 -1
  28. package/dist/handshake/index.mjs +2 -2
  29. package/dist/index.cjs +1 -1
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.mjs +11 -11
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/{parser-DhAWj-TI.cjs → parser-B6cGUByG.cjs} +2 -2
  34. package/dist/{parser-DhAWj-TI.cjs.map → parser-B6cGUByG.cjs.map} +1 -1
  35. package/dist/{parser-CJjP3LlO.js → parser-BPzO8py_.js} +2 -2
  36. package/dist/{parser-CJjP3LlO.js.map → parser-BPzO8py_.js.map} +1 -1
  37. package/dist/primitives-Bt-L4BZa.js +1483 -0
  38. package/dist/primitives-Bt-L4BZa.js.map +1 -0
  39. package/dist/primitives-ClIhDdNZ.cjs +2 -0
  40. package/dist/primitives-ClIhDdNZ.cjs.map +1 -0
  41. package/dist/{resolver-DDD2FFhD.cjs → resolver-B7jho9CP.cjs} +3 -3
  42. package/dist/{resolver-DDD2FFhD.cjs.map → resolver-B7jho9CP.cjs.map} +1 -1
  43. package/dist/{resolver-Br0QefWx.js → resolver-BDCF2KbM.js} +2 -2
  44. package/dist/{resolver-Br0QefWx.js.map → resolver-BDCF2KbM.js.map} +1 -1
  45. package/dist/transport/index.cjs +1 -1
  46. package/dist/transport/index.mjs +1 -1
  47. package/dist/{types-DrnoCdSW.cjs → types-ANvuLFWH.cjs} +2 -2
  48. package/dist/{types-DrnoCdSW.cjs.map → types-ANvuLFWH.cjs.map} +1 -1
  49. package/dist/{types-CGKgXvpG.js → types-Xm1vrW4s.js} +1 -1
  50. package/dist/{types-CGKgXvpG.js.map → types-Xm1vrW4s.js.map} +1 -1
  51. package/package.json +3 -3
  52. package/dist/crypt-handshake-CHmvZ2qs.js +0 -55
  53. package/dist/crypt-handshake-Dbj2cSBZ.cjs +0 -2
  54. package/dist/crypt-init2-C2oihZ7e.cjs +0 -2
  55. package/dist/handler-CqCD93f0.cjs +0 -2
  56. package/dist/primitives-BIAYfJ2Y.js +0 -1842
  57. package/dist/primitives-BIAYfJ2Y.js.map +0 -1
  58. package/dist/primitives-bj-ml31v.cjs +0 -2
  59. package/dist/primitives-bj-ml31v.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"primitives-Bt-L4BZa.js","names":["isBytes","anumber","abytes","bytesToHex","hexToBytes","concatBytes","randomBytes","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","abytes_","anumber_","bytesToHex_","concatBytes_","hexToBytes_","isBytes_","randomBytes","randomBytes_","_0n","_1n","_0n","_1n","_2n","_5n","_8n","gcd","_0n","_1n","_0n","_1n","_2n","_8n","wcRandomBytes","hexToBytes"],"sources":["../src/errors.ts","../src/crypto/identity.ts","../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js","../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_md.js","../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js","../node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha2.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/utils.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/modular.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/curve.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/edwards.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/abstract/hash-to-curve.js","../node_modules/.pnpm/@noble+curves@2.2.0/node_modules/@noble/curves/ed25519.js","../src/crypto/primitives.ts"],"sourcesContent":["export class TeamspeakError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"TeamspeakError\";\n }\n}\n\nexport class ServerError extends TeamspeakError {\n readonly id: string;\n readonly serverMessage: string;\n\n constructor(id: string, serverMessage: string) {\n super(`TeamSpeak server error: ${serverMessage} (id=${id})`);\n this.name = \"ServerError\";\n this.id = id;\n this.serverMessage = serverMessage;\n }\n}\n\nexport class CommandTimeoutError extends TeamspeakError {\n readonly command: string;\n\n constructor(command: string) {\n super(`command timeout: ${command}`);\n this.name = \"CommandTimeoutError\";\n this.command = command;\n }\n}\n\nexport class AlreadyConnectedError extends TeamspeakError {\n constructor() {\n super(\"already connecting or connected\");\n this.name = \"AlreadyConnectedError\";\n }\n}\n\nexport class EAXTagMismatchError extends TeamspeakError {\n constructor() {\n super(\"EAX tag mismatch\");\n this.name = \"EAXTagMismatchError\";\n }\n}\n\nexport class FakeSignatureMismatchError extends TeamspeakError {\n constructor() {\n super(\"fake signature mismatch\");\n this.name = \"FakeSignatureMismatchError\";\n }\n}\n\nexport class FileTransferError extends TeamspeakError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"FileTransferError\";\n }\n}\n\nexport class FileTransferTimeoutError extends TeamspeakError {\n constructor() {\n super(\"timeout waiting for file transfer notification\");\n this.name = \"FileTransferTimeoutError\";\n }\n}\n\nexport class CryptoInitError extends TeamspeakError {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = \"CryptoInitError\";\n }\n}\n\nexport class InvalidIdentityError extends TeamspeakError {\n constructor(message = \"invalid identity format\") {\n super(message);\n this.name = \"InvalidIdentityError\";\n }\n}\n","import {\n createHash,\n createECDH,\n generateKeyPairSync,\n createPrivateKey,\n createPublicKey,\n type KeyObject,\n} from \"node:crypto\";\nimport { InvalidIdentityError } from \"../errors.js\";\n\nconst P256_SCALAR_SIZE = 32;\nconst P256_UNCOMPRESSED_KEY_SIZE = 65;\nconst P256_POINT_PREFIX = 0x04;\n\nexport class Identity {\n readonly privateKey: KeyObject;\n offset: bigint;\n\n constructor(privateKey: KeyObject, offset: bigint) {\n this.privateKey = privateKey;\n this.offset = offset;\n }\n\n publicKeyBase64(): string {\n const pubKey = createPublicKey(this.privateKey);\n const rawJwk = pubKey.export({ format: \"jwk\" });\n\n if (\n rawJwk.x === undefined ||\n rawJwk.y === undefined ||\n typeof rawJwk.x !== \"string\" ||\n typeof rawJwk.y !== \"string\"\n ) {\n return \"\";\n }\n\n const xBytes = base64UrlToBytes(rawJwk.x, P256_SCALAR_SIZE);\n const yBytes = base64UrlToBytes(rawJwk.y, P256_SCALAR_SIZE);\n\n // Encode as TS3 canonical ASN.1: SEQUENCE { BIT STRING, INTEGER(32), INTEGER(x), INTEGER(y) }\n return encodeTsPublicKey(xBytes, yBytes);\n }\n\n toString(): string {\n const jwk = this.privateKey.export({ format: \"jwk\" }) as { d?: string };\n if (!jwk.d) {\n return `:${this.offset}`;\n }\n // Convert base64url d to fixed-size standard base64\n const dBytes = base64UrlToBytes(jwk.d, P256_SCALAR_SIZE);\n return `${Buffer.from(dBytes).toString(\"base64\")}:${this.offset}`;\n }\n\n securityLevel(): number {\n const h = createHash(\"sha1\");\n h.update(this.publicKeyBase64());\n h.update(this.offset.toString(10));\n return countLeadingZeros(h.digest());\n }\n\n async upgradeToLevel(targetLevel: number, signal?: AbortSignal): Promise<void> {\n const prefix = this.publicKeyBase64();\n while (true) {\n if (signal?.aborted) throw signal.reason as Error;\n const h = createHash(\"sha1\");\n h.update(prefix);\n h.update(this.offset.toString(10));\n if (countLeadingZeros(h.digest()) >= targetLevel) return;\n this.offset++;\n // Yield to event loop periodically to avoid blocking\n if (this.offset % 10000n === 0n) {\n await new Promise<void>((resolve) => setImmediate(resolve));\n }\n }\n }\n}\n\nexport function identityFromString(s: string): Identity {\n const colonIdx = s.lastIndexOf(\":\");\n if (colonIdx < 0) throw new InvalidIdentityError();\n\n const dBase64 = s.slice(0, colonIdx);\n const offsetStr = s.slice(colonIdx + 1);\n\n const dBytes = Buffer.from(dBase64, \"base64\");\n const offset = BigInt(offsetStr);\n\n if (dBytes.length > P256_SCALAR_SIZE) {\n throw new InvalidIdentityError(\"private key scalar too large\");\n }\n\n // Pad to P256_SCALAR_SIZE\n const padded = Buffer.alloc(P256_SCALAR_SIZE);\n dBytes.copy(padded, P256_SCALAR_SIZE - dBytes.length);\n\n // node:crypto JWK import requires x and y to be present.\n // Derive the public key from the private scalar via ECDH.\n const ecdh = createECDH(\"prime256v1\");\n ecdh.setPrivateKey(padded);\n const pub = ecdh.getPublicKey(null, \"uncompressed\"); // 65 bytes: 0x04 || x(32) || y(32)\n\n const x = Buffer.from(pub.slice(1, 33)).toString(\"base64url\");\n const y = Buffer.from(pub.slice(33, 65)).toString(\"base64url\");\n const d = padded.toString(\"base64url\");\n\n const jwk = { kty: \"EC\", crv: \"P-256\", d, x, y };\n const privateKey = createPrivateKey({ key: jwk as unknown as string, format: \"jwk\" });\n return new Identity(privateKey, offset);\n}\n\nexport function generateIdentity(targetLevel: number): Identity {\n const { privateKey } = generateKeyPairSync(\"ec\", {\n namedCurve: \"prime256v1\",\n });\n const id = new Identity(privateKey, 0n);\n\n const prefix = id.publicKeyBase64();\n while (true) {\n const h = createHash(\"sha1\");\n h.update(prefix);\n h.update(id.offset.toString(10));\n if (countLeadingZeros(h.digest()) >= targetLevel) return id;\n id.offset++;\n }\n}\n\nexport function getUidFromPublicKey(publicKey: string): string {\n const sum = createHash(\"sha1\").update(publicKey).digest();\n return Buffer.from(sum).toString(\"base64\");\n}\n\nexport function hash512(data: Uint8Array): Uint8Array {\n return createHash(\"sha512\").update(data).digest();\n}\n\n// ---- Internal ASN.1 DER helpers for TS3 canonical P-256 public key ----------\n\n/**\n * Encode a P-256 public key as the TS3 canonical ASN.1 SEQUENCE and return\n * its base64 representation.\n *\n * TS3 canonical format (v3+):\n * SEQUENCE {\n * BIT STRING { unused=7, value=0x00 } — DER: 03 02 07 00\n * INTEGER 32\n * INTEGER x\n * INTEGER y\n * }\n */\nfunction encodeTsPublicKey(x: Uint8Array, y: Uint8Array): string {\n // BIT STRING with 7 unused bits + value byte 0x00 — matches C# DerBitString(0x00, 7)\n const bitStringBody = Buffer.from([0x07, 0x00]);\n const bitStringDer = encodeDerTlv(0x03, bitStringBody);\n\n const integerSize = encodeDerTlv(0x02, encodePositiveInt(32));\n const integerX = encodeDerTlv(0x02, encodePositiveInt(x));\n const integerY = encodeDerTlv(0x02, encodePositiveInt(y));\n\n const seqBody = Buffer.concat([bitStringDer, integerSize, integerX, integerY]);\n const seqDer = encodeDerTlv(0x30, seqBody);\n\n return seqDer.toString(\"base64\");\n}\n\n/** Import a TS3 public key (canonical or legacy ASN.1 DER) and return the\n * uncompressed 65-byte point [0x04 || x || y]. */\nexport function importPublicKey(data: Uint8Array): KeyObject {\n const point = parseTsPublicKeyDer(data);\n const jwk = {\n kty: \"EC\",\n crv: \"P-256\",\n x: Buffer.from(point.slice(1, 33)).toString(\"base64url\"),\n y: Buffer.from(point.slice(33, 65)).toString(\"base64url\"),\n };\n return createPublicKey({ key: jwk, format: \"jwk\" });\n}\n\n/**\n * Parse both TS3 canonical and legacy ASN.1 formats and return the\n * uncompressed 65-byte point [0x04 || x || y].\n */\nfunction parseTsPublicKeyDer(data: Uint8Array): Uint8Array {\n // Try canonical: SEQUENCE { BIT_STRING, INTEGER(32), INTEGER(x), INTEGER(y) }\n try {\n return parseTsCanonicalPublicKey(data);\n } catch {\n // fall through to legacy\n }\n // Try legacy: SEQUENCE { INTEGER(x), INTEGER(y), BIT_STRING, INTEGER }\n return parseTsLegacyPublicKey(data);\n}\n\nfunction parseTsCanonicalPublicKey(data: Uint8Array): Uint8Array {\n const seqTlv = parseDerTlv(data, 0x30);\n const seq = seqTlv.value;\n let offset = 0;\n // BIT_STRING\n const bs = parseDerTlv(seq, 0x03, offset);\n offset += bs.consumed;\n // INTEGER (32)\n const sizeInt = parseDerTlv(seq, 0x02, offset);\n offset += sizeInt.consumed;\n // INTEGER x\n const xInt = parseDerTlv(seq, 0x02, offset);\n offset += xInt.consumed;\n // INTEGER y\n const yInt = parseDerTlv(seq, 0x02, offset);\n\n return buildUncompressedPoint(\n positiveIntToBytes(xInt.value, P256_SCALAR_SIZE),\n positiveIntToBytes(yInt.value, P256_SCALAR_SIZE),\n );\n}\n\nfunction parseTsLegacyPublicKey(data: Uint8Array): Uint8Array {\n const seqTlv = parseDerTlv(data, 0x30);\n const seq = seqTlv.value;\n let offset = 0;\n const xInt = parseDerTlv(seq, 0x02, offset);\n offset += xInt.consumed;\n const yInt = parseDerTlv(seq, 0x02, offset);\n\n return buildUncompressedPoint(\n positiveIntToBytes(xInt.value, P256_SCALAR_SIZE),\n positiveIntToBytes(yInt.value, P256_SCALAR_SIZE),\n );\n}\n\nfunction buildUncompressedPoint(x: Uint8Array, y: Uint8Array): Uint8Array {\n if (x.length > P256_SCALAR_SIZE || y.length > P256_SCALAR_SIZE) {\n throw new Error(\"invalid public key point encoding\");\n }\n const point = new Uint8Array(P256_UNCOMPRESSED_KEY_SIZE);\n point[0] = P256_POINT_PREFIX;\n point.set(x, 1 + P256_SCALAR_SIZE - x.length);\n point.set(y, 1 + 2 * P256_SCALAR_SIZE - y.length);\n return point;\n}\n\n// ---- DER encoding helpers ---------------------------------------------------\n\nfunction encodeDerTlv(tag: number, value: Uint8Array): Buffer {\n const lenBytes = encodeDerLength(value.length);\n return Buffer.concat([Buffer.from([tag]), lenBytes, value]);\n}\n\nfunction encodeDerLength(len: number): Buffer {\n if (len < 128) return Buffer.from([len]);\n if (len < 256) return Buffer.from([0x81, len]);\n return Buffer.from([0x82, (len >> 8) & 0xff, len & 0xff]);\n}\n\n/** Encode a non-negative value as a DER INTEGER (with 0x00 prefix if high bit set). */\nfunction encodePositiveInt(v: number | Uint8Array): Buffer {\n if (typeof v === \"number\") {\n const bytes: number[] = [];\n let n = v;\n do {\n bytes.unshift(n & 0xff);\n n >>= 8;\n } while (n > 0);\n if ((bytes[0]! & 0x80) !== 0) bytes.unshift(0x00);\n return Buffer.from(bytes);\n }\n // Uint8Array — strip leading zeros, add 0x00 if high bit set\n let start = 0;\n while (start < v.length - 1 && v[start] === 0) start++;\n const trimmed = v.slice(start);\n if ((trimmed[0]! & 0x80) !== 0) {\n return Buffer.concat([Buffer.from([0x00]), trimmed]);\n }\n return Buffer.from(trimmed);\n}\n\ninterface ParsedTlv {\n value: Uint8Array;\n consumed: number; // bytes consumed including tag+length\n}\n\nfunction parseDerTlv(data: Uint8Array, expectedTag: number, offset = 0): ParsedTlv {\n if (data[offset] !== expectedTag) {\n throw new Error(\n `expected DER tag 0x${expectedTag.toString(16)}, got 0x${(data[offset] ?? 0).toString(16)}`,\n );\n }\n let pos = offset + 1;\n let len: number;\n const firstLenByte = data[pos++]!;\n if (firstLenByte < 0x80) {\n len = firstLenByte;\n } else if (firstLenByte === 0x81) {\n len = data[pos++]!;\n } else if (firstLenByte === 0x82) {\n len = ((data[pos]! << 8) | data[pos + 1]!) >>> 0;\n pos += 2;\n } else {\n throw new Error(\"unsupported DER length encoding\");\n }\n const value = data.slice(pos, pos + len);\n return { value, consumed: pos - offset + len };\n}\n\n/** Convert a DER INTEGER value (may have leading 0x00) to fixed-length bytes. */\nfunction positiveIntToBytes(int: Uint8Array, size: number): Uint8Array {\n // Strip leading 0x00 sign byte\n let start = 0;\n while (start < int.length - 1 && int[start] === 0x00) start++;\n const stripped = int.slice(start);\n if (stripped.length > size) throw new Error(\"integer too large\");\n if (stripped.length === size) return stripped;\n const padded = new Uint8Array(size);\n padded.set(stripped, size - stripped.length);\n return padded;\n}\n\n// ---- Misc helpers -----------------------------------------------------------\n\nfunction base64UrlToBytes(b64url: string, size: number): Uint8Array {\n const buf = Buffer.from(b64url, \"base64url\");\n if (buf.length === size) return buf;\n const padded = Buffer.alloc(size);\n buf.copy(padded, size - buf.length);\n return padded;\n}\n\nfunction countLeadingZeros(data: Buffer): number {\n let zeros = 0;\n for (const b of data) {\n if (b === 0) {\n zeros += 8;\n } else {\n for (let i = 0; i < 8; i++) {\n if ((b & (1 << i)) === 0) zeros++;\n else return zeros;\n }\n }\n }\n return zeros;\n}\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\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/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n/**\n * 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 const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n }\n return value;\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('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1)\n throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1)\n throw new Error('\"blockLen\" must be >= 1');\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 if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been 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, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n/**\n * 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// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\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));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * 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 * @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 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 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 * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, 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 §10.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n/**\n * 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//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { abytes, aexists, aoutput, clean, 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 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 continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\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 _cloneInto(to) {\n to ||= new this.constructor();\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen)\n to.buffer.set(buffer);\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 §6.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV = /* @__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 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","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// 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// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\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, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\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 §5.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */\nclass SHA2_32B extends HashMD {\n constructor(outputLen) {\n super(64, outputLen, 8, false);\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 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 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n A = SHA224_IV[0] | 0;\n B = SHA224_IV[1] | 0;\n C = SHA224_IV[2] | 0;\n D = SHA224_IV[3] | 0;\n E = SHA224_IV[4] | 0;\n F = SHA224_IV[5] | 0;\n G = SHA224_IV[6] | 0;\n H = SHA224_IV[7] | 0;\n constructor() {\n super(28);\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 §5.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */\nclass SHA2_64B extends HashMD {\n constructor(outputLen) {\n super(128, outputLen, 16, false);\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 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 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n Ah = SHA512_IV[0] | 0;\n Al = SHA512_IV[1] | 0;\n Bh = SHA512_IV[2] | 0;\n Bl = SHA512_IV[3] | 0;\n Ch = SHA512_IV[4] | 0;\n Cl = SHA512_IV[5] | 0;\n Dh = SHA512_IV[6] | 0;\n Dl = SHA512_IV[7] | 0;\n Eh = SHA512_IV[8] | 0;\n El = SHA512_IV[9] | 0;\n Fh = SHA512_IV[10] | 0;\n Fl = SHA512_IV[11] | 0;\n Gh = SHA512_IV[12] | 0;\n Gl = SHA512_IV[13] | 0;\n Hh = SHA512_IV[14] | 0;\n Hl = SHA512_IV[15] | 0;\n constructor() {\n super(64);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n Ah = SHA384_IV[0] | 0;\n Al = SHA384_IV[1] | 0;\n Bh = SHA384_IV[2] | 0;\n Bl = SHA384_IV[3] | 0;\n Ch = SHA384_IV[4] | 0;\n Cl = SHA384_IV[5] | 0;\n Dh = SHA384_IV[6] | 0;\n Dl = SHA384_IV[7] | 0;\n Eh = SHA384_IV[8] | 0;\n El = SHA384_IV[9] | 0;\n Fh = SHA384_IV[10] | 0;\n Fl = SHA384_IV[11] | 0;\n Gh = SHA384_IV[12] | 0;\n Gl = SHA384_IV[13] | 0;\n Hh = SHA384_IV[14] | 0;\n Hl = SHA384_IV[15] | 0;\n constructor() {\n super(48);\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 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n Ah = T224_IV[0] | 0;\n Al = T224_IV[1] | 0;\n Bh = T224_IV[2] | 0;\n Bl = T224_IV[3] | 0;\n Ch = T224_IV[4] | 0;\n Cl = T224_IV[5] | 0;\n Dh = T224_IV[6] | 0;\n Dl = T224_IV[7] | 0;\n Eh = T224_IV[8] | 0;\n El = T224_IV[9] | 0;\n Fh = T224_IV[10] | 0;\n Fl = T224_IV[11] | 0;\n Gh = T224_IV[12] | 0;\n Gl = T224_IV[13] | 0;\n Hh = T224_IV[14] | 0;\n Hl = T224_IV[15] | 0;\n constructor() {\n super(28);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n Ah = T256_IV[0] | 0;\n Al = T256_IV[1] | 0;\n Bh = T256_IV[2] | 0;\n Bl = T256_IV[3] | 0;\n Ch = T256_IV[4] | 0;\n Cl = T256_IV[5] | 0;\n Dh = T256_IV[6] | 0;\n Dl = T256_IV[7] | 0;\n Eh = T256_IV[8] | 0;\n El = T256_IV[9] | 0;\n Fh = T256_IV[10] | 0;\n Fl = T256_IV[11] | 0;\n Gh = T256_IV[12] | 0;\n Gl = T256_IV[13] | 0;\n Hh = T256_IV[14] | 0;\n Hl = T256_IV[15] | 0;\n constructor() {\n super(32);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__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 * @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 * @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 * @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 * @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 * @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//# sourceMappingURL=sha2.js.map","/**\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 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 * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = 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/**\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 const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\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 * @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 RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2)\n throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '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 * @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// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= 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 let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\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 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 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) => (_1n << BigInt(n)) - _1n;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(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 * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}) {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n function checkField(fieldName, expectedType, isOpt) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`param \"${fieldName}\" 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//# sourceMappingURL=utils.js.map","/**\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 { abool, abytes, anumber, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } 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 _16n = /* @__PURE__ */ BigInt(16);\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 return FpPow(Field(modulo), num, power);\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 (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 - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n if (modulo <= _0n)\n throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\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// 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 // 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 if (F.is0(t))\n return F.ZERO; // if t=0 return R=0\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M)\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 ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. P ≡ 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P) {\n // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n if (P % _4n === _3n)\n return sqrt3mod4;\n // P ≡ 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 ≡ 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 const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\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 const F = Fp;\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 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/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\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 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 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) ≡ 1 if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0 if a ≡ 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n const F = Fp;\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 bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// 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 FpPow(this, num, power);\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 return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, 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// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n/**\n * 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 return new _Field(ORDER, opts);\n}\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n/**\n * @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 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 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 // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\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 must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject({\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n }, {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n });\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt(condition, item) {\n const neg = item.negate();\n return condition ? neg : item;\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 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) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n if (!Array.isArray(points))\n throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars, field) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s))\n throw new Error('invalid scalar at index ' + i);\n });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\nfunction assert0(n) {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n)\n throw new Error('invalid wNAF');\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF {\n BASE;\n ZERO;\n Fn;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, bits) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n // non-const time multiplication ladder\n _unsafeLadder(elm, n, p = this.ZERO) {\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(point, W) {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points = [];\n let p = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n))\n throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n }\n else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n)\n break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n }\n else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n getPrecomputes(W, point, transform) {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W);\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function')\n comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n cached(point, scalar, transform) {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n unsafe(point, scalar, transform, prev) {\n const W = getW(point);\n if (W === 1)\n return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P, W) {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n hasCache(elm) {\n return getW(elm) !== 1;\n }\n}\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe(Point, point, k1, k2) {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n p1 = p1.add(acc);\n if (k2 & _1n)\n p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\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 * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe(c, points, windowSize) {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar × 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 × 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 × 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero)\n for (let j = 0; j < windowSize; j++)\n res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr)\n continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\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:\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 (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = 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//# sourceMappingURL=curve.js.map","/**\n * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².\n * For design rationale of types / exports, see weierstrass module documentation.\n * Untwisted Edwards curves exist, but they aren't used in real-world protocols.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from \"../utils.js\";\nimport { createCurveFields, createKeygen, normalizeZ, wNAF, } from \"./curve.js\";\nimport {} from \"./modular.js\";\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);\n// Affine Edwards-equation check only; this does not prove subgroup membership, canonical\n// encoding, prime-order base-point requirements, or identity exclusion.\nfunction isEdValidXY(Fp, CURVE, x, y) {\n const x2 = Fp.sqr(x);\n const y2 = Fp.sqr(y);\n const left = Fp.add(Fp.mul(CURVE.a, x2), y2);\n const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));\n return Fp.eql(left, right);\n}\n/**\n * @param params - Curve parameters. See {@link EdwardsOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.\n * @returns Edwards point constructor. Generator validation here only checks\n * that `(Gx, Gy)` satisfies the affine Edwards equation.\n * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`\n * are left to the caller's chosen parameters, since eager subgroup\n * validation here adds about 10-15ms to heavyweight imports like ed448.\n * The returned constructor also eagerly marks `Point.BASE` for W=8\n * precompute caching. Some code paths still assume\n * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.\n * @throws If the curve parameters or Edwards overrides are invalid. {@link Error}\n * @example\n * ```ts\n * import { edwards } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * // Build a point constructor from explicit curve parameters, then use its base point.\n * const Point = edwards(jubjub.Point.CURVE());\n * Point.BASE.toHex();\n * ```\n */\nexport function edwards(params, extraOpts = {}) {\n const opts = extraOpts;\n const validated = createCurveFields('edwards', params, opts, opts.FpFnLE);\n const { Fp, Fn } = validated;\n let CURVE = validated.CURVE;\n const { h: cofactor } = CURVE;\n validateObject(opts, {}, { uvRatio: 'function' });\n // Important:\n // There are some places where Fp.BYTES is used instead of nByteLength.\n // So far, everything has been tested with curves of Fp.BYTES == nByteLength.\n // TODO: test and find curves which behave otherwise.\n const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);\n const modP = (n) => Fp.create(n); // Function overrides\n // sqrt(u/v)\n const uvRatio = opts.uvRatio === undefined\n ? (u, v) => {\n try {\n return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };\n }\n catch (e) {\n return { isValid: false, value: _0n };\n }\n }\n : opts.uvRatio;\n // Validate whether the passed curve params are valid.\n // equation ax² + y² = 1 + dx²y² should work for generator point.\n if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))\n throw new Error('bad curve params: generator point');\n /**\n * Asserts coordinate is valid: 0 <= n < MASK.\n * Coordinates >= Fp.ORDER are allowed for zip215.\n */\n function acoord(title, n, banZero = false) {\n const min = banZero ? _1n : _0n;\n aInRange('coordinate ' + title, n, min, MASK);\n return n;\n }\n function aedpoint(other) {\n if (!(other instanceof Point))\n throw new Error('EdwardsPoint expected');\n }\n // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point {\n // base / generator point\n static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n // zero / infinity / identity point\n static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n // math field\n static Fp = Fp;\n // scalar field\n static Fn = Fn;\n X;\n Y;\n Z;\n T;\n constructor(X, Y, Z, T) {\n this.X = acoord('x', X);\n this.Y = acoord('y', Y);\n this.Z = acoord('z', Z, true);\n this.T = acoord('t', T);\n Object.freeze(this);\n }\n static CURVE() {\n return CURVE;\n }\n /**\n * Create one extended Edwards point from affine coordinates.\n * Does NOT validate that the point is on-curve or torsion-free.\n * Use `.assertValidity()` on adversarial inputs.\n */\n static fromAffine(p) {\n if (p instanceof Point)\n throw new Error('extended point not allowed');\n const { x, y } = p || {};\n acoord('x', x);\n acoord('y', y);\n return new Point(x, y, _1n, modP(x * y));\n }\n // Uses algo from RFC8032 5.1.3.\n static fromBytes(bytes, zip215 = false) {\n const len = Fp.BYTES;\n const { a, d } = CURVE;\n bytes = copyBytes(abytes(bytes, len, 'point'));\n abool(zip215, 'zip215');\n const normed = copyBytes(bytes); // copy again, we'll manipulate it\n const lastByte = bytes[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = bytesToNumberLE(normed);\n // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n const max = zip215 ? MASK : Fp.ORDER;\n aInRange('point.y', y, _0n, max);\n // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:\n // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y² - 1\n const v = modP(d * y2 - a); // v = d y² + 1.\n let { isValid, value: x } = uvRatio(u, v); // √(u/v)\n if (!isValid)\n throw new Error('bad point: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('bad point: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd)\n x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromHex(hex, zip215 = false) {\n return Point.fromBytes(hexToBytes(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n precompute(windowSize = 8, isLazy = true) {\n wnaf.createCache(this, windowSize);\n if (!isLazy)\n this.multiply(_2n); // random number\n return this;\n }\n // Useful in fromAffine() - not for fromBytes(), which always created valid points.\n assertValidity() {\n const p = this;\n const { a, d } = CURVE;\n // Keep generic Edwards validation fail-closed on the neutral point.\n // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level\n // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids\n // silently treating that degenerate state as an ordinary public point.\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { X, Y, Z, T } = p;\n const X2 = modP(X * X); // X²\n const Y2 = modP(Y * Y); // Y²\n const Z2 = modP(Z * Z); // Z²\n const Z4 = modP(Z2 * Z2); // Z⁴\n const aX2 = modP(X2 * a); // aX²\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n }\n // Compare one point to another.\n equals(other) {\n aedpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n negate() {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));\n }\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double() {\n const { a } = CURVE;\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other) {\n aedpoint(other);\n const { a, d } = CURVE;\n const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;\n const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n subtract(other) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aedpoint(other);\n return this.add(other.negate());\n }\n // Constant-time multiplication.\n multiply(scalar) {\n // 1 <= scalar < L\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar))\n throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');\n const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p));\n return normalizeZ(Point, [p, f])[0];\n }\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but\n // n and larger values are rejected instead of being reduced mod n to the identity point.\n multiplyUnsafe(scalar) {\n // 0 <= scalar < L\n if (!Fn.isValid(scalar))\n throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');\n if (scalar === _0n)\n return Point.ZERO;\n if (this.is0() || scalar === _1n)\n return this;\n return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p));\n }\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Clears cofactor and checks if the result is 0.\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree() {\n return wnaf.unsafe(this, CURVE.n).is0();\n }\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(invertedZ) {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily\n const x = modP(X * iz);\n const y = modP(Y * iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: _0n, y: _1n };\n if (zz !== _1n)\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n return this.multiplyUnsafe(cofactor);\n }\n toBytes() {\n const { x, y } = this.toAffine();\n // Fp.toBytes() allows non-canonical encoding of y (>= p).\n const bytes = Fp.toBytes(y);\n // Each y has 2 valid points: (x, y), (x,-y).\n // When compressing, it's enough to store y and use the last byte to encode sign of x\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;\n return bytes;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;\n }\n }\n const wnaf = new wNAF(Point, Fn.BITS);\n // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve\n // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.\n // Callers that construct custom curves are responsible for supplying the correct base point.\n // try {\n // Point.BASE.assertValidity();\n // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n // } catch {\n // throw new Error('bad curve params: generator point');\n // }\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (Fn.BITS >= 8)\n Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\n * Base class for prime-order points like Ristretto255 and Decaf448.\n * These points eliminate cofactor issues by representing equivalence classes\n * of Edwards curve points. Multiple Edwards representatives can describe the\n * same abstract wrapper element, so wrapper validity is not the same thing as\n * the hidden representative being torsion-free.\n * @param ep - Backing Edwards point.\n * @example\n * Base class for prime-order points like Ristretto255 and Decaf448.\n *\n * ```ts\n * import { ristretto255 } from '@noble/curves/ed25519.js';\n * const point = ristretto255.Point.BASE.multiply(2n);\n * ```\n */\nexport class PrimeEdwardsPoint {\n static BASE;\n static ZERO;\n static Fp;\n static Fn;\n ep;\n /**\n * Wrap one internal Edwards representative directly.\n * This is not a canonical encoding boundary: alternate Edwards\n * representatives may still describe the same abstract wrapper element.\n */\n constructor(ep) {\n this.ep = ep;\n }\n // Static methods that must be implemented by subclasses\n static fromBytes(_bytes) {\n notImplemented();\n }\n static fromHex(_hex) {\n notImplemented();\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n // Common implementations\n clearCofactor() {\n // no-op for the abstract prime-order wrapper group; this is about the\n // wrapper element, not the hidden Edwards representative.\n return this;\n }\n assertValidity() {\n // Keep wrapper validity at the abstract-group boundary. Canonical decode\n // may choose Edwards representatives that differ by small torsion, so\n // checking `this.ep.isTorsionFree()` here would reject valid wrapper points.\n this.ep.assertValidity();\n }\n /**\n * Return affine coordinates of the current internal Edwards representative.\n * This is a convenience helper, not a canonical Ristretto/Decaf encoding.\n * Equal abstract elements may expose different `x` / `y`; use\n * `toBytes()` / `fromBytes()` for canonical roundtrips.\n */\n toAffine(invertedZ) {\n return this.ep.toAffine(invertedZ);\n }\n toHex() {\n return bytesToHex(this.toBytes());\n }\n toString() {\n return this.toHex();\n }\n isTorsionFree() {\n // Abstract Ristretto/Decaf elements are already prime-order even when the\n // hidden Edwards representative is not torsion-free.\n return true;\n }\n isSmallOrder() {\n return false;\n }\n add(other) {\n this.assertSame(other);\n return this.init(this.ep.add(other.ep));\n }\n subtract(other) {\n this.assertSame(other);\n return this.init(this.ep.subtract(other.ep));\n }\n multiply(scalar) {\n return this.init(this.ep.multiply(scalar));\n }\n multiplyUnsafe(scalar) {\n return this.init(this.ep.multiplyUnsafe(scalar));\n }\n double() {\n return this.init(this.ep.double());\n }\n negate() {\n return this.init(this.ep.negate());\n }\n precompute(windowSize, isLazy) {\n this.ep.precompute(windowSize, isLazy);\n // Keep the wrapper identity stable like the backing Edwards API instead of\n // allocating a fresh wrapper around the same cached point.\n return this;\n }\n}\n/**\n * Initializes EdDSA signatures over given Edwards curve.\n * @param Point - Edwards point constructor.\n * @param cHash - Hash function.\n * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.\n * @returns EdDSA helper namespace.\n * @throws If the hash function, options, or derived point operations are invalid. {@link Error}\n * @example\n * Initializes EdDSA signatures over given Edwards curve.\n *\n * ```ts\n * import { eddsa } from '@noble/curves/abstract/edwards.js';\n * import { jubjub } from '@noble/curves/misc.js';\n * import { sha512 } from '@noble/hashes/sha2.js';\n * const sigs = eddsa(jubjub.Point, sha512);\n * const { secretKey, publicKey } = sigs.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = sigs.sign(msg, secretKey);\n * const isValid = sigs.verify(sig, msg, publicKey);\n * ```\n */\nexport function eddsa(Point, cHash, eddsaOpts = {}) {\n if (typeof cHash !== 'function')\n throw new Error('\"hash\" function param is required');\n const hash = cHash;\n const opts = eddsaOpts;\n validateObject(opts, {}, {\n adjustScalarBytes: 'function',\n randomBytes: 'function',\n domain: 'function',\n prehash: 'function',\n zip215: 'boolean',\n mapToCurve: 'function',\n });\n const { prehash } = opts;\n const { BASE, Fp, Fn } = Point;\n const outputLen = hash.outputLen;\n const expectedLen = 2 * Fp.BYTES;\n // When hash metadata is available, reject incompatible EdDSA wrappers at construction time\n // instead of deferring the mismatch until the first keygen/sign call.\n if (outputLen !== undefined) {\n asafenumber(outputLen, 'hash.outputLen');\n if (outputLen !== expectedLen)\n throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);\n }\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n const adjustScalarBytes = opts.adjustScalarBytes === undefined\n ? (bytes) => bytes\n : opts.adjustScalarBytes;\n const domain = opts.domain === undefined\n ? (data, ctx, phflag) => {\n abool(phflag, 'phflag');\n if (ctx.length || phflag)\n throw new Error('Contexts/pre-hash are not supported');\n return data;\n }\n : opts.domain; // NOOP\n // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.\n function modN_LE(hash) {\n return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit\n }\n // Get the hashed private scalar per RFC8032 5.1.5\n function getPrivateScalar(key) {\n const len = lengths.secretKey;\n abytes(key, lengths.secretKey, 'secretKey');\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey');\n // Slice before clamping so in-place adjustors don't corrupt the prefix half.\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n return { head, prefix, scalar };\n }\n /** Convenience method that creates public key from scalar. RFC8032 5.1.5\n * Also exposes the derived scalar/prefix tuple and point form reused by sign().\n */\n function getExtendedPublicKey(secretKey) {\n const { head, prefix, scalar } = getPrivateScalar(secretKey);\n const point = BASE.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toBytes();\n return { head, prefix, scalar, point, pointBytes };\n }\n /** Calculates EdDSA pub key. RFC8032 5.1.5. */\n function getPublicKey(secretKey) {\n return getExtendedPublicKey(secretKey).pointBytes;\n }\n // Hash domain-separated chunks into a little-endian scalar modulo the group order.\n function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {\n const msg = concatBytes(...msgs);\n return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash)));\n }\n /** Signs message with secret key. RFC8032 5.1.6 */\n function sign(msg, secretKey, options = {}) {\n msg = abytes(msg, undefined, 'message');\n if (prehash)\n msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point\n // signature.\n // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider\n // fails loudly instead of silently producing a degenerate signature.\n const R = BASE.multiply(r).toBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L\n if (!Fn.isValid(s))\n throw new Error('sign failed: invalid s'); // 0 <= s < L\n const rs = concatBytes(R, Fn.toBytes(s));\n return abytes(rs, lengths.signature, 'result');\n }\n // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject\n // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.\n const verifyOpts = {\n zip215: opts.zip215,\n };\n /**\n * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.\n * A cofactored verification equation is checked.\n */\n function verify(sig, msg, publicKey, options = verifyOpts) {\n // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.\n const { context } = options;\n const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;\n const len = lengths.signature;\n sig = abytes(sig, len, 'signature');\n msg = abytes(msg, undefined, 'message');\n publicKey = abytes(publicKey, lengths.publicKey, 'publicKey');\n if (zip215 !== undefined)\n abool(zip215, 'zip215');\n if (prehash)\n msg = prehash(msg); // for ed25519ph, etc\n const mid = len / 2;\n const r = sig.subarray(0, mid);\n const s = bytesToNumberLE(sig.subarray(mid, len));\n let A, R, SB;\n try {\n // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that\n // explicitly want consensus-style unreduced encoding acceptance.\n // zip215=true: 0 <= y < MASK (2^256 for ed25519)\n // zip215=false: 0 <= y < P (2^255-19 for ed25519)\n A = Point.fromBytes(publicKey, zip215);\n R = Point.fromBytes(r, zip215);\n SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside\n }\n catch (error) {\n return false;\n }\n // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored\n // verification equation; they do not add a separate low-order-public-key rejection here.\n // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to\n // avoid ambiguous verification outcomes where unusual low-order keys can make distinct\n // key/signature/message combinations verify.\n if (!zip215 && A.isSmallOrder())\n return false;\n // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the\n // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.\n const k = hashDomainToScalar(context, r, publicKey, msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // Check the cofactored verification equation via the curve cofactor h.\n // [h][S]B = [h]R + [h][k]A'\n return RkA.subtract(SB).clearCofactor().is0();\n }\n const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448\n const lengths = {\n secretKey: _size,\n publicKey: _size,\n signature: 2 * _size,\n seed: _size,\n };\n function randomSecretKey(seed) {\n seed = seed === undefined ? randomBytes(lengths.seed) : seed;\n return abytes(seed, lengths.seed, 'seed');\n }\n function isValidSecretKey(key) {\n return isBytes(key) && key.length === lengths.secretKey;\n }\n function isValidPublicKey(key, zip215) {\n try {\n // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.\n return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);\n }\n catch (error) {\n return false;\n }\n }\n const utils = {\n getExtendedPublicKey,\n randomSecretKey,\n isValidSecretKey,\n isValidPublicKey,\n /**\n * Converts ed public key to x public key. Uses formula:\n * - ed25519:\n * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * - ed448:\n * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`\n * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`\n */\n toMontgomery(publicKey) {\n const { y } = Point.fromBytes(publicKey);\n const size = lengths.publicKey;\n const is25519 = size === 32;\n if (!is25519 && size !== 57)\n throw new Error('only defined for 25519 and 448');\n const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);\n return Fp.toBytes(u);\n },\n toMontgomerySecret(secretKey) {\n const size = lengths.secretKey;\n abytes(secretKey, size);\n const hashed = hash(secretKey.subarray(0, size));\n return adjustScalarBytes(hashed).subarray(0, size);\n },\n };\n Object.freeze(lengths);\n Object.freeze(utils);\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, getPublicKey),\n getPublicKey,\n sign,\n verify,\n utils,\n Point,\n lengths,\n });\n}\n//# sourceMappingURL=edwards.js.map","import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, copyBytes, concatBytes, isBytes, validateObject, } from \"../utils.js\";\nimport { FpInvertBatch, mod } from \"./modular.js\";\n// Octet Stream to Integer. \"spec\" implementation of os2ip is 2.5x slower vs bytesToNumberBE.\nconst os2ip = bytesToNumberBE;\n// Integer to Octet Stream (numberToBytesBE).\nfunction i2osp(value, length) {\n asafenumber(value);\n asafenumber(length);\n // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should\n // use bigint + numberToBytesBE instead of routing large widths through this small helper.\n if (length < 0 || length > 4)\n throw new Error('invalid I2OSP length: ' + length);\n if (value < 0 || value > 2 ** (8 * length) - 1)\n throw new Error('invalid I2OSP input: ' + value);\n const res = Array.from({ length }).fill(0);\n for (let i = length - 1; i >= 0; i--) {\n res[i] = value & 0xff;\n value >>>= 8;\n }\n return new Uint8Array(res);\n}\n// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.\nfunction strxor(a, b) {\n const arr = new Uint8Array(a.length);\n for (let i = 0; i < a.length; i++) {\n arr[i] = a[i] ^ b[i];\n }\n return arr;\n}\n// User can always use utf8 if they want, by passing Uint8Array.\n// If string is passed, we treat it as ASCII: other formats are likely a mistake.\nfunction normDST(DST) {\n if (!isBytes(DST) && typeof DST !== 'string')\n throw new Error('DST must be Uint8Array or ascii string');\n const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;\n // RFC 9380 §3.1 requirement 2: tags \"MUST have nonzero length\".\n if (dst.length === 0)\n throw new Error('DST must be non-empty');\n return dst;\n}\n/**\n * Produces a uniformly random byte string using a cryptographic hash\n * function H that outputs b bits.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param H - Hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, hash, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XMD construction.\n *\n * ```ts\n * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);\n * ```\n */\nexport function expand_message_xmd(msg, DST, lenInBytes, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n if (DST.length > 255)\n DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));\n const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;\n const ell = Math.ceil(lenInBytes / b_in_bytes);\n if (lenInBytes > 65535 || ell > 255)\n throw new Error('expand_message_xmd: invalid lenInBytes');\n const DST_prime = concatBytes(DST, i2osp(DST.length, 1));\n const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)\n const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str\n const b = new Array(ell);\n const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));\n b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));\n // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`\n // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`\n // by reaching `I2OSP(256, 1)`.\n for (let i = 1; i < ell; i++) {\n const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];\n b[i] = H(concatBytes(...args));\n }\n const pseudo_random_bytes = concatBytes(...b);\n return pseudo_random_bytes.slice(0, lenInBytes);\n}\n/**\n * Produces a uniformly random byte string using an extendable-output function (XOF) H.\n * 1. The collision resistance of H MUST be at least k bits.\n * 2. H MUST be an XOF that has been proved indifferentiable from\n * a random oracle under a reasonable cryptographic assumption.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.\n * @param msg - Input message.\n * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and\n * oversize-hashes DST when needed.\n * @param lenInBytes - Output length.\n * @param k - Target security level.\n * @param H - XOF hash function.\n * @returns Uniform byte string.\n * @throws If the message, DST, XOF, or output length is invalid. {@link Error}\n * @example\n * Expand one message into uniform bytes with the XOF construction.\n *\n * ```ts\n * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js';\n * import { shake256 } from '@noble/hashes/sha3.js';\n * const uniform = expand_message_xof(\n * new TextEncoder().encode('hello noble'),\n * 'DST',\n * 32,\n * 128,\n * shake256\n * );\n * ```\n */\nexport function expand_message_xof(msg, DST, lenInBytes, k, H) {\n abytes(msg);\n asafenumber(lenInBytes);\n DST = normDST(DST);\n // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3\n // RFC 9380 §5.3.3: DST = H(\"H2C-OVERSIZE-DST-\" || a_very_long_DST, ceil(2 * k / 8)).\n if (DST.length > 255) {\n const dkLen = Math.ceil((2 * k) / 8);\n DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();\n }\n if (lenInBytes > 65535 || DST.length > 255)\n throw new Error('expand_message_xof: invalid lenInBytes');\n return (H.create({ dkLen: lenInBytes })\n .update(msg)\n .update(i2osp(lenInBytes, 2))\n // 2. DST_prime = DST || I2OSP(len(DST), 1)\n .update(DST)\n .update(i2osp(DST.length, 1))\n .digest());\n}\n/**\n * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.\n * @param msg - Input message bytes.\n * @param count - Number of field elements to derive. Must be `>= 1`.\n * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.\n * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.\n * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}\n * @example\n * Hash one message into field elements before mapping it onto a curve.\n *\n * ```ts\n * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {\n * DST: 'DST',\n * p: 17n,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * ```\n */\nexport function hash_to_field(msg, count, options) {\n validateObject(options, {\n p: 'bigint',\n m: 'number',\n k: 'number',\n hash: 'function',\n });\n const { p, k, m, hash, expand, DST } = options;\n asafenumber(hash.outputLen, 'valid hash');\n abytes(msg);\n asafenumber(count);\n // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires\n // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.\n if (count < 1)\n throw new Error('hash_to_field: expected count >= 1');\n if (m < 1)\n throw new Error('hash_to_field: expected m >= 1');\n const log2p = p.toString(2).length;\n const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above\n const len_in_bytes = count * m * L;\n let prb; // pseudo_random_bytes\n if (expand === 'xmd') {\n prb = expand_message_xmd(msg, DST, len_in_bytes, hash);\n }\n else if (expand === 'xof') {\n prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);\n }\n else if (expand === '_internal_pass') {\n // for internal tests only\n prb = msg;\n }\n else {\n throw new Error('expand must be \"xmd\" or \"xof\"');\n }\n const u = new Array(count);\n for (let i = 0; i < count; i++) {\n const e = new Array(m);\n for (let j = 0; j < m; j++) {\n const elm_offset = L * (j + i * m);\n const tv = prb.subarray(elm_offset, elm_offset + L);\n e[j] = mod(os2ip(tv), p);\n }\n u[i] = e;\n }\n return u;\n}\n/**\n * @param field - Field implementation.\n * @param map - Isogeny coefficients.\n * @returns Isogeny mapping helper.\n * @example\n * Build one rational isogeny map, then apply it to affine x/y coordinates.\n *\n * ```ts\n * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);\n * const point = iso(3n, 5n);\n * ```\n */\nexport function isogenyMap(field, map) {\n // Make same order as in spec\n const coeff = map.map((i) => Array.from(i).reverse());\n return (x, y) => {\n const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));\n // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must\n // return the identity on E.\n // Shipped Weierstrass consumers encode that affine identity as all-zero\n // coordinates, so `passZero=true` intentionally collapses zero\n // denominators to `{ x: 0, y: 0 }`.\n const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);\n x = field.mul(xn, xd_inv); // xNum / xDen\n y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)\n return { x, y };\n };\n}\n// Keep the shared DST removable when the selected bundle never hashes to scalar.\n// Callers that need protocol-specific scalar domain separation must override this generic default.\n// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.\n// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior\n// by mutating a shared Uint8Array in place.\nexport const _DST_scalar = 'HashToScalar-';\n/**\n * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.\n * @param Point - Point constructor.\n * @param mapToCurve - Map-to-curve function.\n * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as\n * the shared defaults bundle for the returned helpers.\n * @returns Hash-to-curve helper namespace.\n * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}\n * @example\n * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.\n *\n * ```ts\n * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {\n * DST: 'P256_XMD:SHA-256_SSWU_RO_',\n * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n * p: p256.Point.Fp.ORDER,\n * m: 1,\n * k: 128,\n * expand: 'xmd',\n * hash: sha256,\n * });\n * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport function createHasher(Point, mapToCurve, defaults) {\n if (typeof mapToCurve !== 'function')\n throw new Error('mapToCurve() must be defined');\n // `Point` is intentionally not shape-validated eagerly here: point constructors vary across\n // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured\n // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().\n const snapshot = (src) => Object.freeze({\n ...src,\n DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,\n ...(src.encodeDST === undefined\n ? {}\n : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),\n });\n // Keep one private defaults snapshot for actual hashing and expose fresh\n // detached snapshots via the public getter.\n // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison\n // the singleton hasher for every other consumer in the same process.\n const safeDefaults = snapshot(defaults);\n function map(num) {\n return Point.fromAffine(mapToCurve(num));\n }\n function clear(initial) {\n const P = initial.clearCofactor();\n // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity\n // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.\n if (P.equals(Point.ZERO))\n return Point.ZERO;\n P.assertValidity();\n return P;\n }\n return Object.freeze({\n get defaults() {\n return snapshot(safeDefaults);\n },\n Point,\n hashToCurve(msg, options) {\n const opts = Object.assign({}, safeDefaults, options);\n const u = hash_to_field(msg, 2, opts);\n const u0 = map(u[0]);\n const u1 = map(u[1]);\n return clear(u0.add(u1));\n },\n encodeToCurve(msg, options) {\n const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};\n const opts = Object.assign({}, safeDefaults, optsDst, options);\n const u = hash_to_field(msg, 1, opts);\n const u0 = map(u[0]);\n return clear(u0);\n },\n /** See {@link H2CHasher} */\n mapToCurve(scalars) {\n // Curves with m=1 accept only single scalar\n if (safeDefaults.m === 1) {\n if (typeof scalars !== 'bigint')\n throw new Error('expected bigint (m=1)');\n return clear(map([scalars]));\n }\n if (!Array.isArray(scalars))\n throw new Error('expected array of bigints');\n for (const i of scalars)\n if (typeof i !== 'bigint')\n throw new Error('expected array of bigints');\n return clear(map(scalars));\n },\n // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393\n // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic\n // `HashToScalar-` prefix above unless the caller overrides it per invocation.\n hashToScalar(msg, options) {\n // @ts-ignore\n const N = Point.Fn.ORDER;\n const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);\n return hash_to_field(msg, 1, opts)[0][0];\n },\n });\n}\n//# sourceMappingURL=hash-to-curve.js.map","/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js';\nimport {} from \"./abstract/curve.js\";\nimport { eddsa, edwards, PrimeEdwardsPoint, } from \"./abstract/edwards.js\";\nimport { createFROST } from \"./abstract/frost.js\";\nimport { _DST_scalar, createHasher, expand_message_xmd, } from \"./abstract/hash-to-curve.js\";\nimport { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from \"./abstract/modular.js\";\nimport { montgomery } from \"./abstract/montgomery.js\";\nimport { createOPRF } from \"./abstract/oprf.js\";\nimport { asciiToBytes, bytesToNumberLE, equalBytes } from \"./utils.js\";\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// P = 2n**255n - 19n\nconst ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed');\n// N = 2n**252n + 27742317777372353535851937790883648493n\n// a = Fp.create(BigInt(-1))\n// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666))\nconst ed25519_CURVE = /* @__PURE__ */ (() => ({\n p: ed25519_CURVE_p,\n n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'),\n h: _8n,\n a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'),\n d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'),\n Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'),\n Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'),\n}))();\nfunction ed25519_pow_2_252_3(x) {\n // prettier-ignore\n const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n const P = ed25519_CURVE_p;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8).\n return { pow_p_5_8, b2 };\n}\n// Mutates and returns the provided 32-byte buffer in place.\nfunction adjustScalarBytes(bytes) {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n// √(-1) aka √(a) aka 2^((p-1)/4)\n// Fp.sqrt(Fp.neg(1))\nconst ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');\n// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a\n// dummy root-shaped field element so callers can stay constant-time.\nfunction uvRatio(u, v) {\n const P = ed25519_CURVE_p;\n const v3 = mod(v * v * v, P); // v³\n const v7 = mod(v3 * v3 * v, P); // v⁷\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx²\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1)\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P))\n x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\nconst ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });\n// Public field alias stays stricter than the RFC 8032 Appendix A sample code:\n// `Fp.inv(0)` throws instead of returning `0`.\nconst Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();\nconst Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)();\n// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the\n// empty-domain path in `ed()` and would be wrong if routed through this helper.\nfunction ed25519_domain(data, ctx, phflag) {\n if (ctx.length > 255)\n throw new Error('Context is too big');\n return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data);\n}\nfunction ed(opts) {\n // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility.\n return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts));\n}\n/**\n * ed25519 curve with EdDSA signatures.\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Generate one Ed25519 keypair, sign a message, and verify it.\n *\n * ```js\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * const { secretKey, publicKey } = ed25519.keygen();\n * // const publicKey = ed25519.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519.sign(msg, secretKey);\n * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215\n * // RFC8032 / FIPS 186-5\n * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false });\n * ```\n */\nexport const ed25519 = /* @__PURE__ */ ed({});\n/**\n * Context version of ed25519 (ctx for domain separation). See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Sign and verify with Ed25519ctx under one explicit context.\n *\n * ```ts\n * const context = new TextEncoder().encode('docs');\n * const { secretKey, publicKey } = ed25519ctx.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ctx.sign(msg, secretKey, { context });\n * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context });\n * ```\n */\nexport const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain });\n/**\n * Prehashed version of ed25519. See {@link ed25519}\n * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided\n * 32-byte seed buffer instead of copying it.\n * @example\n * Use the prehashed Ed25519 variant for one message.\n *\n * ```ts\n * const { secretKey, publicKey } = ed25519ph.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = ed25519ph.sign(msg, secretKey);\n * const isValid = ed25519ph.verify(sig, msg, publicKey);\n * ```\n */\nexport const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 });\n/**\n * FROST threshold signatures over ed25519. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ed25519 signing.\n *\n * ```ts\n * const alice = ed25519_FROST.Identifier.derive('alice@example.com');\n * const bob = ed25519_FROST.Identifier.derive('bob@example.com');\n * const carol = ed25519_FROST.Identifier.derive('carol@example.com');\n * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ed25519_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-ED25519-SHA512-v1',\n Point: ed25519_Point,\n validatePoint: (p) => {\n p.assertValidity();\n if (!p.isTorsionFree())\n throw new Error('bad point: not torsion-free');\n },\n hash: sha512,\n // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(),\n // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats\n // that the same as omitted DST, even though custom hooks can still observe the empty bag.\n H2: '',\n}))();\n/**\n * ECDH using curve25519 aka x25519.\n * `getSharedSecret()` rejects low-order peer inputs by default, and seeded\n * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it.\n * @example\n * Derive one shared secret between two X25519 peers.\n *\n * ```js\n * import { x25519 } from '@noble/curves/ed25519.js';\n * const alice = x25519.keygen();\n * const bob = x25519.keygen();\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n return montgomery({\n P,\n type: 'x25519',\n powPminus2: (x) => {\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, _3n, P) * b2, P);\n },\n adjustScalarBytes,\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\n/**\n * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later.\n * @private\n */\n// prettier-ignore\nexport function _map_to_curve_elligator2_curve25519(u) {\n const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic\n const ELL2_J = BigInt(486662);\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let xd = Fp.add(tv1, Fp.ONE);\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let y1 = Fp.cmov(y12, y11, e1);\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n let y2 = Fp.cmov(y22, y21, e2);\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n// sgn0(c1) MUST equal 0\nconst ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))();\nfunction map_to_curve_elligator2_edwards25519(u) {\n // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u)\n const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u);\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let yd = Fp.add(xMn, xMd);\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division\n // Noble normalizes the RFC rational representation to affine `{ x, y }`\n // before returning from the internal helper.\n return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd)\n}\n/**\n * Hashing to ed25519 points / field. RFC 9380 methods.\n * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the\n * internal map callback below consumes one field element bigint, not `[bigint]`.\n * @example\n * Hash one message onto the ed25519 curve.\n *\n * ```ts\n * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: ed25519_CURVE_p,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n}))();\n// √(-1) aka √(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// √(ad - 1)\nconst SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');\n// 1 / √(a-d)\nconst INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');\n// 1-d²\nconst ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');\n// (d-1)²\nconst D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');\n// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`,\n// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch.\nconst invertSqrt = (number) => uvRatio(_1n, number);\nconst MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element\n// derivation. The decode path has the opposite contract and rejects that bit.\nconst bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n/**\n * Computes Elligator map for Ristretto255.\n * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds\n * `hash_to_ristretto255` on top of this helper.\n * Returns an internal Edwards representative, not a public `_RistrettoPoint`.\n */\nfunction calcElligatorRistrettoMap(r0) {\n const { d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P))\n s_ = mod(-s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n/**\n * Wrapper over Edwards Point for ristretto255.\n *\n * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint,\n * but it should work in its own namespace: do not combine those two.\n * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496).\n */\nclass _RistrettoPoint extends PrimeEdwardsPoint {\n // Do NOT change syntax: the following gymnastics is done,\n // because typescript strips comments, which makes bundlers disable tree-shaking.\n // prettier-ignore\n static BASE = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))();\n // prettier-ignore\n static ZERO = \n /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))();\n // prettier-ignore\n static Fp = \n /* @__PURE__ */ (() => Fp)();\n // prettier-ignore\n static Fn = \n /* @__PURE__ */ (() => Fn)();\n constructor(ep) {\n super(ep);\n }\n /**\n * Create one Ristretto255 point from affine Edwards coordinates.\n * This wraps the internal Edwards representative directly and is not a\n * canonical ristretto255 decoding path.\n * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter.\n */\n static fromAffine(ap) {\n return new _RistrettoPoint(ed25519_Point.fromAffine(ap));\n }\n assertSame(other) {\n if (!(other instanceof _RistrettoPoint))\n throw new Error('RistrettoPoint expected');\n }\n init(ep) {\n return new _RistrettoPoint(ep);\n }\n static fromBytes(bytes) {\n abytes(bytes, 32);\n const { a, d } = ed25519_CURVE;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const s = bytes255ToNumberLE(bytes);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P))\n x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n)\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t));\n }\n /**\n * Converts ristretto-encoded string to ristretto point.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode).\n * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex) {\n return _RistrettoPoint.fromBytes(hexToBytes(hex));\n }\n /**\n * Encodes ristretto point to Uint8Array.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode).\n */\n toBytes() {\n let { X, Y, Z, T } = this.ep;\n const P = ed25519_CURVE_p;\n const mod = (n) => Fp.create(n);\n const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1\n const u2 = mod(X * Y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * T); // 6\n let D; // 7\n if (isNegativeLE(T * zInv, P)) {\n let _x = mod(Y * SQRT_M1);\n let _y = mod(X * SQRT_M1);\n X = _x;\n Y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (isNegativeLE(X * zInv, P))\n Y = mod(-Y); // 9\n let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P))\n s = mod(-s);\n return Fp.toBytes(s); // 11\n }\n /**\n * Compares two Ristretto points.\n * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals).\n */\n equals(other) {\n this.assertSame(other);\n const { X: X1, Y: Y1 } = this.ep;\n const { X: X2, Y: Y2 } = other.ep;\n const mod = (n) => Fp.create(n);\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\nObject.freeze(_RistrettoPoint.BASE);\nObject.freeze(_RistrettoPoint.ZERO);\nObject.freeze(_RistrettoPoint.prototype);\nObject.freeze(_RistrettoPoint);\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint });\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * §4.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = Object.freeze({\n Point: _RistrettoPoint,\n /**\n * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats:\n * * There are no test vectors\n * * encodeToCurve / mapToCurve is undefined\n * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map!\n * * hashToScalar is undefined too, so we just use OPRF implementation\n * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC\n (os2ip -> bytes255ToNumberLE)\n * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map\n * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF\n version here. Using `bytes255ToNumblerLE` will create a different result\n if we use `bytes255ToNumberLE` as os2ip\n * * current version is closest to spec.\n */\n hashToCurve(msg, options) {\n // == 'hash_to_ristretto255'\n // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them.\n const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST;\n const xmd = expand_message_xmd(msg, DST, 64, sha512);\n // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`.\n // In RFC 9496, `map` was the per-point function inside the construction.\n // That also led to confusion that `ristretto255_map` is `mapToCurve`.\n // It is not: it is the older hash-to-curve construction.\n return ristretto255_hasher.deriveToCurve(xmd);\n },\n hashToScalar(msg, options = { DST: _DST_scalar }) {\n const xmd = expand_message_xmd(msg, options.DST, 64, sha512);\n return Fn.create(bytesToNumberLE(xmd));\n },\n /**\n * HashToCurve-like construction based on RFC 9496 (Element Derivation).\n * Converts 64 uniform random bytes into a curve point.\n *\n * WARNING: This represents an older hash-to-curve construction from before\n * RFC 9380 was finalized.\n * It was later reused as a component in the newer\n * `hash_to_ristretto255` function defined in RFC 9380.\n */\n deriveToCurve(bytes) {\n // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation\n abytes(bytes, 64);\n const r1 = bytes255ToNumberLE(bytes.subarray(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(bytes.subarray(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new _RistrettoPoint(R1.add(R2));\n },\n});\n/**\n * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497.\n * @example\n * Run one blind/evaluate/finalize OPRF round over ristretto255.\n *\n * ```ts\n * const input = new TextEncoder().encode('hello noble');\n * const keys = ristretto255_oprf.oprf.generateKeyPair();\n * const blind = ristretto255_oprf.oprf.blind(input);\n * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded);\n * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated);\n * ```\n */\nexport const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({\n name: 'ristretto255-SHA512',\n Point: _RistrettoPoint,\n hash: sha512,\n hashToGroup: ristretto255_hasher.hashToCurve,\n hashToScalar: ristretto255_hasher.hashToScalar,\n}))();\n/**\n * FROST threshold signatures over ristretto255. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 ristretto255 signing.\n *\n * ```ts\n * const alice = ristretto255_FROST.Identifier.derive('alice@example.com');\n * const bob = ristretto255_FROST.Identifier.derive('bob@example.com');\n * const carol = ristretto255_FROST.Identifier.derive('carol@example.com');\n * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({\n name: 'FROST-RISTRETTO255-SHA512-v1',\n Point: _RistrettoPoint,\n validatePoint: (p) => {\n // Prime-order wrappers are torsion-free at the abstract-group level.\n p.assertValidity();\n },\n hash: sha512,\n}))();\n/**\n * Weird / bogus points, useful for debugging.\n * All 8 ed25519 points of 8-torsion subgroup can be generated from the point\n * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`.\n * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the\n * array below is that set, not the powers in that exact index order.\n * @example\n * Decode one known torsion point for debugging.\n *\n * ```ts\n * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js';\n * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]);\n * ```\n */\nexport const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n]);\n//# sourceMappingURL=ed25519.js.map","import { createSign, createVerify, createHash, randomBytes, type KeyObject } from \"node:crypto\";\nimport { ed25519 } from \"@noble/curves/ed25519.js\";\n\nconst CURVE25519_KEY_SIZE = 32;\nconst CLAMP_MASK_LOW = 248;\nconst CLAMP_MASK_HIGH = 127;\nconst CLAMP_HIGH_BIT = 64;\nconst SHARED_SIGN_BIT = 0x80;\nconst PRIVATE_KEY_TOP_MASK = 0x7f;\n\n/** Clamp a Curve25519 scalar in-place (required before scalar multiplication). */\nexport function clampScalar(key: Uint8Array): void {\n if (key.length < CURVE25519_KEY_SIZE) return;\n key[0] = (key[0] ?? 0) & CLAMP_MASK_LOW;\n key[CURVE25519_KEY_SIZE - 1] =\n ((key[CURVE25519_KEY_SIZE - 1] ?? 0) & CLAMP_MASK_HIGH) | CLAMP_HIGH_BIT;\n}\n\n/**\n * Generate an ephemeral Ed25519 key pair for the TS3 handshake.\n * Returns [publicKey (32 bytes, RFC-8032 encoded), privateKey (32 bytes)].\n */\nexport function generateTemporaryKey(): [Uint8Array, Uint8Array] {\n const privateKey = new Uint8Array(randomBytes(CURVE25519_KEY_SIZE));\n clampScalar(privateKey);\n\n // Base point G is in the prime-order subgroup, so G*s = G*(s mod n).\n // Safe to reduce here since G has no small-order component.\n const scalar = bytesToBigIntLE(privateKey) % ed25519.Point.CURVE().n;\n const publicKey = ed25519.Point.BASE.multiply(scalar).toBytes();\n\n return [publicKey, Uint8Array.from(privateKey)];\n}\n\n/**\n * Sign data with a P-256 private key (SHA-256 hash, ASN.1 DER encoded).\n */\nexport function sign(privateKey: KeyObject, data: Uint8Array): Uint8Array {\n const signer = createSign(\"SHA256\");\n signer.update(data);\n return signer.sign(privateKey);\n}\n\n/**\n * Verify a P-256 ECDSA signature (SHA-256 hash, ASN.1 DER encoded).\n */\nexport function verifySign(publicKey: KeyObject, data: Uint8Array, sig: Uint8Array): boolean {\n try {\n const verifier = createVerify(\"SHA256\");\n verifier.update(data);\n return verifier.verify(publicKey, Buffer.from(sig));\n } catch {\n return false;\n }\n}\n\n/**\n * TS3-specific shared secret derivation using Ed25519 point arithmetic.\n * Mirrors NaCl's ge_scalarmult_vartime:\n * 1. Negate the public point\n * 2. Scalar-multiply by clamped private key bytes (NOT reduced mod n)\n * 3. Flip sign bit of result\n * 4. SHA-512 the resulting point bytes\n *\n * The scalar must NOT be reduced mod n: Ed25519 has cofactor 8, so the server's\n * public key may have a small-order component, and P*s ≠ P*(s mod n) in that case.\n * We use scalarMultFull to handle scalars >= n without losing the cofactor term.\n */\nexport function getSharedSecret2(\n publicKeyBytes: Uint8Array,\n privateKeyBytes: Uint8Array,\n): Uint8Array {\n if (\n publicKeyBytes.length !== CURVE25519_KEY_SIZE ||\n privateKeyBytes.length !== CURVE25519_KEY_SIZE\n ) {\n throw new Error(\"invalid key length\");\n }\n\n const privCopy = Uint8Array.from(privateKeyBytes);\n privCopy[CURVE25519_KEY_SIZE - 1] =\n (privCopy[CURVE25519_KEY_SIZE - 1] ?? 0) & PRIVATE_KEY_TOP_MASK;\n\n // Use raw scalar WITHOUT reducing mod n — matches NaCl's ge_scalarmult_vartime.\n // Ed25519 has cofactor 8, so P*s ≠ P*(s mod n) when P has a small-order component.\n // Since @noble/curves rejects scalars >= n, we decompose: P*s = P*(s%n) + (P*n)*q\n const rawScalar = bytesToBigIntLE(privCopy);\n\n const pub = ed25519.Point.fromBytes(publicKeyBytes);\n const negPub = pub.negate();\n\n const sharedPoint = scalarMultFull(negPub, rawScalar);\n const sharedBytes = sharedPoint.toBytes();\n\n // Flip sign bit (mirrors Go: shared[31] ^= 0x80)\n sharedBytes[CURVE25519_KEY_SIZE - 1] =\n (sharedBytes[CURVE25519_KEY_SIZE - 1] ?? 0) ^ SHARED_SIGN_BIT;\n\n return createHash(\"sha512\").update(sharedBytes).digest();\n}\n\n// ---- Internal ---------------------------------------------------------------\n\n/**\n * Multiply an Ed25519 point by a scalar that may be >= curve order n.\n * Decomposes as: P*s = P*(s mod n) + (P*n)*q where q = floor(s/n).\n * This preserves the small-order component (cofactor 8) that would be\n * lost by reducing mod n first.\n *\n * For a clamped 255-bit scalar, q is at most 7 (since maxScalar / n < 8),\n * so the second term is computed with at most one extra scalar multiplication.\n */\nexport function scalarMultFull(\n point: InstanceType<typeof ed25519.Point>,\n scalar: bigint,\n): InstanceType<typeof ed25519.Point> {\n const n = ed25519.Point.CURVE().n;\n if (scalar < n) {\n return scalar === 0n ? ed25519.Point.ZERO : point.multiply(scalar);\n }\n const remainder = scalar % n;\n const quotient = scalar / n; // integer division, 1 <= quotient <= 7 for clamped scalars\n\n // P * (s mod n)\n const mainPart = remainder === 0n ? ed25519.Point.ZERO : point.multiply(remainder);\n\n // (P * n) * q — compute P*n via P*(n-1)+P since multiply() rejects scalar == n\n const pointTimesN = point.multiply(n - 1n).add(point);\n const cofactorPart = pointTimesN.multiply(quotient);\n\n return mainPart.add(cofactorPart);\n}\n\n/** Interpret a little-endian byte array as an unsigned BigInt. */\nexport function bytesToBigIntLE(bytes: Uint8Array): bigint {\n let result = 0n;\n for (let i = bytes.length - 1; i >= 0; i--) {\n result = (result << 8n) | BigInt(bytes[i]!);\n }\n return result;\n}\n"],"x_google_ignoreList":[2,3,4,5,6,7,8,9,10,11],"mappings":";;AAAA,IAAa,IAAb,cAAoC,MAAM;CACxC,YAAY,GAAiB,GAAwB;EAEnD,AADA,MAAM,GAAS,CAAO,GACtB,KAAK,O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