@honeybbq/teamspeak-client 0.3.1 → 0.3.2

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/address-BR-5unVo.cjs.map +1 -1
  2. package/dist/address-BfmovVpp.js.map +1 -1
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/client.d.ts +16 -1
  5. package/dist/client.d.ts.map +1 -1
  6. package/dist/command/index.cjs +1 -1
  7. package/dist/command/index.mjs +1 -1
  8. package/dist/command/parser.d.ts.map +1 -1
  9. package/dist/{crypt-init2-D70ha4LB.js → crypt-init2-BcGT--df.js} +2 -2
  10. package/dist/{crypt-init2-D70ha4LB.js.map → crypt-init2-BcGT--df.js.map} +1 -1
  11. package/dist/{crypt-init2-DparLekm.cjs → crypt-init2-Bkee1YxV.cjs} +2 -2
  12. package/dist/{crypt-init2-DparLekm.cjs.map → crypt-init2-Bkee1YxV.cjs.map} +1 -1
  13. package/dist/crypto/identity.d.ts +13 -1
  14. package/dist/crypto/identity.d.ts.map +1 -1
  15. package/dist/crypto/index.cjs +1 -1
  16. package/dist/crypto/index.d.ts +2 -1
  17. package/dist/crypto/index.d.ts.map +1 -1
  18. package/dist/crypto/index.mjs +3 -3
  19. package/dist/{crypto-CDlweUL3.cjs → crypto-BfDd9DP6.cjs} +2 -2
  20. package/dist/{crypto-CDlweUL3.cjs.map → crypto-BfDd9DP6.cjs.map} +1 -1
  21. package/dist/{crypto-Bg02m4ZE.js → crypto-DLV3oH5F.js} +12 -12
  22. package/dist/{crypto-Bg02m4ZE.js.map → crypto-DLV3oH5F.js.map} +1 -1
  23. package/dist/{handler-DI_abe9c.js → handler-BpdZFsKo.js} +104 -102
  24. package/dist/handler-BpdZFsKo.js.map +1 -0
  25. package/dist/handler-aywHvv7I.cjs +2 -0
  26. package/dist/handler-aywHvv7I.cjs.map +1 -0
  27. package/dist/handshake/index.cjs +1 -1
  28. package/dist/handshake/index.mjs +1 -1
  29. package/dist/handshake.d.ts +9 -0
  30. package/dist/handshake.d.ts.map +1 -1
  31. package/dist/index.cjs +2 -2
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.mjs +294 -290
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/{parser-DZMv3Jm-.js → parser-BX8NEiBe.js} +4 -4
  36. package/dist/parser-BX8NEiBe.js.map +1 -0
  37. package/dist/parser-BfwYH2fT.cjs +2 -0
  38. package/dist/parser-BfwYH2fT.cjs.map +1 -0
  39. package/dist/{primitives-xIr6Tjk4.js → primitives-CdX74Rgu.js} +194 -190
  40. package/dist/primitives-CdX74Rgu.js.map +1 -0
  41. package/dist/primitives-DkwW7wcP.cjs +2 -0
  42. package/dist/primitives-DkwW7wcP.cjs.map +1 -0
  43. package/dist/transfer.d.ts.map +1 -1
  44. package/dist/transport/handler.d.ts +9 -1
  45. package/dist/transport/handler.d.ts.map +1 -1
  46. package/dist/transport/index.cjs +1 -1
  47. package/dist/transport/index.mjs +1 -1
  48. package/dist/types.d.ts +11 -0
  49. package/dist/types.d.ts.map +1 -1
  50. package/package.json +5 -2
  51. package/dist/handler-DI_abe9c.js.map +0 -1
  52. package/dist/handler-DuwoO5RC.cjs +0 -2
  53. package/dist/handler-DuwoO5RC.cjs.map +0 -1
  54. package/dist/parser-CL33R9tr.cjs +0 -2
  55. package/dist/parser-CL33R9tr.cjs.map +0 -1
  56. package/dist/parser-DZMv3Jm-.js.map +0 -1
  57. package/dist/primitives-cNNAeFCo.cjs +0 -2
  58. package/dist/primitives-cNNAeFCo.cjs.map +0 -1
  59. package/dist/primitives-xIr6Tjk4.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"primitives-xIr6Tjk4.js","names":["isBytes","atitle","anumber","abytes","aobject","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","_4n","_5n","_8n","gcd","_0n","_1n","_4n","_1n","_2n","_8n","wcRandomBytes","TeamspeakError","message","options","ServerError","serverMessage","id","CommandTimeoutError","command","AlreadyConnectedError","EAXTagMismatchError","FakeSignatureMismatchError","FileTransferError","FileTransferTimeoutError","CryptoInitError","InvalidIdentityError","P256_SCALAR_SIZE","P256_UNCOMPRESSED_KEY_SIZE","P256_POINT_PREFIX","Identity","privateKey","offset","rawJwk","encodeTsPublicKey","base64UrlToBytes","jwk","dBytes","h","createHash","countLeadingZeros","prefix","signal","targetLevel","resolve","identityFromString","colonIdx","s","dBase64","offsetStr","padded","ecdh","createECDH","pub","x","y","createPrivateKey","generateIdentity","generateKeyPairSync","getUidFromPublicKey","sum","publicKey","hash512","data","bitStringDer","encodeDerTlv","integerSize","encodePositiveInt","integerX","integerY","importPublicKey","point","parseTsPublicKeyDer","createPublicKey","parseTsCanonicalPublicKey","parseTsLegacyPublicKey","seq","parseDerTlv","bs","sizeInt","xInt","yInt","buildUncompressedPoint","positiveIntToBytes","lenBytes","encodeDerLength","value","tag","len","v","bytes","start","trimmed","expectedTag","pos","firstLenByte","int","stripped","size","buf","b64url","zeros","b","i","U32_MASK64","_32n","fromBig","le","n","split","lst","Ah","Al","l","fromNumH","fromNumL","setU64FromNum","view","byteOffset","isLE","shrSH","shrSL","rotrSH","rotrSL","rotrBH","rotrBL","add","Bl","Bh","add3L","Cl","add3H","Ch","low","add4L","Dl","add4H","Dh","add5L","El","add5H","Eh","isBytes$1","a","atitle$1","title","anumber$1","abytes$1","length","ofLen","got","aobject$1","label","aopts","proto","aexists","instance","checkFinished","aoutput","out","min","clean","arrays","createView","arr","hasHexBuiltin","hexes","bytesToHex$1","hex","asciiToBase16","ch","hexToBytes$1","error","hl","al","array","ai","hi","n1","n2","char","concatBytes$1","res","pad","checkOpts","defaults","opts","createHasher","hashCons","info","hashC","msg","tmp","randomBytes$2","bytesLength","cr","oidNist","suffix","HashMD","blockLen","outputLen","padOffset","processed","take","dataView","buffer","oview","outLen","state","destroyed","finished","to","SHA512_IV","K512","SHA512_Kh","SHA512_Kl","SHA512_W_H","SHA512_W_L","SHA2_64B","IV","Fh","Fl","Gh","Gl","Hh","Hl","W15h","W15l","s0h","s0l","W2h","W2l","s1h","SUMl","SUMh","sigma1h","sigma1l","CHIh","CHIl","T1ll","T1h","T1l","sigma0h","sigma0l","MAJh","MAJl","All","_SHA512","sha512","aarray","item","abytes","anumber","aobject","afunction","bytesToHex","concatBytes","hexToBytes","isBytes","randomBytes$1","_0n$3","_1n$4","atitle","abool","abignumber","isPosBig","asafenumber","hexToNumber","bytesToNumberBE","bytesToNumberLE","copyBytes","numberToBytesBE","expectedLen","numberToBytesLE","inRange","max","aInRange","bitLen","bitMask","validateObject","object","fields","optFields","checkField","fieldName","val","isOpt","expectedType","current","iter","f","k","_0n$2","_1n$3","_2n$2","_3n","_4n$2","_5n$1","_7n","_8n$2","_9n","_15n","_16n","POW_WINDOWED_MIN","mod","result","pow","modulo","power","num","d","p","digits","table","w","digit","pow2","invert","number","u","q","r","m","assertIsSquare","F","Fp","root","aoddModulus","order","fnName","sqrt3mod4","p1div4","sqrt5mod8","p5div8","nv","sqrt9mod16","Fp_","Field","P","tn","tonelliShanks","c1","c2","c3","c4","tv1","tv2","tv3","tv4","e1","e2","e3","Q","S","Z","_Fp","FpLegendre","cc","Q1div2","M","t","R","t_tmp","exponent","FpSqrt","isNegativeLE","FIELD_FIELDS","validateField","field","name","FpInvertBatch","nums","passZero","inverted","multipliedAcc","acc","invertedAcc","p1mod2","powered","yes","zero","no","nLength","nBitLength","bits","_nBitLength","FIELD_SQRT","_Field","ORDER","_nbitLength","nByteLength","lhs","rhs","sqrt","allowedLengths","modFromBytes","BYTES","scalar","skipValidation","condition","_0n$1","_1n$2","_4n$1","BLIND_BYTES","BLIND_BITS","FW_WINDOW","TABLE_BYTES_MAX","validatePointCons","pc","Point","normalizeZ","c","validateMSMPoints","points","invertedZs","validateW","W","validateTableBytes","numPoints","fpBytes","probeRandomBytes","randomBytes","probe","validateMSMScalars","scalars","maxScalar","pointWindowSizes","getWindowSize","oddMultiples","dbl","j","wnafDigits","half","mask","signedWindowDigits","shiftBy","windows","wnafWalk","bit","tables","ScalarMultiplier","comp","base","precomputes","idx","sel","neg","entries","entry","transform","blind","window","cofactor","mulAddUnsafe","allowOversized","createField","createCurveFields","type","FpFnLE","CURVE","curveOpts","Fn","params","createKeygen","secretKey","randomSecretKey","seed","getPublicKey","_0n","_1n$1","_2n$1","_4n","_8n$1","isEdValidXY","x2","y2","left","right","edwards","extraOpts","validated","MASK","isOdd","uvRatio","mulA","acoord","banZero","aedpoint","other","X","Y","T","zip215","normed","lastByte","isValid","isXOdd","isLastByteOdd","wnaf","windowSize","isLazy","X2","Y2","Z2","Z4","aX2","XY","ZT","X1","Y1","Z1","X1Z2","X2Z1","Y1Z2","Y2Z1","A","B","C","D","x1y1","E","G","H","X3","Y3","T3","Z3","T1","T2","normalize","iz","invertedZ","is0","zz","eddsa","cHash","hash","eddsaOpts","toMontgomery","toMontgomerySecret","adjustScalarBytes","domain","phflag","ctx","modN_LE","getPrivateScalar","lengths","key","hashed","head","getExtendedPublicKey","BASE","hashDomainToScalar","msgs","context","prehash","sign","pointBytes","verifyOpts","verify","sig","mid","SB","_size","isValidSecretKey","isValidPublicKey","utils","_1n","_2n","_5n","_8n","ed25519_CURVE_p","ed25519_CURVE","ed25519_pow_2_252_3","_10n","_20n","_40n","_80n","b2","b5","b10","b20","b40","b80","ED25519_SQRT_M1","v3","vx2","root1","root2","useRoot1","useRoot2","noRoot","ed25519_Point","ed","ed25519","CURVE25519_KEY_SIZE","CLAMP_MASK_LOW","CLAMP_MASK_HIGH","CLAMP_HIGH_BIT","SHARED_SIGN_BIT","PRIVATE_KEY_TOP_MASK","clampScalar","generateTemporaryKey","bytesToBigIntLE","signer","createSign","verifySign","verifier","createVerify","getSharedSecret2","publicKeyBytes","privateKeyBytes","privCopy","rawScalar","sharedBytes","scalarMultFull","remainder","quotient","mainPart","cofactorPart"],"sources":["../src/errors.ts","../src/crypto/identity.ts","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js","../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js","../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js","../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js","../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js","../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/edwards.js","../node_modules/.pnpm/@noble+curves@2.4.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 rawJwk = this.privateKey.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, 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","const U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();\nconst _32n = /* @__PURE__ */ BigInt(32);\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// Split a JS number into u32 halves without a BigInt allocation. Exact only for integers\n// `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below\n// that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).\nconst fromNumH = (n) => (n / 2 ** 32) | 0;\nconst fromNumL = (n) => n >>> 0;\n// Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call\n// BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.\nfunction setU64FromNum(view, byteOffset, n, isLE) {\n const h = fromNumH(n);\n const l = fromNumL(n);\n view.setUint32(byteOffset, isLE ? l : h, isLE);\n view.setUint32(byteOffset + 4, isLE ? h : l, isLE);\n}\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h, _l, s) => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h, l) => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h, _l) => h;\n// 64-bit left rotates (rotl*) are not defined here: sha3.ts, their only consumer, keeps\n// local copies so V8 inlines them into keccakP.\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, fromNumH, fromNumL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, setU64FromNum, shrSH, shrSL, split, toBig };\n","/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a) {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1));\n}\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @returns The validated number.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n, title = '') {\n if (typeof n !== 'number')\n throw new TypeError(atitle(title) + 'expected number, got ' + typeof n);\n if (!Number.isSafeInteger(n) || n < 0)\n throw new RangeError(atitle(title) + 'expected integer >= 0, got ' + n);\n return n;\n}\n/**\n * Asserts something is a boolean.\n * @param value - value to validate\n * @param title - label included in thrown errors\n * @returns The validated boolean.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a boolean option.\n * ```ts\n * abool(true, 'enableXOF');\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(value, length, title = '') {\n // Success path first: this runs at the start of every update() / digestInto(), and the\n // common `abytes(data)` form must not pay for length handling it does not use.\n if (isBytes(value) && (length === undefined || value.length === length))\n return value;\n // Error path: recompute freely to build the exact message.\n if (length !== undefined)\n anumber(length, 'length');\n const bytes = isBytes(value);\n const ofLen = length !== undefined ? ` of length ${length}` : '';\n const got = bytes ? `length=${value.length}` : `type=${typeof value}`;\n const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes)\n throw new TypeError(message);\n throw new RangeError(message);\n}\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('expected hash wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1 || h.blockLen < 1)\n throw new Error('hash blockLen / outputLen must be >= 1');\n}\nconst aobject = (value, label) => {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError((label === 'object' ? '' : `\"${label}\" `) + 'expected object, got type=' + typeof value);\n};\nconst aopts = (value, label) => {\n aobject(value, label);\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null)\n throw new TypeError(`\"${label}\" expected plain object`);\n // Object.assign() treats an own \"__proto__\" source key as a write to the target's legacy\n // prototype setter. Reject it before merging so inherited option values cannot be injected.\n if (Object.hasOwn(value, '__proto__'))\n throw new TypeError(`\"${label}.__proto__\" is not allowed`);\n};\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance, checkFinished = true) {\n // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their\n // truthiness is checked - re-validating their type per call was pure hot-path overhead.\n if (instance.destroyed)\n throw new Error('hash was destroyed');\n if (checkFinished && instance.finished)\n throw new Error('digest() was already called');\n}\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out, instance) {\n abytes(out, undefined, 'output');\n // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast\n // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.\n const min = instance.outputLen;\n if (!(out.length >= min)) {\n throw new RangeError('\"output\" expected length >= ' + min);\n }\n}\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Whether the current platform is little-endian. */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n) >>> 0;\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// Strict ASCII nibble parser: non-ASCII hex lookalikes are rejected as undefined.\n// ASCII codes: '0'..'9' = 48..57, 'A'..'F' = 65..70, 'a'..'f' = 97..102.\n// prettier-ignore\nfunction asciiToBase16(ch) {\n return ch >= 48 && ch <= 57 ? ch - 48 // '2' => 50-48\n : ch >= 65 && ch <= 70 ? ch - (65 - 10) // 'B' => 66-(65-10)\n : ch >= 97 && ch <= 102 ? ch - (97 - 10) // 'b' => 98-(97-10)\n : undefined;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return Uint8Array.fromHex(hex);\n }\n catch (error) {\n if (error instanceof SyntaxError)\n throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n}\n/**\n * Yields to the host task scheduler so timers, I/O, and rendering can make progress.\n * Uses the Web Scheduling API when available or `setTimeout` as a cross-platform fallback.\n * Host-task yields are much slower than microtasks (roughly 1ms with the timer fallback), so\n * async loops should use `asyncTick >= 10` to amortize scheduling overhead to about 10% while\n * still allowing other event-loop work to proceed.\n * @param onReject - optional cleanup invoked only if the host yield fails\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport function nextTick(onReject) {\n const host = globalThis;\n if (typeof host.scheduler?.yield === 'function') {\n const promise = host.scheduler.yield();\n // Keep the original scheduler rejection; this handler exists only for cleanup.\n if (onReject)\n promise.catch(onReject);\n return promise;\n }\n return new Promise((resolve) => host.setTimeout(resolve, 0));\n}\n/**\n * Returns control to the host event loop every `tick` 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 * @param onReject - optional cleanup invoked only if a host yield fails\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(iters, tick, cb, onReject) {\n anumber(iters, 'iters');\n anumber(tick, 'tick');\n if (typeof cb !== 'function')\n throw new TypeError('callback must be a function');\n // Callback is synchronous by contract; asyncLoop only yields between sync work windows.\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick(onReject);\n // Track only synchronous work time; scheduler delay after yielding is outside our budget.\n ts = Date.now();\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 const encoded = new TextEncoder().encode(str);\n try {\n // Copy into the current realm for Firefox extension contexts. Callers that own the returned\n // buffer can then wipe it independently of TextEncoder's temporary result.\n return new Uint8Array(encoded); // https://bugzil.la/1681809\n }\n finally {\n clean(encoded);\n }\n}\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data, errorTitle = '') {\n if (typeof data === 'string')\n return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `abytes()`, `abool()`, or `anumber()` instead.\n * @param object - object to validate\n * @param fields - map of required field names to expected types\n * @param optFields - map of optional field names to expected types\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate required and optional option fields.\n * ```ts\n * validateObject({ N: 1024, dkLen: 32 }, { N: 'number' }, { dkLen: 'number' });\n * ```\n */\nexport const validateObject = (object, fields = {}, optFields = {}, title = 'object') => {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @param title - label included in thrown override errors\n * @returns Fresh merged option object with a null prototype.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(defaults, opts, title = 'opts') {\n aopts(defaults, 'defaults');\n if (opts !== undefined)\n aopts(opts, title);\n // Callers read optional fields directly, so omitted values must not fall through to ambient\n // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).\n const merged = Object.assign(Object.create(null), defaults, opts);\n return merged;\n}\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher(hashCons, info = {}) {\n if (typeof hashCons !== 'function')\n throw new TypeError('\"hashCons\" expected function, got type=' + typeof hashCons);\n info = checkOpts({}, info, 'info');\n const hashC = (msg, opts) => hashCons(opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC);\n}\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32) {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? globalThis.crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 §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","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { setU64FromNum } from \"./_u64.js\";\nimport { abytes, aexists, aoutput, createView } from \"./utils.js\";\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a, b, c) {\n return (a & b) ^ (~a & c);\n}\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a, b, c) {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport class HashMD {\n blockLen;\n outputLen;\n canXOF = false;\n padOffset;\n isLE;\n // For partial updates less than block size\n buffer;\n view;\n finished = false;\n length = 0;\n pos = 0;\n destroyed = false;\n constructor(blockLen, outputLen, padOffset, isLE) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n let processed = false;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n processed = true;\n continue;\n }\n // When the whole input is buffered in one go (common for short messages), passing `data`\n // directly avoids allocating a subarray view.\n buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n processed = true;\n }\n }\n this.length += data.length;\n // Shared schedule buffers only pick up input-derived words inside process(); if everything\n // was buffered without processing, there is nothing to zero.\n if (processed)\n this.roundClean();\n return this;\n }\n digestInto(out) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message, then zero-pad the rest of the block\n buffer[pos++] = 0b10000000;\n buffer.fill(0, pos);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n buffer.fill(0);\n }\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an\n // integer below 2**53, so the split inside the helper stays exact).\n setU64FromNum(view, blockLen - 8, this.length * 8, isLE);\n this.process(view, 0);\n // The final block above is processed outside update(), so the shared message-schedule\n // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().\n this.roundClean();\n // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.\n const oview = out === buffer ? view : createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n const outLen = len / 4;\n const state = this.get();\n // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.\n if (len % 4 || outLen > state.length)\n throw new Error('invalid outputLen');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneIntoMeta(to) {\n const { buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (pos)\n to.buffer.set(buffer); // Avoid a hot modulo guard.\n return to;\n }\n clone() {\n return this._cloneInto();\n }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state from RFC 6234 §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","/**\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 // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and makes sha256 3x slower (measured).\n A = 0;\n B = 0;\n C = 0;\n D = 0;\n E = 0;\n F = 0;\n G = 0;\n H = 0;\n constructor(outputLen, IV) {\n super(64, outputLen, 8, false);\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n clean(SHA256_W);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */\nexport class _SHA256 extends SHA2_32B {\n constructor() {\n super(32, SHA256_IV);\n }\n}\n/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */\nexport class _SHA224 extends SHA2_32B {\n constructor() {\n super(28, SHA224_IV);\n }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// SHA-384 / SHA-512 round constants from RFC 6234 §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 // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n // h -- high 32 bits, l -- low 32 bits\n // Numeric initializers matter: starting the fields as `undefined` changes\n // V8's field representation and slows hashing down (measured on sha256).\n Ah = 0;\n Al = 0;\n Bh = 0;\n Bl = 0;\n Ch = 0;\n Cl = 0;\n Dh = 0;\n Dl = 0;\n Eh = 0;\n El = 0;\n Fh = 0;\n Fl = 0;\n Gh = 0;\n Gl = 0;\n Hh = 0;\n Hl = 0;\n constructor(outputLen, IV) {\n super(128, outputLen, 16, false);\n this.Ah = IV[0] | 0;\n this.Al = IV[1] | 0;\n this.Bh = IV[2] | 0;\n this.Bl = IV[3] | 0;\n this.Ch = IV[4] | 0;\n this.Cl = IV[5] | 0;\n this.Dh = IV[6] | 0;\n this.Dl = IV[7] | 0;\n this.Eh = IV[8] | 0;\n this.El = IV[9] | 0;\n this.Fh = IV[10] | 0;\n this.Fl = IV[11] | 0;\n this.Gh = IV[12] | 0;\n this.Gl = IV[13] | 0;\n this.Hh = IV[14] | 0;\n this.Hl = IV[15] | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n _cloneInto(to) {\n (to ||= new this.constructor()).set(...this.get());\n return this._cloneIntoMeta(to);\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy() {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA512 extends SHA2_64B {\n constructor() {\n super(64, SHA512_IV);\n }\n}\n/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */\nexport class _SHA384 extends SHA2_64B {\n constructor() {\n super(48, SHA384_IV);\n }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B {\n constructor() {\n super(28, T224_IV);\n }\n}\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 §6.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B {\n constructor() {\n super(32, T256_IV);\n }\n}\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), \n/* @__PURE__ */ oidNist(0x01));\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), \n/* @__PURE__ */ oidNist(0x04));\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), \n/* @__PURE__ */ oidNist(0x03));\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), \n/* @__PURE__ */ oidNist(0x02));\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), \n/* @__PURE__ */ oidNist(0x06));\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @param opts - Reserved hash options.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), \n/* @__PURE__ */ oidNist(0x05));\n","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { abytes as abytes_, anumber as anumber_, bytesToHex as bytesToHex_, concatBytes as concatBytes_, hexToBytes as hexToBytes_, isBytes as isBytes_, randomBytes as randomBytes_, } from '@noble/hashes/utils.js';\n/**\n * Validates that a value is an array, optionally validating each element.\n * @param item - Value to validate.\n * @param title - Label included in thrown errors.\n * @param inner - Optional per-element validator, called with the element and its label.\n * @returns The validated array.\n * @example\n * Validate an array of points before batch processing.\n *\n * ```ts\n * aarray([1n, 2n], 'scalars');\n * ```\n */\nexport function aarray(item, title, inner = () => { }) {\n if (!Array.isArray(item))\n throw new TypeError(`\"${title}\" expected array, got type=${typeof item}`);\n for (let i = 0; i < item.length; i++)\n inner(item[i], `${title}[${i}]`);\n return item;\n}\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = (value, length, title) => abytes_(value, length, title);\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @returns The validated number.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber = anumber_;\n/**\n * Asserts something is a string.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a label string.\n *\n * ```ts\n * astring('example', 'label');\n * ```\n */\nexport function astring(value, title = '') {\n if (typeof value !== 'string') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected string, got type=' + typeof value);\n }\n return value;\n}\n/**\n * Asserts something is a plain object-ish value, not null or array.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated object.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate an options object before checking fields.\n *\n * ```ts\n * aobject({ flag: true });\n * ```\n */\nexport function aobject(value, title = 'object') {\n if (value === null || typeof value !== 'object' || Array.isArray(value))\n throw new TypeError(title === 'object'\n ? 'expected valid options object'\n : `\"${title}\" expected object, got type=${typeof value}`);\n return value;\n}\n/**\n * Asserts something is a function.\n * @param value - Value to validate.\n * @param title - Label included in thrown errors.\n * @returns The validated function.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate a required method before calling it.\n *\n * ```ts\n * afunction(() => true, 'predicate');\n * ```\n */\nexport function afunction(value, title) {\n if (typeof value !== 'function')\n throw new TypeError(`\"${title}\" is invalid: expected function, got ${typeof value}`);\n return value;\n}\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays) => concatBytes_(...arrays);\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex) => hexToBytes_(hex);\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength) => randomBytes_(bytesLength);\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n// Shared error-message prefix builder. Only called on throw paths, so assert\n// success paths never pay for the string concatenation.\nconst atitle = (title) => (title ? `\"${title}\" ` : '');\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value, title = '') {\n if (typeof value !== 'boolean')\n throw new TypeError(atitle(title) + 'expected boolean, got type=' + typeof value);\n return value;\n}\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n) {\n if (typeof n === 'bigint') {\n if (!isPosBig(n))\n throw new RangeError('positive bigint expected, got ' + n);\n }\n else\n anumber(n);\n return n;\n}\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value, title = '') {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num) {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes) {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n, len) {\n anumber_(len);\n if (len === 0)\n throw new Error('zero output length is invalid');\n n = abignumber(n);\n const expectedLen = len * 2;\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > expectedLen)\n throw new RangeError('number is too large');\n return hexToBytes_(hex.padStart(expectedLen, '0'));\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If a documented runtime validation or state check fails. {@link Error}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n) {\n return hexToBytes_(numberToHexUnpadded(abignumber(n)));\n}\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a, b) {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length)\n return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++)\n diff |= a[i] ^ b[i];\n return diff === 0;\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes) {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes));\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii) {\n if (typeof ascii !== 'string')\n throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n }\n return charCode;\n });\n}\n/**\n * Checks whether n is non-negative bigint. Historical name.\n * @param n - candidate value\n * @returns `true` when the value is bigint and 0 or larger\n * @example\n * Check a candidate scalar before range validation.\n *\n * ```ts\n * isPosBig(2n);\n * ```\n */\nexport function isPosBig(n) {\n return typeof n === 'bigint' && _0n <= n;\n}\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n, min, max) {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title, n, min, max) {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n) {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n)\n throw new Error('expected non-negative bigint, got ' + n);\n // Native radix conversion beats a shift loop at every size, and the loop is quadratic in bits.\n return n === _0n ? 0 : n.toString(2).length;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n, pos) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n, pos, value) {\n if (typeof n !== 'bigint')\n throw new TypeError('\"n\" expected bigint, got type=' + typeof n);\n asafenumber(pos, 'pos');\n abool(value, 'value');\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n) => {\n asafenumber(n, 'n');\n return (_1n << BigInt(n)) - _1n;\n};\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hmacFn = (key: Uint8Array, msg: Uint8Array) => hmac(sha256, key, msg);\n * const drbg = createHmacDrbg(32, 32, hmacFn);\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function')\n throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len) => new Uint8Array(len);\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs));\n const reseed = (seed = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters)\n throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = pred(gen())) === undefined)\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * This walks field schemas and formats detailed errors, so avoid it on hot paths; use direct\n * one-line guards such as `aobject()`, `afunction()`, `abool()`, or `asafenumber()` instead.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @param title - Object label included in thrown errors.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(object, fields = {}, optFields = {}, title = 'object') {\n aobject(object, title);\n aobject(fields, 'fields');\n aobject(optFields, 'optFields');\n function checkField(fieldName, expectedType, isOpt) {\n const label = title === 'object' ? `param \"${String(fieldName)}\"` : `\"${title}.${String(fieldName)}\"`;\n // Config fields must be explicit own properties. Optional inherited values are rejected too\n // because callers keep reading the same options object after validation.\n const val = object[fieldName];\n // Runtime objects such as Field instances intentionally satisfy required method slots\n // via their shared prototype.\n if (!Object.hasOwn(object, fieldName) &&\n (isOpt ? val !== undefined : expectedType !== 'function')) {\n throw new TypeError(`${label} is invalid: expected own property`);\n }\n if (isOpt && val === undefined)\n return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);\n }\n const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = () => {\n throw new Error('not implemented');\n};\n","/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, abytes, afunction, anumber, aobject, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, } from \"../utils.js\";\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _15n = /* @__PURE__ */ BigInt(15), _16n = /* @__PURE__ */ BigInt(16);\n// 2^64: exponents below this use plain square-and-multiply in pow()/FpPow(); the windowed path's\n// table build (14 multiplications) only pays off for longer exponents (break-even ~50 bits).\nconst POW_WINDOWED_MIN = /* @__PURE__ */ BigInt('0x10000000000000000');\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a, b) {\n if (b <= _0n)\n throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow: expected modulus > 1, got ' + modulo);\n // Non-bigint exponents coerce every comparison below to false and would silently return 1.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return _1n;\n if (power === _1n)\n return num;\n let d = num % modulo;\n if (d < _0n)\n d += modulo;\n // Control flow in both branches below depends only on the exponent, never on `num` — invertCt()\n // relies on that for its (public-exponent) secret-independence guarantee.\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents.\n let p = _1n;\n while (power > _0n) {\n if (power & _1n)\n p = (p * d) % modulo;\n d = (d * d) % modulo;\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first: a 14-multiplication table drops per-window cost to <1\n // multiplication (vs ~2 per window for square-and-multiply), ~25-30% faster for the dense\n // 256-bit exponents of sqrt / Legendre / invertCt.\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = _1n;\n table[1] = d;\n for (let i = 2; i < 16; i++)\n table[i] = (table[i - 1] * d) % modulo;\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n p = (p * p) % modulo;\n const digit = digits[w];\n if (digit !== 0)\n p = (p * table[digit]) % modulo;\n }\n return p;\n}\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x, power, modulo) {\n if (modulo <= _1n)\n throw new Error('pow2: expected modulus > 1, got ' + modulo);\n if (power < _0n)\n throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Modulus greater than 1.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number, modulo) {\n if (number === _0n)\n throw new Error('invert: expected non-zero number');\n // modulo = 1 is the zero ring: gcd(x, 1) = 1 makes the loop below \"succeed\" and return the\n // useless inverse 0. Reject it like pow() and invertCt() do.\n if (modulo <= _1n)\n throw new Error('invert: expected modulus > 1, got ' + modulo);\n // This is variable-time: the loop count depends on `number`. For a secret-independent\n // (Fermat) alternative over a prime modulus, see {@link invertCt} (~4x slower).\n let a = mod(number, modulo);\n let b = modulo;\n // Only the Bézout coefficient of `number` (x/u chain) is tracked; the coefficient of `modulo`\n // never affects the output, so it is not computed.\n // prettier-ignore\n let x = _0n, u = _1n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n // prettier-ignore\n b = a, a = r, x = u, u = m;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Inverses number over modulo using Fermat's little theorem: `a^(p-2) ≡ a⁻¹ (mod p)`.\n *\n * Unlike {@link invert} (extended Euclidean), the exponent `p-2` is a public constant, so the\n * underlying square-and-multiply has the same control flow for every secret `a`: there is no\n * data-dependent branching or loop count that could leak `a` through timing (e.g. Minerva-style\n * ECDSA nonce-inversion attacks). This is only \"algorithmically\" constant-time — JS bigint\n * multiplication/reduction is still value-dependent — and it is roughly 4x slower than\n * {@link invert}.\n *\n * REQUIRES a prime modulus; Fermat's theorem does not hold otherwise. The result is verified to be\n * a real inverse, so a non-prime modulus (or a non-invertible input) fails closed with an error\n * instead of returning a wrong value.\n * @param a - Value to invert.\n * @param prime - Prime modulus.\n * @returns Multiplicative inverse in `[1, prime)`.\n * @throws If the modulus is below 2, the input reduces to zero, or the inverse does not exist.\n * {@link Error}\n * @example\n * Compute one modular inverse without secret-dependent branching.\n *\n * ```ts\n * invertCt(3n, 11n); // 4n, since 3 * 4 = 12 ≡ 1 (mod 11)\n * ```\n */\nexport function invertCt(a, prime) {\n if (prime <= _1n)\n throw new Error('invertCt: expected prime modulus > 1, got ' + prime);\n const an = mod(a, prime);\n if (an === _0n)\n throw new Error('invertCt: expected non-zero number');\n // Exponent (prime - 2) is public, so FpPow's square-and-multiply is secret-independent.\n const inverse = pow(an, prime - _2n, prime);\n // O(1) safety net: verifies the inverse and rejects composite moduli where a^(p-2) is not one.\n if (mod(an * inverse, prime) !== _1n)\n throw new Error('invertCt: does not exist');\n return inverse;\n}\nfunction assertIsSquare(Fp, root, n) {\n const F = Fp;\n if (!F.eql(F.sqr(root), n))\n throw new Error('Cannot find square root');\n}\n// The Legendre symbol and every sqrt variant here are only defined over an odd (prime) modulus.\n// An even ORDER makes their integer divisions — (p-1)/2, (p+1)/4, (p-5)/8, (p+7)/16 — truncate and\n// silently return a wrong result, so reject it explicitly at the entry points instead. This is a\n// cheap necessary-condition check, not a primality test (composite odd moduli are caught later by\n// the Legendre-result / assertIsSquare checks).\nfunction aoddModulus(order, fnName) {\n if ((order & _1n) === _0n)\n throw new Error(fnName + ': expected odd modulus, got ' + order);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n const F = Fp;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp, n) {\n const F = Fp;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P) {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return ((Fp, n) => {\n const F = Fp;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n });\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P) {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n)\n throw new Error('sqrt is not defined for small field');\n aoddModulus(P, 'tonelliShanks');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000)\n throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1)\n return sqrt3mod4;\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n const F = Fp;\n if (F.is0(n))\n return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1)\n throw new Error('Cannot find square root');\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n // Unreachable over a genuine field (no zero divisors; n=0 already returned above). A zero t\n // means composite ORDER, where a fabricated root would be wrong: fail closed instead.\n if (F.is0(t))\n throw new Error('Cannot find square root: probably non-prime P');\n let i = 1;\n // Find the smallest i >= 1 such that t^(2^i) ≡ 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 aoddModulus(P, 'Fp.sqrt');\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 aobject(field, 'field');\n if (typeof field.ORDER !== 'bigint')\n throw new TypeError('param \"ORDER\" is invalid: expected bigint, got ' + typeof field.ORDER);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n for (const name of FIELD_FIELDS)\n afunction(field[name], 'field.' + name);\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1)\n throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field;\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp, num, power) {\n validateField(Fp);\n const F = Fp;\n // Non-bigint exponents (e.g. an accidental field element) coerce every comparison below to\n // false and would silently return ONE.\n if (typeof power !== 'bigint')\n throw new TypeError('invalid exponent: expected bigint, got ' + typeof power);\n if (power < _0n)\n throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n)\n return F.ONE;\n if (power === _1n)\n return num;\n if (power < POW_WINDOWED_MIN) {\n // Square-and-multiply: cheaper than the windowed path for short exponents (e.g. poseidon\n // sbox x^5), which would waste the 14-multiplication table build.\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n }\n // Fixed 4-bit windows, MSB-first — same shape as pow() above, over generic field ops.\n // Speeds up dense long exponents (extension-field sqrt / Legendre, e.g. Fp2 decompression).\n const digits = [];\n while (power > _0n) {\n digits.push(Number(power & _15n));\n power >>= _4n;\n }\n const table = new Array(16);\n table[0] = F.ONE;\n table[1] = num;\n for (let i = 2; i < 16; i++)\n table[i] = F.mul(table[i - 1], num);\n let p = table[digits[digits.length - 1]]; // top digit is nonzero: the loop above stops on 0\n for (let w = digits.length - 2; w >= 0; w--) {\n p = F.sqr(F.sqr(F.sqr(F.sqr(p))));\n const digit = digits[w];\n if (digit !== 0)\n p = F.mul(p, table[digit]);\n }\n return p;\n}\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n validateField(Fp);\n aarray(nums, 'nums');\n abool(passZero, 'passZero');\n const F = Fp;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined);\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num))\n return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num))\n return acc;\n // Non-zero `num` means the forward pass already stored a defined prefix product at index i.\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp, lhs, rhs) {\n validateField(Fp);\n const F = Fp;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 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 powered value does not match a valid Legendre symbol. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp, n) {\n validateField(Fp);\n const F = Fp;\n aoddModulus(F.ORDER, 'FpLegendre');\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no)\n throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp, n) {\n const l = FpLegendre(Fp, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined)\n anumber(nBitLength);\n if (n <= _0n)\n throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap();\nclass _Field {\n ORDER;\n BITS;\n BYTES;\n isLE;\n ZERO = _0n;\n ONE = _1n;\n _lengths;\n _mod;\n constructor(ORDER, opts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n)\n throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number')\n _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean')\n this.isLE = opts.isLE;\n if (opts.allowedLengths)\n this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean')\n this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048)\n throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n create(num) {\n return mod(num, this.ORDER);\n }\n isValid(num) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num) {\n return (num & _1n) === _1n;\n }\n neg(num) {\n return mod(-num, this.ORDER);\n }\n eql(lhs, rhs) {\n return lhs === rhs;\n }\n sqr(num) {\n return mod(num * num, this.ORDER);\n }\n add(lhs, rhs) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs, rhs) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs, rhs) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num, power) {\n return pow(num, power, this.ORDER);\n }\n div(lhs, rhs) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n // Same as above, but doesn't normalize\n sqrN(num) {\n return num * num;\n }\n addN(lhs, rhs) {\n return lhs + rhs;\n }\n subN(lhs, rhs) {\n return lhs - rhs;\n }\n mulN(lhs, rhs) {\n return lhs * rhs;\n }\n inv(num) {\n return invert(num, this.ORDER);\n }\n sqrt(num) {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt)\n FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length);\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes)\n scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst) {\n // `passZero` keeps the `bigint[]` contract honest: zero inputs map to `0` instead of leaking\n // `undefined` into a `bigint[]`. Callers that must distinguish non-invertible inputs should use\n // `FpInvertBatch` directly, whose default omits `passZero` and returns `(bigint | undefined)[]`.\n return FpInvertBatch(this, lst, true);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a, b, condition) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER, opts = {}) {\n // Freeze the shared method surface before any instance is reachable; otherwise callers can\n // poison every Field instance by monkey-patching `_Field.prototype` even if each instance is\n // frozen. Freezing here instead of module scope keeps `_Field` tree-shakeable for importers\n // that never construct a field; the call is idempotent and cheap.\n Object.freeze(_Field.prototype);\n return new _Field(ORDER, opts);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp, elm) {\n validateField(Fp);\n const F = Fp;\n if (!F.isOdd)\n throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n)\n throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // Map into the non-zero scalar range [1, fieldOrder-1]: reduce mod (fieldOrder-1) to land in\n // [0, fieldOrder-2], then add 1. This shifts the range off zero; it is NOT equal to\n // `mod(num, fieldOrder)` (which spans [0, fieldOrder-1] and can be 0). A residual modulo bias\n // remains but is negligible (~2^-(nBits/2), e.g. ~2^-128 for a 256-bit order) because `key` is\n // required to be at least `getMinHashLength(fieldOrder)` (~1.5x field size) bytes of input.\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF-based ScalarMultiplier, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { aarray, abool, afunction, aobject, bitLen, bitMask, bytesToNumberBE, inRange, isBytes, isPosBig, validateObject, } from \"../utils.js\";\nimport { Field, FpInvertBatch, validateField } from \"./modular.js\";\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _4n = /* @__PURE__ */ BigInt(4);\nconst BLIND_BYTES = 16;\nconst BLIND_BITS = 128;\n// Fixed-window width for the constant-time multiply of un-precomputed points (W===1).\n// A flat 2^FW_WINDOW table has a small, scalar-independent build cost that amortizes over a single\n// multiply, unlike the larger per-point wNAF tables that only pay off when cached.\nconst FW_WINDOW = 5;\n// Precompute tables are capped at ~2 GiB of estimated heap. Rejecting larger windows up front\n// turns a typo'd window size into an immediate error instead of a multi-GB allocation (or an\n// effective hang) when the lazy table is built on first multiply.\nconst TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons(Point) {\n const pc = Point;\n if (typeof pc !== 'function')\n throw new TypeError('\"Point\" expected constructor, got type=' + typeof Point);\n afunction(pc.fromAffine, 'Point.fromAffine');\n afunction(pc.fromBytes, 'Point.fromBytes');\n afunction(pc.fromHex, 'Point.fromHex');\n // Generic helpers (ScalarMultiplier, normalizeZ, MSM) dereference BASE / ZERO:\n // fail here with a typed error instead of an `undefined` access later.\n aobject(pc.BASE, 'Point.BASE');\n aobject(pc.ZERO, 'Point.ZERO');\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ(c, points) {\n // Match MSM helpers: reject malformed public inputs before reading projective internals.\n validatePointCons(c);\n validateMSMPoints(points, c);\n // Identity points (Z=0) rely on an implicit contract: FpInvertBatch without `passZero`\n // yields `undefined` for zero inputs, and `toAffine(undefined)` falls back to its internal\n // is0 handling instead of using the batch inverse.\n const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\nfunction validateW(W, bits, min = 1) {\n if (!Number.isSafeInteger(W) || W < min || W > bits)\n throw new Error('invalid window size, expected [' + min + '..' + bits + '], got W=' + W);\n}\n// Rough per-point heap estimate for the {@link TABLE_BYTES_MAX} cap: up to 4 projective/extended\n// coordinates of Fp.BYTES each, plus bigint/object overhead. Callers pass the point count of the\n// largest table the checked parameters can produce.\nfunction validateTableBytes(numPoints, fpBytes) {\n const bytes = numPoints * (4 * fpBytes + 128);\n if (bytes > TABLE_BYTES_MAX)\n throw new Error('invalid window size: table would need ~' +\n Math.ceil(bytes / 2 ** 20) +\n ' MiB, max ' +\n TABLE_BYTES_MAX / 2 ** 20 +\n ' MiB');\n}\n/**\n * Probes an RNG once, at construction time: returns `undefined` when it is unavailable —\n * throws or returns malformed bytes — so callers can downgrade to their unblinded /\n * deterministic constant-time fallback. Blinding is defense-in-depth (DPA/template\n * hardening), not a correctness or key-secrecy requirement, so availability-based\n * downgrade is acceptable.\n *\n * The downgrade decision is deliberately static. After a successful probe the RNG becomes\n * part of the trusted contract: later misbehavior must fail closed in per-call validation\n * (throw), never downgrade — a dynamic fallback would let a tampered RNG silently strip\n * blinding on demand. A probe can only ever classify broken environments, not adversarial\n * RNGs: a stateful RNG can always behave while probed and misbehave later.\n * @param randomBytes - RNG to probe, or `undefined` when the environment provides none.\n * @param length - Byte length requested from the probe call.\n * @returns The RNG when the probe produced `length` valid bytes; `undefined` otherwise.\n * @example\n * Probe an RNG once before enabling scalar blinding.\n *\n * ```ts\n * import { probeRandomBytes } from '@noble/curves/abstract/curve.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const rng = probeRandomBytes(randomBytes, 16);\n * ```\n */\nexport function probeRandomBytes(randomBytes, length) {\n if (randomBytes === undefined)\n return undefined;\n afunction(randomBytes, 'randomBytes');\n try {\n const probe = randomBytes(length);\n if (!isBytes(probe) || probe.length !== length)\n return undefined;\n }\n catch {\n return undefined;\n }\n return randomBytes;\n}\nfunction validateMSMPoints(points, c) {\n aarray(points, 'points');\n points.forEach((p, i) => {\n if (!(p instanceof c))\n throw new Error('invalid point at index ' + i);\n });\n}\n// Default bound is field membership (0 <= s < field.ORDER); a `maxScalar` override widens it\n// to 0 <= s < maxScalar for callers that accept oversized scalars.\nfunction validateMSMScalars(scalars, field, maxScalar) {\n if (!Array.isArray(scalars))\n throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n const ok = maxScalar === undefined ? field.isValid(s) : isPosBig(s) && s < maxScalar;\n if (!ok)\n throw new Error('invalid scalar at index ' + i);\n });\n}\nconst pointWindowSizes = new WeakMap();\nfunction getWindowSize(P) {\n // `1` is the uncached sentinel: use the non-precomputed (wNAF / fixed-window) path.\n return pointWindowSizes.get(P) || 1;\n}\n/** Table of odd multiples [1P, 3P, ..., (2⋅size−1)P]; width-W wNAF uses size = 2^(W−2). */\nfunction oddMultiples(p, size) {\n const dbl = p.double();\n const t = [p];\n for (let j = 1; j < size; j++)\n t.push(t[j - 1].add(dbl));\n return t;\n}\n/**\n * Width-W wNAF signed-digit recoding (W >= 2), LSB-first: digits are 0 or odd with\n * |digit| < 2^(W−1); nonzero density ~1/(W+1) (a nonzero digit is followed by W−1 zeros).\n */\nfunction wnafDigits(n, W) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const d = [];\n while (n > _0n) {\n let w = 0;\n if (n & _1n) {\n w = Number(n & mask); // n mod 2^W, odd\n if (w >= half)\n w -= size; // signed residue\n n -= BigInt(w); // n - w ≡ 0 mod 2^W: next W−1 digits are zero\n }\n d.push(w);\n n >>= _1n;\n }\n return d;\n}\n/**\n * Fixed-position signed-window recoding for precomputed wNAF: `n = Σ digits[w]⋅2^(w⋅W)` with\n * digits in `[−2^(W−1)+1, 2^(W−1)]`. Digit count is fixed by `windows` (callers reserve one\n * extra window for the final carry), so recoding length does not depend on the scalar.\n */\nfunction signedWindowDigits(n, W, windows) {\n const size = 2 ** W;\n const half = size / 2;\n const mask = BigInt(size - 1);\n const shiftBy = BigInt(W);\n const d = [];\n for (let w = 0; w < windows; w++) {\n let v = Number(n & mask);\n n >>= shiftBy;\n if (v > half) {\n v -= size; // negative digit, carry into the next window\n n += _1n;\n }\n d.push(v);\n }\n // Internal invariant: leftover bits mean the window count did not cover the scalar.\n if (n !== _0n)\n throw new Error('invalid wnaf');\n return d;\n}\n/**\n * Shared vartime walk over per-scalar wNAF digit streams: one doubling of a single shared\n * accumulator per bit position of the longest recoding, one signed table addition per\n * nonzero digit. `tables[i]` must hold the odd multiples of the i-th point.\n */\nfunction wnafWalk(zero, tables, digits) {\n let max = 0;\n for (const d of digits)\n max = Math.max(max, d.length);\n let acc = zero;\n for (let bit = max - 1; bit >= 0; bit--) {\n if (bit !== max - 1)\n acc = acc.double();\n for (let i = 0; i < digits.length; i++) {\n const w = digits[i][bit]; // reads past shorter recodings yield undefined, skipped below\n if (w) {\n const item = tables[i][(Math.abs(w) - 1) >> 1];\n acc = acc.add(w < 0 ? item.negate() : item);\n }\n }\n }\n return acc;\n}\n/**\n * Elliptic curve multiplication of Point by scalar.\n * Routes between cached-table, fixed-window, and one-shot wNAF paths; entry points validate\n * their own scalars (`mulCT`/`mulCTBlinded`: `1 <= s < Fn.ORDER`; `mulUnsafe`: up to the\n * `Fn.ORDER^4` DoS cap via {@link mulAddUnsafe}).\n * Table generation is expensive and happens on first call of `multiply()`\n * (or eagerly via `precompute(W, false)`). By default, `BASE` point is precomputed.\n *\n * Cached algorithm is signed fixed-window wNAF:\n * - table stores, for every window w, the multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P` — all doublings\n * are baked in, so a multiplication is exactly one table addition per window\n * - window count is fixed (`ceil(bits/W) + 1`), so the point-operation count is scalar-independent\n * (basis of the constant-time path)\n * - for a 256-bit curve and W=6: 44⋅32 = 1408 table points, 44 additions per multiply\n * - secret scalars are additionally blinded (see {@link ScalarMultiplier.mulCTBlinded}), which\n * widens tables by 128 bits\n * @param Point - Point constructor.\n * @param randomBytes - RNG used for scalar blinding; required by the blinded secret path.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { ScalarMultiplier } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const mul = new ScalarMultiplier(p256.Point);\n * ```\n */\nexport class ScalarMultiplier {\n Point;\n BASE;\n ZERO;\n randomBytes;\n wnafPrecomputes = new WeakMap();\n baseCanBeBlinded;\n bits;\n // Parametrized with a given Point class (not individual point)\n constructor(Point, randomBytes) {\n validatePointCons(Point);\n // Probe the RNG once (see {@link probeRandomBytes}): in environments without working\n // randomness (e.g. no WebCrypto), shouldBlind() then routes secret multiplication to the\n // unblinded constant-time path instead of throwing on every multiply(). The shape of\n // returned bytes is still validated on every blinded call, where breakage fails closed.\n this.randomBytes = probeRandomBytes(randomBytes, BLIND_BYTES);\n this.Point = Point;\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.bits = Point.Fn.BITS;\n }\n /**\n * Creates a signed fixed-window wNAF precomputation table: for every window w, the\n * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,\n * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra\n * window absorbs the final carry of signed-digit recoding.\n * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.\n * @param point - Point instance\n * @param W - window size\n * @param bits - scalar bitlength the table must cover\n */\n buildWnafTable(point, W, bits) {\n // W needs no re-validation: its only source is setWindowSize(), which enforces\n // 1 <= W <= Fn.BITS <= bits (the blinded path only ever widens bits) and caps the\n // resulting table at ~2 GiB (sized against the wider blinded layout).\n const windows = Math.ceil(bits / W) + 1;\n const half = 2 ** (W - 1);\n const comp = [];\n let base = point;\n for (let w = 0; w < windows; w++) {\n let acc = base;\n for (let i = 0; i < half; i++) {\n comp.push(acc);\n acc = acc.add(base);\n }\n base = comp[comp.length - 1].double(); // 2⋅(2^(W−1)⋅base) = next window's base\n }\n return { W, bits, windows, comp };\n }\n /**\n * Implements ec multiplication using precomputed signed fixed-window wNAF tables.\n * Constant-time: fixed window count with one table addition per window — zero digits feed\n * the fake accumulator — and no doublings; the lookup scans the whole window slice.\n * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},\n * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});\n * signedWindowDigits throws if `n` exceeds the table.\n * @returns real and fake (for const-time) points\n */\n wnafCachedCT(precomputes, n) {\n const { W, windows, comp } = precomputes;\n const half = 2 ** (W - 1);\n const digits = signedWindowDigits(n, W, windows);\n let p = this.ZERO;\n let f = this.BASE;\n for (let w = 0; w < windows; w++) {\n const digit = digits[w];\n const start = w * half;\n // Data-oblivious select: touch every entry of the window before the digit branch.\n const idx = Math.abs(digit) - 1; // -1 for zero digits: matches nothing, `sel` unused\n let sel = comp[start];\n for (let i = 1; i < half; i++)\n sel = i === idx ? comp[start + i] : sel;\n const neg = sel.negate(); // compute both signs; the digit only picks one\n if (digit === 0)\n f = f.add(comp[start]);\n else\n p = p.add(digit < 0 ? neg : sel);\n }\n return { p, f };\n }\n // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width\n // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with\n // incompatible `transform(...)` layouts and expect a separate cache entry.\n getWnafPrecomputes(W, point, bits, transform) {\n let entries = this.wnafPrecomputes.get(point);\n let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);\n if (!comp) {\n comp = this.buildWnafTable(point, W, bits);\n if (typeof transform === 'function')\n comp = { ...comp, comp: transform(comp.comp) };\n if (!entries) {\n entries = [];\n this.wnafPrecomputes.set(point, entries);\n }\n entries.push(comp);\n }\n return comp;\n }\n assertPoint(point) {\n if (!(point instanceof this.Point))\n throw new TypeError('\"point\" expected Point instance, got type=' + typeof point);\n }\n // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style\n // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.\n // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.\n validateMulInput(point, scalar) {\n this.assertPoint(point);\n if (!inRange(scalar, _1n, this.Point.Fn.ORDER))\n throw new Error('invalid scalar');\n }\n // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.\n // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window\n // multiply. `n` must be < 2^bits.\n runCT(point, n, bits, transform) {\n const W = getWindowSize(point);\n if (W === 1)\n return this.fixedWindowCT(point, n, bits);\n return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);\n }\n mulCT(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n return this.runCT(point, scalar, this.bits, transform);\n }\n mulCTBlinded(point, scalar, transform) {\n this.validateMulInput(point, scalar);\n // Blinding computes n = scalar + blind*Fn.ORDER, then n*P via a constant-time multiply. This\n // equals scalar*P only when Fn.ORDER*P == O; callers guarantee that via shouldBlind() (always\n // for cofactor-1 curves; for cofactored curves only BASE, and only after checking BASE*n == O).\n // Fail before building the (large) precompute table if randomness is unavailable.\n if (this.randomBytes === undefined)\n throw new Error('randomBytes is required for scalar blinding');\n const bits = this.Point.Fn.BITS + BLIND_BITS;\n const blind = this.randomBytes(BLIND_BYTES);\n if (!isBytes(blind) || blind.length !== BLIND_BYTES)\n throw new Error('randomBytes returned invalid byte array');\n // Force the top two bits of the 128-bit blind to 10xxxxxx, so blind is in [2^127, 1.5*2^127):\n // * `| 0x80` (bit 127 = 1) is the load-bearing part: it guarantees blind >= 2^127, so the blind\n // is always a full-width, nonzero factor and the scalar is masked even with a degenerate RNG.\n // * `& 0x3f` (bit 126 = 0) is a safety margin: it caps blind < 1.5*2^127, keeping\n // blind*Fn.ORDER + scalar < 0.75*2^(nBits+128), i.e. ~half a window below the 2^(nBits+128)\n // ceiling. Not strictly required for the bound (see below), but it reserves headroom so the\n // guarantee does not rest on the tight `Fn.ORDER < 2^Fn.BITS` fact and the final carry window\n // only ever holds a small carry, never a full digit.\n blind[0] = (blind[0] & 0x3f) | 0x80;\n // Even at the extreme (blind < 2^128, scalar < Fn.ORDER < 2^nBits): n <= 2^128*Fn.ORDER - 1 <\n // 2^(nBits+128), so n stays below 2^bits and within the blinded table's\n // window count. Both cached CT kernels run a fixed number of windows/rows with one point-add\n // each, so the add count is independent of scalar (constant-time).\n const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;\n return this.runCT(point, n, bits, transform);\n }\n /**\n * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.\n * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is\n * far cheaper to build for a single use. The point-operation sequence is independent of `n`:\n * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over\n * every table entry, and one addition (adds the identity when the window digit is 0 — never\n * skipped).\n *\n * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any\n * add), which holds for the Weierstrass/Edwards point types used here. The table is left in\n * projective form (no normalizeZ): normalizing this small a table costs more than the\n * mixed-add savings it would buy for a single multiply.\n * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape\n * (this path needs no fake accumulator — its op-count is already scalar-independent).\n */\n fixedWindowCT(point, n, bits) {\n const W = FW_WINDOW;\n const size = 1 << W;\n const mask = bitMask(W);\n // Flat table [O, point, 2*point, ..., (size-1)*point].\n const table = new Array(size);\n table[0] = this.ZERO;\n for (let i = 1; i < size; i++)\n table[i] = table[i - 1].add(point);\n // Horner MSB->LSB. windows*W >= bits and n < 2^bits, so every bit of n is consumed.\n const windows = Math.ceil(bits / W);\n let acc = this.ZERO;\n for (let window = windows - 1; window >= 0; window--) {\n // W doublings per window; skipped for the first (topmost) window, where acc is still the\n // identity. The skip is scalar-independent: it depends only on the loop index.\n if (window !== windows - 1)\n for (let d = 0; d < W; d++)\n acc = acc.double();\n const digit = Number((n >> BigInt(window * W)) & mask);\n // Data-oblivious select: touch every entry, same as wnafCachedCT.\n let sel = table[0];\n for (let i = 1; i < size; i++)\n sel = i === digit ? table[i] : sel;\n acc = acc.add(sel); // one add per window, even for digit 0\n }\n return { p: acc, f: acc };\n }\n shouldBlind(point, cofactor) {\n // No usable RNG (probed in the constructor): blinding is impossible, use the plain CT path.\n if (this.randomBytes === undefined)\n return false;\n if (cofactor === _1n)\n return true;\n if (point !== this.BASE)\n return false;\n if (this.baseCanBeBlinded === undefined)\n this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();\n return this.baseCanBeBlinded;\n }\n mulSecret(point, scalar, cofactor, transform) {\n return this.shouldBlind(point, cofactor)\n ? this.mulCTBlinded(point, scalar, transform)\n : this.mulCT(point, scalar, transform);\n }\n mulUnsafe(point, scalar, transform) {\n this.assertPoint(point);\n if (!isPosBig(scalar))\n throw new Error('invalid scalar');\n const W = getWindowSize(point);\n // W === 1 (un-precomputed): one-shot width-4 wNAF via {@link mulAddUnsafe} with L=1 —\n // a cached table would be thrown away after one use. `allowOversized` swaps the\n // `s < Fn.ORDER` check for mulAddUnsafe's `Fn.ORDER^4` DoS cap.\n //\n // Oversized scalar could happen when:\n // a) user passes large scalar on their own (rare)\n // b) `assertValidity()` calls `isTorsionFree()`, which multiplies point by `Fn.ORDER`\n if (W === 1 || scalar >= this.Point.Fn.ORDER)\n return mulAddUnsafe(this.Point, [point], [scalar], true);\n // Precomputed points reuse the CT kernel (fake accumulator discarded): with W=6 only\n // ~1/64 of window-adds are skippable, so a dedicated vartime kernel saved just ~6% on\n // this path while doubling the cached-table code surface.\n const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);\n return this.wnafCachedCT(precomputes, scalar).p;\n }\n // Remembers the window size used for precomputed wNAF multiplication of the given point\n // and drops any previously built tables. Usually only the base point is precomputed.\n // W=1 resets the point to the un-precomputed (table-less) paths.\n // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).\n setWindowSize(point, W) {\n this.assertPoint(point);\n validateW(W, this.bits);\n // Size against the widest table this W can produce: the blinded path adds BLIND_BITS.\n const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;\n validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);\n pointWindowSizes.set(point, W);\n this.wnafPrecomputes.delete(point);\n }\n // True when a window size is set: tables themselves are built lazily on first multiply.\n hasWindowSize(point) {\n return getWindowSize(point) !== 1;\n }\n}\n/**\n * Combined multi-scalar multiplication `Σ scalars[i]⋅points[i]` via interleaved width-4 wNAF\n * (Strauss–Shamir). Every input gets its own table of odd multiples `[1P, 3P, 5P, 7P]` and\n * signed-digit recoding, but all walks share one doubling chain, so total cost is\n * `~bits` doublings + `L⋅bits/5` additions instead of `L⋅bits` doublings for separate\n * multiplications. Intended for the 2-4 point shapes of signature verification\n * (`R = u1⋅G + u2⋅P`); use {@link pippenger} for larger batches.\n *\n * Not constant-time: only for public inputs. Scalars must satisfy `0 <= s < Fn.ORDER`;\n * fold negative signs into the points before calling.\n * @param c - Point constructor.\n * @param points - Array of curve points.\n * @param scalars - Array of non-negative scalars, same length as points.\n * @param allowOversized - Replace the `s < Fn.ORDER` scalar check with a `Fn.ORDER^4` DoS cap.\n * Off by default. For scalars that must NOT be reduced mod ORDER: torsion checks\n * (`Fn.ORDER⋅P ≟ O`) and cofactor-clearing multiples. Walk length grows with `bitLen(s)`.\n * @returns Combined multiplication result; identity for empty input.\n * @throws If the point set or scalar set is invalid. {@link Error}\n * @example\n * Combined multi-scalar multiplication via Strauss–Shamir.\n *\n * ```ts\n * import { mulAddUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const G = p256.Point.BASE;\n * const R = mulAddUnsafe(p256.Point, [G, G.double()], [2n, 3n]); // 2⋅G + 3⋅(2⋅G)\n * ```\n */\nexport function mulAddUnsafe(c, points, scalars, allowOversized = false) {\n validatePointCons(c);\n validateMSMPoints(points, c);\n abool(allowOversized, 'allowOversized');\n // Oversized cap is ORDER^4: hard bound to mitigate DoS, walk length grows with bitLen(s).\n validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n : undefined);\n if (points.length !== scalars.length)\n throw new Error('arrays of points and scalars must have equal length');\n const tables = points.map((p) => oddMultiples(p, 4));\n const digits = scalars.map((n) => wnafDigits(n, 4));\n return wnafWalk(c.ZERO, tables, digits);\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Point-operation count is scalar-independent (for same L), even when 1 point + scalar, or when\n * scalar = 0 — but bucket indices are scalar windows, so the memory-access pattern is\n * scalar-dependent: do not rely on this for secret scalars.\n *\n * A repaired LFG bucket-set variant from ePrint 2024/750 was benchmarked on BLS12-381 G1\n * against this implementation: ~1.4x faster at 2048 points and ~1.1-1.25x faster at\n * 4096-32768 points, at the cost of extra recoding and multiplier-table complexity.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger(c, points, scalars) {\n // 0 is accepted in scalars\n validatePointCons(c);\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength)\n throw new Error('arrays of points and scalars must have equal length');\n const zero = c.ZERO;\n // Without this, the window loop below would still run ~Fn.BITS doublings of ZERO.\n if (plength === 0)\n return zero;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12)\n windowSize = wbits - 3;\n else if (wbits > 4)\n windowSize = wbits - 2;\n else if (wbits > 0)\n windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0)\n for (let j = 0; j < windowSize; j++)\n sum = sum.double();\n }\n return sum;\n}\n/**\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...) over a FIXED set\n * of points: each point gets a one-time table of odd multiples\n * `[1P, 3P, ..., (2^(W−1)−1)P]`, and the returned closure evaluates MSMs against those\n * tables. All scalars share one doubling chain (Straus 1964) — one doubling per scalar bit\n * plus one signed table addition per nonzero width-W wNAF digit (density ~1/(W+1)) — the\n * \"interleaving\" method of Möller, \"Algorithms for multi-exponentiation\" (SAC 2001).\n *\n * Table memory is `L⋅2^(W−2)` points, capped at ~2 GiB. Prefer this over {@link pippenger}\n * when the same points are reused across many MSMs (fixed-base commitments etc.) and up to a\n * few hundred points; prefer pippenger for one-shot MSMs or thousands of points, where\n * bucketing beats per-point tables.\n *\n * Not constant-time (zero digits are skipped): public inputs only.\n * @param c - Curve Point constructor\n * @param points - array of L curve points, captured by the returned closure\n * @param windowSize - window width W in bits, from 2 to Fn.BITS; also capped so the\n * per-closure tables stay under ~2 GiB\n * @returns Function which multiplies points with scalars. The closure accepts at most\n * `points.length` scalars, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Interleaved wNAF multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { interleavedMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = interleavedMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function interleavedMSMUnsafe(c, points, windowSize) {\n validatePointCons(c);\n const fieldN = c.Fn;\n // Signed odd digits need at least width 2 (W=2 is plain NAF with a single-entry table).\n validateW(windowSize, fieldN.BITS, 2);\n validateMSMPoints(points, c);\n validateTableBytes(points.length * 2 ** (windowSize - 2), c.Fp.BYTES);\n const tables = points.map((p) => oddMultiples(p, 2 ** (windowSize - 2)));\n return (scalars) => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must not be larger than array of points');\n return wnafWalk(c.ZERO, tables, scalars.map((n) => wnafDigits(n, windowSize)));\n };\n}\nfunction createField(order, field, isLE) {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order)\n throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field;\n }\n else {\n return Field(order, { isLE });\n }\n}\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides. See {@link FpFn}:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {\n if (type !== 'weierstrass' && type !== 'edwards')\n throw new Error('expected curve type \"weierstrass\" or \"edwards\"');\n if (FpFnLE === undefined)\n FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object')\n throw new Error(`expected valid ${type} CURVE object`);\n // Validate before reading Fp/Fn so explicit null fails with an options-object error.\n validateObject(curveOpts);\n for (const p of ['p', 'n', 'h']) {\n const val = CURVE[p];\n if (!(isPosBig(val) && val !== _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b];\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn };\n}\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(randomSecretKey, getPublicKey) {\n return function keygen(seed) {\n const secretKey = randomSecretKey(seed);\n return { secretKey, publicKey: getPublicKey(secretKey) };\n };\n}\n","/**\n * 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, ScalarMultiplier, validatePointCons, } from \"./curve.js\";\nimport { FpLegendre } 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), _4n = /* @__PURE__ */ BigInt(4), _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=6\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 validateObject(extraOpts, {}, {}, '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 // The unified add-2008-hwcd formulas (see EdwardsPoint.add/double) are complete —\n // exception-free for every input pair — only when a is a square and d a non-square in Fp\n // (Bernstein–Birkner–Joye–Lange–Peters, \"Twisted Edwards curves\", thm 3.3). The constant-time\n // kernels in curve.ts assume completeness, so an incomplete curve could silently produce\n // wrong results on exceptional inputs. Fail construction instead.\n if (FpLegendre(Fp, CURVE.a) !== 1)\n throw new Error('edwards: CURVE.a must be a square in Fp for complete addition formulas');\n if (FpLegendre(Fp, CURVE.d) !== -1)\n throw new Error('edwards: CURVE.d must be a non-square in Fp for complete addition formulas');\n validateObject(opts, {}, { uvRatio: 'function', randomBytes: 'function' });\n const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes;\n // Coordinate and ZIP-215 bounds follow the base-field byte container, not scalar bytes.\n const MASK = _2n << (BigInt(Fp.BYTES * 8) - _1n);\n function isOdd(n) {\n if (!Fp.isOdd)\n throw new Error('Field does not have .isOdd()');\n return Fp.isOdd(n);\n }\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 // Multiplication by param `a` sits on the double() / add() hot paths. For the common twists\n // a=-1 (ed25519, jubjub) and a=1 (ed448) the full field multiplication is replaced with\n // negation / identity. Selection depends only on public curve constants.\n const mulA = Fp.eql(CURVE.a, Fp.neg(Fp.ONE)) ? (x) => Fp.neg(x)\n : Fp.eql(CURVE.a, Fp.ONE) ? (x) => x\n : (x) => Fp.mul(CURVE.a, x); // prettier-ignore\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 static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE, Fp.mul(CURVE.Gx, CURVE.Gy));\n static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ONE, Fp.ZERO);\n static Fp = Fp;\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, Fp.ONE, Fp.mul(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 = Fp.sqr(y); // denominator is always non-0 mod p.\n const u = Fp.sub(y2, Fp.ONE); // u = y² - 1\n const v = Fp.sub(Fp.mulN(d, y2), a); // v = d y² - a.\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 = isOdd(x); // 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 && Fp.is0(x) && 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 = Fp.neg(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 = 6, isLazy = true) {\n wnaf.setWindowSize(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 = Fp.sqr(X); // X²\n const Y2 = Fp.sqr(Y); // Y²\n const Z2 = Fp.sqr(Z); // Z²\n const Z4 = Fp.sqr(Z2); // Z⁴\n const aX2 = Fp.mul(X2, a); // aX²\n const left = Fp.mul(Fp.add(aX2, Y2), Z2); // (aX² + Y²)Z²\n const right = Fp.add(Z4, Fp.mul(d, Fp.mul(X2, Y2))); // Z⁴ + dX²Y²\n if (!Fp.eql(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 = Fp.mul(X, Y);\n const ZT = Fp.mul(Z, T);\n if (!Fp.eql(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 = Fp.mul(X1, Z2);\n const X2Z1 = Fp.mul(X2, Z1);\n const Y1Z2 = Fp.mul(Y1, Z2);\n const Y2Z1 = Fp.mul(Y2, Z1);\n return Fp.eql(X1Z2, X2Z1) && Fp.eql(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(Fp.neg(this.X), this.Y, this.Z, Fp.neg(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 { X: X1, Y: Y1, Z: Z1 } = this;\n const A = Fp.sqr(X1); // A = X12\n const B = Fp.sqr(Y1); // B = Y12\n const C = Fp.mul(Fp.sqr(Z1), _2n); // C = 2*Z12\n const D = mulA(A); // D = a*A\n const x1y1 = Fp.addN(X1, Y1);\n const E = Fp.sub(Fp.subN(Fp.sqr(x1y1), A), B); // E = (X1+Y1)2-A-B\n const G = Fp.addN(D, B); // G = D+B\n const F = Fp.subN(G, C); // F = G-C\n const H = Fp.subN(D, B); // H = D-B\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(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 { 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 = Fp.mul(X1, X2); // A = X1*X2\n const B = Fp.mul(Y1, Y2); // B = Y1*Y2\n const C = Fp.mul(Fp.mulN(T1, d), T2); // C = T1*d*T2\n const D = Fp.mul(Z1, Z2); // D = Z1*Z2\n // E = (X1+Y1)*(X2+Y2)-A-B\n const E = Fp.sub(Fp.subN(Fp.mulN(Fp.addN(X1, Y1), Fp.addN(X2, Y2)), A), B);\n const F = Fp.subN(D, C); // F = D-C\n const G = Fp.addN(D, C); // G = D+C\n const H = Fp.sub(B, mulA(A)); // H = B-a*A\n const X3 = Fp.mul(E, F); // X3 = E*F\n const Y3 = Fp.mul(G, H); // Y3 = G*H\n const T3 = Fp.mul(E, H); // T3 = E*H\n const Z3 = Fp.mul(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.mulSecret(this, scalar, cofactor, normalize);\n return normalize([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.mulUnsafe(this, scalar, normalize);\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.mulUnsafe(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 if (iz != null && typeof iz !== 'bigint')\n throw new TypeError('\"invertedZ\" expected bigint, got type=' + typeof iz);\n const { X, Y, Z } = p;\n const is0 = p.is0();\n if (iz == null)\n iz = is0 ? Fp.create(_8n) : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ONE };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x, y };\n }\n clearCofactor() {\n if (cofactor === _1n)\n return this;\n // 2.8-3.8x speed-up vs naive\n if (cofactor === _2n)\n return this.double();\n if (cofactor === _4n)\n return this.double().double();\n if (cofactor === _8n)\n return this.double().double().double();\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] |= isOdd(x) ? 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 // 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 const normalize = (points) => normalizeZ(Point, points);\n const wnaf = new ScalarMultiplier(Point, randomBytes);\n // Enable W=6 wNAF precomputes. Slows down first publicKey computation.\n // Disable for tiny toy curves, with scalar fields < 6 bits.\n if (wnaf.bits >= 6)\n Point.BASE.precompute(6);\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n/**\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 validatePointCons(Point);\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 toMontgomery: 'function',\n toMontgomerySecret: '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 toMontgomery = opts.toMontgomery;\n const toMontgomerySecret = opts.toMontgomerySecret;\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 validateObject(options, {}, {}, 'options');\n // Snapshot once: nonce and challenge must use the same invocation-time message bytes.\n msg = copyBytes(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 // Validate before destructuring so explicit null follows the standard options error.\n validateObject(options);\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 /** Converts an Edwards public key to a companion Montgomery public key. */\n toMontgomery(publicKey) {\n if (toMontgomery === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomery(Point.fromBytes(publicKey));\n },\n toMontgomerySecret(secretKey) {\n if (toMontgomerySecret === undefined)\n throw new Error('Montgomery conversion is not supported for this curve');\n return toMontgomerySecret(secretKey);\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","/**\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)();\nfunction toMontgomery(point) {\n // Birational map from Ed25519 to Curve25519 / X25519:\n // (u, v) = ((1 + y) / (1 - y), sqrt(-486664) * u / x)\n // (x, y) = (sqrt(-486664) * u / v, (u - 1) / (u + 1))\n const { y } = point;\n return Fp.toBytes(Fp.div(_1n + y, _1n - y));\n}\nfunction toMontgomerySecret(secretKey) {\n const size = ed25519_Point.Fp.BYTES;\n abytes(secretKey, size);\n return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);\n}\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, toMontgomery, toMontgomerySecret, 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 alicePublic = x25519.getPublicKey(alice.secretKey);\n * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey);\n * ```\n */\nexport const x25519 = /* @__PURE__ */ (() => {\n const P = ed25519_CURVE_p;\n const 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 return montgomery({\n P,\n type: 'x25519',\n powPminus2,\n adjustScalarBytes,\n // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached\n // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.\n // Same construction as libsodium's crypto_scalarmult_curve25519_base.\n scalarMultBase: (k) => {\n // Clamped k (≈2^254) exceeds n, but B has prime order n, so [k]B == [k mod n]B.\n const kn = mod(k, ed25519_Point.Fn.ORDER);\n // k ≡ 0 (mod n): [k]B is the point at infinity, whose u is 0 in the x-only ladder;\n // returning 0 makes montgomery() reject it exactly like the ladder path.\n if (kn === _0n)\n return _0n;\n const p = ed25519_Point.BASE.multiply(kn);\n // Z-Y == 0 only at the identity, which kn != 0 excludes.\n return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);\n },\n });\n})();\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards\n// map constant below, so use the even root explicitly.\n// 1. c1 = (q + 3) / 8 # Integer arithmetic\nconst ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)();\nconst ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1\nconst ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1)\nconst ELL2_J = /* @__PURE__ */ BigInt(486662);\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 // 4. c4 = (q - 5) / 8: tv2^c4 below reuses the ed25519_pow_2_252_3 addition chain,\n // whose pow_p_5_8 output is exactly x^((p-5)/8).\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 = ed25519_pow_2_252_3(tv2).pow_p_5_8; // 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 r = Fp.mul(Fp.mulN(SQRT_M1, r0), r0); // 1\n const Ns = Fp.mul(Fp.addN(r, _1n), ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = Fp.mul(Fp.subN(c, Fp.mulN(d, r)), Fp.add(r, d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = Fp.mul(s, r0); // 6\n if (!Fp.isOdd(s_))\n s_ = Fp.neg(s_);\n if (!Ns_D_is_sq)\n s = s_; // 7\n if (!Ns_D_is_sq)\n c = r; // 8\n const Nt = Fp.sub(Fp.mulN(Fp.mulN(c, Fp.subN(r, _1n)), D_MINUS_ONE_SQ), D); // 9\n const s2 = Fp.sqrN(s);\n const W0 = Fp.mul(Fp.addN(s, s), D); // 10\n const W1 = Fp.mul(Nt, SQRT_AD_MINUS_ONE); // 11\n const W2 = Fp.sub(_1n, s2); // 12\n const W3 = Fp.add(_1n, s2); // 13\n return new ed25519_Point(Fp.mul(W0, W3), Fp.mul(W2, W1), Fp.mul(W1, W3), Fp.mul(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 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) || Fp.isOdd(s))\n throw new Error('invalid ristretto255 encoding 1');\n const s2 = Fp.sqr(s);\n const u1 = Fp.add(_1n, Fp.mulN(a, s2)); // 4 (a is -1)\n const u2 = Fp.sub(_1n, Fp.mulN(a, s2)); // 5\n const u1_2 = Fp.sqr(u1);\n const u2_2 = Fp.sqr(u2);\n const v = Fp.sub(Fp.mulN(Fp.mulN(a, d), u1_2), u2_2); // 6\n const { isValid, value: I } = invertSqrt(Fp.mul(v, u2_2)); // 7\n const Dx = Fp.mul(I, u2); // 8\n const Dy = Fp.mul(Fp.mulN(I, Dx), v); // 9\n let x = Fp.mul(Fp.addN(s, s), Dx); // 10\n if (Fp.isOdd(x))\n x = Fp.neg(x); // 10\n const y = Fp.mul(u1, Dy); // 11\n const t = Fp.mul(x, y); // 12\n if (!isValid || Fp.isOdd(t) || Fp.is0(y))\n throw new Error('invalid ristretto255 encoding 2');\n return new _RistrettoPoint(new ed25519_Point(x, y, Fp.ONE, 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 u1 = Fp.mul(Fp.add(Z, Y), Fp.sub(Z, Y)); // 1\n const u2 = Fp.mul(X, Y); // 2\n // Square root always exists\n const u2sq = Fp.sqr(u2);\n const { value: invsqrt } = invertSqrt(Fp.mul(u1, u2sq)); // 3\n const D1 = Fp.mul(invsqrt, u1); // 4\n const D2 = Fp.mul(invsqrt, u2); // 5\n const zInv = Fp.mul(Fp.mulN(D1, D2), T); // 6\n let D; // 7\n if (Fp.isOdd(Fp.mul(T, zInv))) {\n let _x = Fp.mul(Y, SQRT_M1);\n let _y = Fp.mul(X, SQRT_M1);\n X = _x;\n Y = _y;\n D = Fp.mul(D1, INVSQRT_A_MINUS_D);\n }\n else {\n D = D2; // 8\n }\n if (Fp.isOdd(Fp.mul(X, zInv)))\n Y = Fp.neg(Y); // 9\n let s = Fp.mul(Fp.subN(Z, Y), D); // 10 (check footer's note, no sqrt(-a))\n if (Fp.isOdd(s))\n s = Fp.neg(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 // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = Fp.eql(Fp.mul(X1, Y2), Fp.mul(Y1, X2));\n const two = Fp.eql(Fp.mul(Y1, Y2), Fp.mul(X1, X2));\n return one || two;\n }\n is0() {\n return this.equals(_RistrettoPoint.ZERO);\n }\n}\n/** Prime-order Ristretto255 group bundle. */\nexport const ristretto255 = /* @__PURE__ */ (() => {\n Object.freeze(_RistrettoPoint.BASE);\n Object.freeze(_RistrettoPoint.ZERO);\n Object.freeze(_RistrettoPoint.prototype);\n Object.freeze(_RistrettoPoint);\n return Object.freeze({ Point: _RistrettoPoint });\n})();\n/**\n * Hashing to ristretto255 points / field. RFC 9380 methods.\n * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496\n * §4.3.4 element-derivation building block, and `hashToScalar()` is a\n * library-specific helper for OPRF-style use.\n * @example\n * Hash one message onto ristretto255.\n *\n * ```ts\n * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const ristretto255_hasher = \n/* @__PURE__ */ 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) {\n const DST = options?.DST === undefined ? _DST_scalar : options.DST;\n const xmd = expand_message_xmd(msg, 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","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"],"ignoreList":[2,3,4,5,6,7,8,9,10],"mappings":";;AAAA,IAAa+C,IAAb,cAAoC,MAAM;CACxC,YAAY,GAAiB,GAAwB;EAEnD,AADA,MAAMC,GAASC,CAAO,GACtB,KAAK,OAAO;CACd;AACF,GAEaC,IAAb,cAAiCH,EAAe;CAC9C;CACA;CAEA,YAAY,GAAY,GAAuB;EAI7C,AAHA,MAAM,2BAA2BI,EAAc,OAAOC,EAAG,EAAE,GAC3D,KAAK,OAAO,eACZ,KAAK,KAAKA,GACV,KAAK,gBAAgBD;CACvB;AACF,GAEaE,IAAb,cAAyCN,EAAe;CACtD;CAEA,YAAY,GAAiB;EAG3B,AAFA,MAAM,oBAAoBO,GAAS,GACnC,KAAK,OAAO,uBACZ,KAAK,UAAUA;CACjB;AACF,GAEaC,IAAb,cAA2CR,EAAe;CACxD,cAAc;EAEZ,AADA,MAAM,iCAAiC,GACvC,KAAK,OAAO;CACd;AACF,GAEaS,IAAb,cAAyCT,EAAe;CACtD,cAAc;EAEZ,AADA,MAAM,kBAAkB,GACxB,KAAK,OAAO;CACd;AACF,GAEaU,IAAb,cAAgDV,EAAe;CAC7D,cAAc;EAEZ,AADA,MAAM,yBAAyB,GAC/B,KAAK,OAAO;CACd;AACF,GAEaW,IAAb,cAAuCX,EAAe;CACpD,YAAY,GAAiB,GAAwB;EAEnD,AADA,MAAMC,GAASC,CAAO,GACtB,KAAK,OAAO;CACd;AACF,GAEaU,IAAb,cAA8CZ,EAAe;CAC3D,cAAc;EAEZ,AADA,MAAM,gDAAgD,GACtD,KAAK,OAAO;CACd;AACF,GAEaa,IAAb,cAAqCb,EAAe;CAClD,YAAY,GAAiB,GAAwB;EAEnD,AADA,MAAMC,GAASC,CAAO,GACtB,KAAK,OAAO;CACd;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