diff --git a/build-pq-bundle.js b/build-pq-bundle.js deleted file mode 100644 index 798c84a..0000000 --- a/build-pq-bundle.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Build script for the post-quantum crypto bundle. - * Bundles pq-crypto.mjs and all its dependencies into a single - * ESM file that can be loaded directly in the browser. - * - * Usage: node build-pq-bundle.js - */ - -const esbuild = require('esbuild'); -const path = require('path'); - -async function build() { - console.log('๐Ÿ”ง Building PQ crypto bundle...'); - - await esbuild.build({ - entryPoints: ['www/js/pq-crypto.mjs'], - bundle: true, - format: 'esm', - target: ['es2020'], - outfile: 'www/pq-crypto.bundle.js', - sourcemap: true, - minify: false, // keep readable for demo - logLevel: 'info', - // Pure JS โ€” no WASM files to handle - define: { - 'process.env.NODE_ENV': '"production"' - } - }); - - console.log('โœ… PQ crypto bundle built: www/pq-crypto.bundle.js'); -} - -build().catch(err => { - console.error('โŒ Build failed:', err); - process.exit(1); -}); diff --git a/www/js/pq-crypto.mjs b/www/js/pq-crypto.mjs deleted file mode 100644 index 3c20bca..0000000 --- a/www/js/pq-crypto.mjs +++ /dev/null @@ -1,351 +0,0 @@ -/** - * Post-Quantum Crypto Module for Nostr - * - * Provides: - * - BIP39 seed phrase generation - * - NIP-06 key derivation (secp256k1 from seed) - * - PQ key derivation from seed (ML-DSA-65, SLH-DSA-128s, ML-KEM-768) - * - PQ signing (ML-DSA, SLH-DSA) - * - NIP-QR event construction - * - * Uses @noble/post-quantum (pure JS, no WASM needed) - */ - -import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; -import { wordlist } from '@scure/bip39/wordlists/english.js'; -import { HDKey } from '@scure/bip32'; -import { hkdf } from '@noble/hashes/hkdf.js'; -import { sha256 as sha256Hash, sha512 as sha512Hash } from '@noble/hashes/sha2.js'; -import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js'; -import { slh_dsa_sha2_128s } from '@noble/post-quantum/slh-dsa.js'; -import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; - -// ============================================================================ -// BIP39 SEED PHRASE -// ============================================================================ - -/** - * Generate a new 12-word BIP39 mnemonic. - * @returns {string} 12-word seed phrase - */ -export function generateSeedPhrase() { - return generateMnemonic(wordlist, 128); // 128 bits = 12 words -} - -/** - * Convert a mnemonic to a 64-byte BIP39 seed (PBKDF2-HMAC-SHA512). - * @param {string} mnemonic - 12/24 word seed phrase - * @param {string} [passphrase=''] - optional BIP39 passphrase - * @returns {Uint8Array} 64-byte seed - */ -export function mnemonicToSeed(mnemonic, passphrase = '') { - if (!validateMnemonic(mnemonic, wordlist)) { - throw new Error('Invalid mnemonic'); - } - return mnemonicToSeedSync(mnemonic, passphrase); -} - -/** - * Validate a BIP39 mnemonic. - * @param {string} mnemonic - * @returns {boolean} - */ -export function isValidMnemonic(mnemonic) { - return validateMnemonic(mnemonic, wordlist); -} - -// ============================================================================ -// NIP-06 KEY DERIVATION (secp256k1 from seed) -// ============================================================================ - -/** - * Derive a secp256k1 keypair from a BIP39 seed using NIP-06. - * Path: m/44'/1237'/0'/0/0 - * - * @param {Uint8Array} seed - 64-byte BIP39 seed - * @param {number} [accountIndex=0] - account index - * @returns {{privateKey: Uint8Array, publicKey: Uint8Array}} secp256k1 keypair - */ -export function deriveSecp256k1FromSeed(seed, accountIndex = 0) { - const hdKey = HDKey.fromMasterSeed(seed); - const path = `m/44'/1237'/${accountIndex}'/0/0`; - const child = hdKey.derive(path); - if (!child.privateKey) { - throw new Error('Failed to derive private key'); - } - return { - privateKey: child.privateKey, - publicKey: child.publicKey - }; -} - -// ============================================================================ -// PQ KEY DERIVATION FROM SEED -// ============================================================================ - -/** - * Derive PQ key seeds from a BIP39 seed using HKDF. - * Each algorithm gets a unique label so keys are independent. - * - * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed - * @param {string} label - algorithm label (e.g. 'nostr-pq-ml-dsa-65') - * @param {number} length - output length in bytes - * @returns {Uint8Array} deterministic seed for PQ keygen - */ -function derivePQSeed(bip39Seed, label, length) { - const info = new TextEncoder().encode(label); - return hkdf(sha512Hash, bip39Seed, undefined, info, length); -} - -/** - * Derive all PQ keypairs from a BIP39 seed. - * - * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed - * @returns {{ - * mlDsa: {publicKey: Uint8Array, secretKey: Uint8Array}, - * slhDsa: {publicKey: Uint8Array, secretKey: Uint8Array}, - * mlKem: {publicKey: Uint8Array, secretKey: Uint8Array} - * }} - */ -export function derivePQKeysFromSeed(bip39Seed) { - // ML-DSA-65 needs 32-byte seed - const mlDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-dsa-65', 32); - const mlDsa = ml_dsa65.keygen(mlDsaSeed); - - // SLH-DSA-128s needs 48-byte seed (3 * 16 for sk seed, pk seed, etc.) - const slhDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-slh-dsa-128s', 48); - const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed); - - // ML-KEM-768 needs 64-byte seed - const mlKemSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-kem-768', 64); - const mlKem = ml_kem768.keygen(mlKemSeed); - - return { mlDsa, slhDsa, mlKem }; -} - -// ============================================================================ -// PQ SIGNING -// ============================================================================ - -/** - * Sign a message with ML-DSA-65. - * @param {Uint8Array} message - * @param {Uint8Array} secretKey - * @returns {Uint8Array} signature - */ -export function signWithMLDSA(message, secretKey) { - return ml_dsa65.sign(message, secretKey); -} - -/** - * Verify an ML-DSA-65 signature. - * @param {Uint8Array} signature - * @param {Uint8Array} message - * @param {Uint8Array} publicKey - * @returns {boolean} - */ -export function verifyMLDSA(signature, message, publicKey) { - return ml_dsa65.verify(signature, message, publicKey); -} - -/** - * Sign a message with SLH-DSA-128s. - * @param {Uint8Array} message - * @param {Uint8Array} secretKey - * @returns {Uint8Array} signature - */ -export function signWithSLHDSA(message, secretKey) { - return slh_dsa_sha2_128s.sign(message, secretKey); -} - -/** - * Verify an SLH-DSA-128s signature. - * @param {Uint8Array} signature - * @param {Uint8Array} message - * @param {Uint8Array} publicKey - * @returns {boolean} - */ -export function verifySLHDSA(signature, message, publicKey) { - return slh_dsa_sha2_128s.verify(signature, message, publicKey); -} - -// ============================================================================ -// UTILITIES -// ============================================================================ - -/** - * Convert Uint8Array to base64 string. - * @param {Uint8Array} bytes - * @returns {string} - */ -export function bytesToBase64(bytes) { - let binary = ''; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} - -/** - * Convert base64 string to Uint8Array. - * @param {string} base64 - * @returns {Uint8Array} - */ -export function base64ToBytes(base64) { - const binary = atob(base64); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes; -} - -/** - * Convert Uint8Array to hex string. - * @param {Uint8Array} bytes - * @returns {string} - */ -export function bytesToHex(bytes) { - return Array.from(bytes) - .map(b => b.toString(16).padStart(2, '0')) - .join(''); -} - -/** - * Convert hex string to Uint8Array. - * @param {string} hex - * @returns {Uint8Array} - */ -export function hexToBytes(hex) { - const bytes = new Uint8Array(hex.length / 2); - for (let i = 0; i < hex.length; i += 2) { - bytes[i / 2] = parseInt(hex.substr(i, 2), 16); - } - return bytes; -} - -// ============================================================================ -// NIP-QR EVENT CONSTRUCTION -// ============================================================================ - -/** - * Build the NIP-QR event content (the JSON that goes in the event's content field). - * - * The content contains: - * - A link statement - * - All PQ public keys - * - PQ signatures over the statement - * - The ML-KEM public key (no signature โ€” KEM can't sign) - * - * @param {string} npub - The user's Nostr npub (hex pubkey) - * @param {string} successorNpub - The successor's hex pubkey (for Path B), or null for Path A - * @param {{mlDsa: *, slhDsa: *, mlKem: *}} pqKeys - PQ keypairs - * @returns {{statement: string, content: object, statementBytes: Uint8Array}} - */ -export function buildNIPQRContent(npub, successorNpub, pqKeys) { - let statement; - if (successorNpub) { - // Path B: migration from old nsec to seed-derived key - statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`; - } else { - // Path A: direct link (identity already seed-derived) - statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`; - } - - const statementBytes = new TextEncoder().encode(statement); - - // Sign the statement with each PQ signature scheme - const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey); - const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey); - - const content = { - statement, - pq_keys: [ - { - algorithm: 'ml-dsa-65', - public_key: bytesToBase64(pqKeys.mlDsa.publicKey), - signature: bytesToBase64(mlDsaSig) - }, - { - algorithm: 'slh-dsa-128s', - public_key: bytesToBase64(pqKeys.slhDsa.publicKey), - signature: bytesToBase64(slhDsaSig) - }, - { - algorithm: 'ml-kem-768', - public_key: bytesToBase64(pqKeys.mlKem.publicKey), - note: 'KEM key for encryption; ownership asserted by secp256k1 signature over this content' - } - ] - }; - - // If Path B, include successor info - if (successorNpub) { - content.successor_pubkey = successorNpub; - } - - return { statement, content, statementBytes }; -} - -/** - * Verify a NIP-QR event's PQ signatures. - * @param {object} content - The parsed content object - * @returns {{valid: boolean, results: Array}} verification results - */ -export function verifyNIPQRContent(content) { - const results = []; - - for (const keyEntry of content.pq_keys) { - if (keyEntry.algorithm === 'ml-kem-768') { - // KEM can't sign โ€” skip verification - results.push({ algorithm: keyEntry.algorithm, valid: true, note: 'KEM (no signature to verify)' }); - continue; - } - - const pubKey = base64ToBytes(keyEntry.public_key); - const sig = base64ToBytes(keyEntry.signature); - const msg = new TextEncoder().encode(content.statement); - - let valid = false; - if (keyEntry.algorithm === 'ml-dsa-65') { - valid = verifyMLDSA(sig, msg, pubKey); - } else if (keyEntry.algorithm === 'slh-dsa-128s') { - valid = verifySLHDSA(sig, msg, pubKey); - } - - results.push({ algorithm: keyEntry.algorithm, valid }); - } - - return { - valid: results.every(r => r.valid), - results - }; -} - -// ============================================================================ -// KEY SIZE INFO (for display) -// ============================================================================ - -export const PQ_KEY_INFO = { - 'ml-dsa-65': { - name: 'ML-DSA-65 (Dilithium)', - publicKeySize: 1952, - signatureSize: 3309, - fips: 'FIPS 204', - type: 'signature' - }, - 'slh-dsa-128s': { - name: 'SLH-DSA-128s (SPHINCS+)', - publicKeySize: 32, - signatureSize: 7856, - fips: 'FIPS 205', - type: 'signature' - }, - 'ml-kem-768': { - name: 'ML-KEM-768 (Kyber)', - publicKeySize: 1184, - ciphertextSize: 1088, - fips: 'FIPS 203', - type: 'kem' - } -}; diff --git a/www/js/version.json b/www/js/version.json index ee89121..eb1c786 100644 --- a/www/js/version.json +++ b/www/js/version.json @@ -1,5 +1,5 @@ { - "VERSION": "v0.7.94", - "VERSION_NUMBER": "0.7.94", - "BUILD_DATE": "2026-07-12T14:10:59.968Z" + "VERSION": "v0.7.95", + "VERSION_NUMBER": "0.7.95", + "BUILD_DATE": "2026-07-31T10:32:03.777Z" } diff --git a/www/post-quantum.html b/www/post-quantum.html deleted file mode 100644 index b4f5c7d..0000000 --- a/www/post-quantum.html +++ /dev/null @@ -1,1135 +0,0 @@ - - - - - - - Post-Quantum Nostr - - - - - - - - - - - - - - - -
- - -
-
-
-
๐Ÿ”’ Post-Quantum Nostr
-
-
-
- - -
-
- - -
-
๐Ÿ”’ Post-Quantum Nostr
-
Make your Nostr identity quantum-resistant
-
- Sign in with your Nostr signer to begin. Your npub won't change, your followers stay, - and your social graph is preserved. We'll generate a quantum-safe seed phrase and link - it to your current identity. -
- -
- - -
-
๐Ÿ”’ Post-Quantum Migration
-
Step 1 of 4: Overview
- -
- Connected as: -
- -
- This tool will: -
    -
  1. Generate a new seed phrase (your quantum-safe backup)
  2. -
  3. Derive post-quantum keys from that seed (ML-DSA, SLH-DSA, ML-KEM)
  4. -
  5. Sign a NIP-QR migration event linking your identity to the PQ keys
  6. -
  7. Publish the event to relays with an OpenTimestamps proof
  8. -
-
- -
- โš ๏ธ Important: Your seed phrase is generated and handled entirely in your browser. - It is never sent to any server. Write it down on paper โ€” it's your quantum-safe backup. -
- - -
- - -
-
- 2 - Your Quantum-Safe Seed Phrase -
- -
- We've generated a new 12-word seed phrase. This is your quantum-safe root of trust. - Write it down on paper. Never store it digitally. Never share it with anyone. -
- -
- -
- - -
- - - - -
- - -
-
- 3 - Deriving Post-Quantum Keys -
- -
- Deriving post-quantum keys from your seed phrase. All keys are generated - deterministically โ€” the same seed will always produce the same keys. -
- -
-
-
- -
-
-
โณ
-
-
ML-DSA-65 (Dilithium)
-
FIPS 204 ยท Lattice-based signature ยท 1952-byte pubkey
-
-
-
-
-
โณ
-
-
SLH-DSA-128s (SPHINCS+)
-
FIPS 205 ยท Hash-based signature ยท 32-byte pubkey
-
-
-
-
-
โณ
-
-
ML-KEM-768 (Kyber)
-
FIPS 203 ยท Lattice-based KEM ยท 1184-byte pubkey
-
-
-
-
- -
- - -
- - -
-
- 4 - Sign & Publish Migration Event -
- -
- We'll now create the NIP-QR migration event. This event links your current Nostr identity - to your post-quantum keys. Your signer will be asked to sign the event with your secp256k1 key. -
- -
- -
-
-
โณ
-
-
PQ signature: ML-DSA-65
-
Done in browser (WASM-free pure JS)
-
-
-
-
โณ
-
-
PQ signature: SLH-DSA-128s
-
Done in browser (WASM-free pure JS)
-
-
-
-
โณ
-
-
secp256k1 signature (NIP-01)
-
Requires approval from your signer
-
-
-
-
โณ
-
-
Publish to relays
-
Broadcast the NIP-QR event
-
-
-
- - - -
-
Event preview:
-
-
-
- - -
-
-
๐ŸŽ‰
-
Migration Complete!
-
- Your Nostr identity is now linked to post-quantum keys.

- What happened:
- โ€ข Your identity is linked to PQ keys (ML-DSA, SLH-DSA, ML-KEM)
- โ€ข The link is established pre-quantum via secp256k1 signature
- โ€ข PQ signatures prove key ownership even after secp256k1 is broken

- What to do now:
- โ€ข Keep your seed phrase safe โ€” it's your quantum-safe backup
- โ€ข PQ-aware clients will recognize your new keys automatically -
- -
- - -
-
- -
-
- - -
-
-
-
-
0 sats
-
- - -
-
-
-
-
-
-
AI
-
-
No saved providers yet.
-
-
-
-
ใƒชใƒฌใƒผ
-
Loading relays...
-
-
-
ใƒ–ใƒญใƒƒใ‚ตใƒ 
-
Loading blossom servers...
-
-
- v0.0.1 -
- - -
-
-
- - - - - - - - - diff --git a/www/pq-crypto.bundle.js b/www/pq-crypto.bundle.js deleted file mode 100644 index 65a7fc5..0000000 --- a/www/pq-crypto.bundle.js +++ /dev/null @@ -1,7454 +0,0 @@ -var __defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - -// node_modules/@noble/hashes/utils.js -function isBytes(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; -} -function anumber(n, title = "") { - if (typeof n !== "number") { - const prefix = title && `"${title}" `; - throw new TypeError(`${prefix}expected number, got ${typeof n}`); - } - if (!Number.isSafeInteger(n) || n < 0) { - const prefix = title && `"${title}" `; - throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); - } -} -function abytes(value, length, title = "") { - const bytes = isBytes(value); - const len = value?.length; - const needsLen = length !== void 0; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message); - throw new RangeError(message); - } - return value; -} -function ahash(h) { - if (typeof h !== "function" || typeof h.create !== "function") - throw new TypeError("Hash must wrapped by utils.createHasher"); - anumber(h.outputLen); - anumber(h.blockLen); - if (h.outputLen < 1) - throw new Error('"outputLen" must be >= 1'); - if (h.blockLen < 1) - throw new Error('"blockLen" must be >= 1'); -} -function aexists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput(out, instance) { - abytes(out, void 0, "digestInto() output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError('"digestInto() output" expected to be of length >=' + min); - } -} -function u32(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function clean(...arrays) { - for (let i = 0; i < arrays.length; i++) { - arrays[i].fill(0); - } -} -function createView(arr) { - return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -} -function rotr(word, shift) { - return word << 32 - shift | word >>> shift; -} -function rotl(word, shift) { - return word << shift | word >>> 32 - shift >>> 0; -} -var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -function byteSwap(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -} -function byteSwap32(arr) { - for (let i = 0; i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); - } - return arr; -} -var swap32IfBE = isLE ? (u) => u : byteSwap32; -var hasHexBuiltin = /* @__PURE__ */ (() => ( - // @ts-ignore - typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" -))(); -var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -function bytesToHex(bytes) { - abytes(bytes); - if (hasHexBuiltin) - return bytes.toHex(); - let hex = ""; - for (let i = 0; i < bytes.length; i++) { - hex += hexes[bytes[i]]; - } - return hex; -} -var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); - return; -} -function hexToBytes(hex) { - if (typeof hex !== "string") - throw new TypeError("hex string expected, got " + typeof hex); - if (hasHexBuiltin) { - try { - return Uint8Array.fromHex(hex); - } catch (error) { - if (error instanceof SyntaxError) - throw new RangeError(error.message); - throw error; - } - } - const hl = hex.length; - const al = hl / 2; - if (hl % 2) - throw new RangeError("hex string expected, got unpadded hex of length " + hl); - const array = new Uint8Array(al); - for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex.charCodeAt(hi)); - const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); - if (n1 === void 0 || n2 === void 0) { - const char = hex[hi] + hex[hi + 1]; - throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array[ai] = n1 * 16 + n2; - } - return array; -} -function utf8ToBytes(str) { - if (typeof str !== "string") - throw new TypeError("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); -} -function kdfInputToBytes(data, errorTitle = "") { - if (typeof data === "string") - return utf8ToBytes(data); - return abytes(data, void 0, errorTitle); -} -function concatBytes(...arrays) { - let sum = 0; - for (let i = 0; i < arrays.length; i++) { - const a = arrays[i]; - abytes(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad = 0; i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad); - pad += a.length; - } - return res; -} -function checkOpts(defaults, opts2) { - if (opts2 !== void 0 && {}.toString.call(opts2) !== "[object Object]") - throw new TypeError("options must be object or undefined"); - const merged = Object.assign(defaults, opts2); - return merged; -} -function createHasher(hashCons, info = {}) { - const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest(); - const tmp = hashCons(void 0); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.canXOF = tmp.canXOF; - hashC.create = (opts2) => hashCons(opts2); - Object.assign(hashC, info); - return Object.freeze(hashC); -} -function randomBytes(bytesLength = 32) { - anumber(bytesLength, "bytesLength"); - const cr = typeof globalThis === "object" ? globalThis.crypto : null; - if (typeof cr?.getRandomValues !== "function") - throw new Error("crypto.getRandomValues must be defined"); - if (bytesLength > 65536) - throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); - return cr.getRandomValues(new Uint8Array(bytesLength)); -} -var oidNist = (suffix) => ({ - // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. - // Larger suffix values would need base-128 OID encoding and a different length byte. - oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) -}); - -// node_modules/@noble/hashes/hmac.js -var _HMAC = class { - constructor(hash, key) { - __publicField(this, "oHash"); - __publicField(this, "iHash"); - __publicField(this, "blockLen"); - __publicField(this, "outputLen"); - __publicField(this, "canXOF", false); - __publicField(this, "finished", false); - __publicField(this, "destroyed", false); - ahash(hash); - abytes(key, void 0, "key"); - this.iHash = hash.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54; - this.iHash.update(pad); - this.oHash = hash.create(); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 54 ^ 92; - this.oHash.update(pad); - clean(pad); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const buf = out.subarray(0, this.outputLen); - this.iHash.digestInto(buf); - this.oHash.update(buf); - this.oHash.digestInto(buf); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - clone() { - return this._cloneInto(); - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -}; -var hmac = /* @__PURE__ */ (() => { - const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest()); - hmac_.create = (hash, key) => new _HMAC(hash, key); - return hmac_; -})(); - -// node_modules/@noble/hashes/pbkdf2.js -function pbkdf2Init(hash, _password, _salt, _opts) { - ahash(hash); - const opts2 = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c, dkLen, asyncTick } = opts2; - anumber(c, "c"); - anumber(dkLen, "dkLen"); - anumber(asyncTick, "asyncTick"); - if (c < 1) - throw new Error("iterations (c) must be >= 1"); - if (dkLen < 1) - throw new Error('"dkLen" must be >= 1'); - if (dkLen > (2 ** 32 - 1) * hash.outputLen) - throw new Error("derived key too long"); - const password = kdfInputToBytes(_password, "password"); - const salt = kdfInputToBytes(_salt, "salt"); - const DK = new Uint8Array(dkLen); - const PRF = hmac.create(hash, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; -} -function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - clean(u); - return DK; -} -function pbkdf2(hash, password, salt, opts2) { - const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts2); - let prfW; - const arr = new Uint8Array(4); - const view = createView(arr); - const u = new Uint8Array(PRF.outputLen); - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - for (let ui = 1; ui < c; ui++) { - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); -} - -// node_modules/@noble/hashes/_md.js -function Chi(a, b, c) { - return a & b ^ ~a & c; -} -function Maj(a, b, c) { - return a & b ^ a & c ^ b & c; -} -var HashMD = class { - constructor(blockLen, outputLen, padOffset, isLE2) { - __publicField(this, "blockLen"); - __publicField(this, "outputLen"); - __publicField(this, "canXOF", false); - __publicField(this, "padOffset"); - __publicField(this, "isLE"); - // For partial updates less than block size - __publicField(this, "buffer"); - __publicField(this, "view"); - __publicField(this, "finished", false); - __publicField(this, "length", 0); - __publicField(this, "pos", 0); - __publicField(this, "destroyed", false); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - aexists(this); - abytes(data); - const { view, buffer, blockLen } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer[pos++] = 128; - clean(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen must be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - clone() { - return this._cloneInto(); - } -}; -var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -var SHA512_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 4089235720, - 3144134277, - 2227873595, - 1013904242, - 4271175723, - 2773480762, - 1595750129, - 1359893119, - 2917565137, - 2600822924, - 725511199, - 528734635, - 4215389547, - 1541459225, - 327033209 -]); - -// node_modules/@noble/hashes/_u64.js -var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -var _32n = /* @__PURE__ */ BigInt(32); -function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(lst, le = false) { - const len = lst.length; - let Ah = new Uint32Array(len); - let Al = new Uint32Array(len); - for (let i = 0; i < len; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -var shrSH = (h, _l, s) => h >>> s; -var shrSL = (h, l, s) => h << 32 - s | l >>> s; -var rotrSH = (h, l, s) => h >>> s | l << 32 - s; -var rotrSL = (h, l, s) => h << 32 - s | l >>> s; -var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; -var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; -var rotlSH = (h, l, s) => h << s | l >>> 32 - s; -var rotlSL = (h, l, s) => l << s | h >>> 32 - s; -var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; -var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; -function add(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; -} -var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); -var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; -var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); -var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; -var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); -var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; - -// node_modules/@noble/hashes/sha2.js -var SHA256_K = /* @__PURE__ */ Uint32Array.from([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]); -var SHA256_W = /* @__PURE__ */ new Uint32Array(64); -var SHA2_32B = class extends HashMD { - constructor(outputLen) { - super(64, outputLen, 8, false); - } - get() { - const { A, B, C, D: D2, E, F: F3, G, H } = this; - return [A, B, C, D2, E, F3, G, H]; - } - // prettier-ignore - set(A, B, C, D2, E, F3, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D2 | 0; - this.E = E | 0; - this.F = F3 | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D: D2, E, F: F3, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F3, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F3; - F3 = E; - E = D2 + T1 | 0; - D2 = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D2 = D2 + this.D | 0; - E = E + this.E | 0; - F3 = F3 + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D2, E, F3, G, H); - } - roundClean() { - clean(SHA256_W); - } - destroy() { - this.destroyed = true; - this.set(0, 0, 0, 0, 0, 0, 0, 0); - clean(this.buffer); - } -}; -var _SHA256 = class extends SHA2_32B { - constructor() { - super(32); - // We cannot use array here since array allows indexing by variable - // which means optimizer/compiler cannot use registers. - __publicField(this, "A", SHA256_IV[0] | 0); - __publicField(this, "B", SHA256_IV[1] | 0); - __publicField(this, "C", SHA256_IV[2] | 0); - __publicField(this, "D", SHA256_IV[3] | 0); - __publicField(this, "E", SHA256_IV[4] | 0); - __publicField(this, "F", SHA256_IV[5] | 0); - __publicField(this, "G", SHA256_IV[6] | 0); - __publicField(this, "H", SHA256_IV[7] | 0); - } -}; -var K512 = /* @__PURE__ */ (() => split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" -].map((n) => BigInt(n))))(); -var SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); -var SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); -var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); -var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); -var SHA2_64B = class extends HashMD { - constructor(outputLen) { - super(128, outputLen, 16, false); - } - // prettier-ignore - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - // prettier-ignore - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); - } - for (let i = 16; i < 80; i++) { - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); - const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); - const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); - const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - for (let i = 0; i < 80; i++) { - const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); - const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); - const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = add3L(T1l, sigma0l, MAJl); - Ah = add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - clean(SHA512_W_H, SHA512_W_L); - } - destroy() { - this.destroyed = true; - clean(this.buffer); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } -}; -var _SHA512 = class extends SHA2_64B { - constructor() { - super(64); - __publicField(this, "Ah", SHA512_IV[0] | 0); - __publicField(this, "Al", SHA512_IV[1] | 0); - __publicField(this, "Bh", SHA512_IV[2] | 0); - __publicField(this, "Bl", SHA512_IV[3] | 0); - __publicField(this, "Ch", SHA512_IV[4] | 0); - __publicField(this, "Cl", SHA512_IV[5] | 0); - __publicField(this, "Dh", SHA512_IV[6] | 0); - __publicField(this, "Dl", SHA512_IV[7] | 0); - __publicField(this, "Eh", SHA512_IV[8] | 0); - __publicField(this, "El", SHA512_IV[9] | 0); - __publicField(this, "Fh", SHA512_IV[10] | 0); - __publicField(this, "Fl", SHA512_IV[11] | 0); - __publicField(this, "Gh", SHA512_IV[12] | 0); - __publicField(this, "Gl", SHA512_IV[13] | 0); - __publicField(this, "Hh", SHA512_IV[14] | 0); - __publicField(this, "Hl", SHA512_IV[15] | 0); - } -}; -var sha256 = /* @__PURE__ */ createHasher( - () => new _SHA256(), - /* @__PURE__ */ oidNist(1) -); -var sha512 = /* @__PURE__ */ createHasher( - () => new _SHA512(), - /* @__PURE__ */ oidNist(3) -); - -// node_modules/@scure/base/index.js -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; -} -function isArrayOf(isString, arr) { - if (!Array.isArray(arr)) - return false; - if (arr.length === 0) - return true; - if (isString) { - return arr.every((item) => typeof item === "string"); - } else { - return arr.every((item) => Number.isSafeInteger(item)); - } -} -function afn(input) { - if (typeof input !== "function") - throw new TypeError("function expected"); - return true; -} -function astr(label, input) { - if (typeof input !== "string") - throw new TypeError(`${label}: string expected`); - return true; -} -function anumber2(n) { - if (typeof n !== "number") - throw new TypeError(`number expected, got ${typeof n}`); - if (!Number.isSafeInteger(n)) - throw new RangeError(`invalid integer: ${n}`); -} -function aArr(input) { - if (!Array.isArray(input)) - throw new TypeError("array expected"); -} -function astrArr(label, input) { - if (!isArrayOf(true, input)) - throw new TypeError(`${label}: array of strings expected`); -} -function anumArr(label, input) { - if (!isArrayOf(false, input)) - throw new TypeError(`${label}: array of numbers expected`); -} -// @__NO_SIDE_EFFECTS__ -function chain(...args) { - const id2 = (a) => a; - const wrap = (a, b) => (c) => a(b(c)); - const encode = args.map((x) => x.encode).reduceRight(wrap, id2); - const decode = args.map((x) => x.decode).reduce(wrap, id2); - return { encode, decode }; -} -// @__NO_SIDE_EFFECTS__ -function alphabet(letters) { - const lettersA = typeof letters === "string" ? letters.split("") : letters; - const len = lettersA.length; - astrArr("alphabet", lettersA); - const indexes = new Map(lettersA.map((l, i) => [l, i])); - return { - encode: (digits) => { - aArr(digits); - return digits.map((i) => { - if (!Number.isSafeInteger(i) || i < 0 || i >= len) - throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`); - return lettersA[i]; - }); - }, - decode: (input) => { - aArr(input); - return input.map((letter) => { - astr("alphabet.decode", letter); - const i = indexes.get(letter); - if (i === void 0) - throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); - return i; - }); - } - }; -} -// @__NO_SIDE_EFFECTS__ -function join(separator = "") { - astr("join", separator); - return { - encode: (from) => { - astrArr("join.decode", from); - return from.join(separator); - }, - decode: (to) => { - astr("join.decode", to); - return to.split(separator); - } - }; -} -// @__NO_SIDE_EFFECTS__ -function padding(bits, chr = "=") { - anumber2(bits); - astr("padding", chr); - return { - encode(data) { - astrArr("padding.encode", data); - while (data.length * bits % 8) - data.push(chr); - return data; - }, - decode(input) { - astrArr("padding.decode", input); - let end = input.length; - if (end * bits % 8) - throw new Error("padding: invalid, string should have whole number of bytes"); - for (; end > 0 && input[end - 1] === chr; end--) { - const last = end - 1; - const byte = last * bits; - if (byte % 8 === 0) - throw new Error("padding: invalid, string has too much padding"); - } - return input.slice(0, end); - } - }; -} -function convertRadix(data, from, to) { - if (from < 2) - throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`); - if (to < 2) - throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`); - aArr(data); - if (!data.length) - return []; - let pos = 0; - const res = []; - const digits = Array.from(data, (d) => { - anumber2(d); - if (d < 0 || d >= from) - throw new Error(`invalid integer: ${d}`); - return d; - }); - const dlen = digits.length; - while (true) { - let carry = 0; - let done = true; - for (let i = pos; i < dlen; i++) { - const digit = digits[i]; - const fromCarry = from * carry; - const digitBase = fromCarry + digit; - if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) { - throw new Error("convertRadix: carry overflow"); - } - const div = digitBase / to; - carry = digitBase % to; - const rounded = Math.floor(div); - digits[i] = rounded; - if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) - throw new Error("convertRadix: carry overflow"); - if (!done) - continue; - else if (!rounded) - pos = i; - else - done = false; - } - res.push(carry); - if (done) - break; - } - for (let i = 0; i < data.length - 1 && data[i] === 0; i++) - res.push(0); - return res.reverse(); -} -var gcd = (a, b) => b === 0 ? a : gcd(b, a % b); -var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); -var powers = /* @__PURE__ */ (() => { - let res = []; - for (let i = 0; i < 40; i++) - res.push(2 ** i); - return res; -})(); -function convertRadix2(data, from, to, padding2) { - aArr(data); - if (from <= 0 || from > 32) - throw new RangeError(`convertRadix2: wrong from=${from}`); - if (to <= 0 || to > 32) - throw new RangeError(`convertRadix2: wrong to=${to}`); - if (/* @__PURE__ */ radix2carry(from, to) > 32) { - throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`); - } - let carry = 0; - let pos = 0; - const max = powers[from]; - const mask = powers[to] - 1; - const res = []; - for (const n of data) { - anumber2(n); - if (n >= max) - throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); - carry = carry << from | n; - if (pos + from > 32) - throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); - pos += from; - for (; pos >= to; pos -= to) - res.push((carry >> pos - to & mask) >>> 0); - const pow = powers[pos]; - if (pow === void 0) - throw new Error("invalid carry"); - carry &= pow - 1; - } - carry = carry << to - pos & mask; - if (!padding2 && pos >= from) - throw new Error("Excess padding"); - if (!padding2 && carry > 0) - throw new Error(`Non-zero padding: ${carry}`); - if (padding2 && pos > 0) - res.push(carry >>> 0); - return res; -} -// @__NO_SIDE_EFFECTS__ -function radix(num) { - anumber2(num); - const _256 = 2 ** 8; - return { - encode: (bytes) => { - if (!isBytes2(bytes)) - throw new TypeError("radix.encode input should be Uint8Array"); - return convertRadix(Array.from(bytes), _256, num); - }, - decode: (digits) => { - anumArr("radix.decode", digits); - return Uint8Array.from(convertRadix(digits, num, _256)); - } - }; -} -// @__NO_SIDE_EFFECTS__ -function radix2(bits, revPadding = false) { - anumber2(bits); - if (bits <= 0 || bits > 32) - throw new RangeError("radix2: bits should be in (0..32]"); - if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32) - throw new RangeError("radix2: carry overflow"); - return { - encode: (bytes) => { - if (!isBytes2(bytes)) - throw new TypeError("radix2.encode input should be Uint8Array"); - return convertRadix2(Array.from(bytes), 8, bits, !revPadding); - }, - decode: (digits) => { - anumArr("radix2.decode", digits); - return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); - } - }; -} -function checksum(len, fn) { - anumber2(len); - if (len <= 0) - throw new RangeError(`checksum length must be positive: ${len}`); - afn(fn); - const _fn = fn; - return { - encode(data) { - if (!isBytes2(data)) - throw new TypeError("checksum.encode: input should be Uint8Array"); - const sum = _fn(data).slice(0, len); - const res = new Uint8Array(data.length + len); - res.set(data); - res.set(sum, data.length); - return res; - }, - decode(data) { - if (!isBytes2(data)) - throw new TypeError("checksum.decode: input should be Uint8Array"); - const payload = data.slice(0, -len); - const oldChecksum = data.slice(-len); - const newChecksum = _fn(payload).slice(0, len); - for (let i = 0; i < len; i++) - if (newChecksum[i] !== oldChecksum[i]) - throw new Error("Invalid checksum"); - return payload; - } - }; -} -var utils = /* @__PURE__ */ Object.freeze({ - alphabet, - chain, - checksum, - convertRadix, - convertRadix2, - radix, - radix2, - join, - padding -}); -var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join("")); -var base58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")); -var createBase58check = (sha2562) => { - afn(sha2562); - const _sha256 = sha2562; - return /* @__PURE__ */ chain(checksum(4, (data) => _sha256(_sha256(data))), base58); -}; - -// node_modules/@scure/bip39/index.js -var isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093"; -function nfkd(str) { - if (typeof str !== "string") - throw new TypeError("invalid mnemonic type: " + typeof str); - return str.normalize("NFKD"); -} -function normalize(str) { - const norm = nfkd(str); - const words = norm.split(" "); - if (![12, 15, 18, 21, 24].includes(words.length)) - throw new Error("Invalid mnemonic"); - return { nfkd: norm, words }; -} -function aentropy(ent) { - abytes(ent); - if (![16, 20, 24, 28, 32].includes(ent.length)) - throw new RangeError("invalid entropy length"); -} -function generateMnemonic(wordlist2, strength = 128) { - anumber(strength); - if (strength % 32 !== 0 || strength > 256) - throw new RangeError("Invalid entropy"); - return entropyToMnemonic(randomBytes(strength / 8), wordlist2); -} -var calcChecksum = (entropy) => { - const bitsLeft = 8 - entropy.length / 4; - return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]); -}; -function getCoder(wordlist2) { - if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string") - throw new TypeError("Wordlist: expected array of 2048 strings"); - wordlist2.forEach((i) => { - if (typeof i !== "string") - throw new TypeError("wordlist: non-string element: " + i); - }); - return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2)); -} -function mnemonicToEntropy(mnemonic, wordlist2) { - const { words } = normalize(mnemonic); - const entropy = getCoder(wordlist2).decode(words); - aentropy(entropy); - return entropy; -} -function entropyToMnemonic(entropy, wordlist2) { - aentropy(entropy); - const words = getCoder(wordlist2).encode(entropy); - return words.join(isJapanese(wordlist2) ? "\u3000" : " "); -} -function validateMnemonic(mnemonic, wordlist2) { - try { - mnemonicToEntropy(mnemonic, wordlist2); - } catch (e) { - return false; - } - return true; -} -var psalt = (passphrase) => nfkd("mnemonic" + passphrase); -function mnemonicToSeedSync(mnemonic, passphrase = "") { - return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { - c: 2048, - dkLen: 64 - }); -} - -// node_modules/@scure/bip39/wordlists/english.js -var wordlist = /* @__PURE__ */ Object.freeze(`abandon -ability -able -about -above -absent -absorb -abstract -absurd -abuse -access -accident -account -accuse -achieve -acid -acoustic -acquire -across -act -action -actor -actress -actual -adapt -add -addict -address -adjust -admit -adult -advance -advice -aerobic -affair -afford -afraid -again -age -agent -agree -ahead -aim -air -airport -aisle -alarm -album -alcohol -alert -alien -all -alley -allow -almost -alone -alpha -already -also -alter -always -amateur -amazing -among -amount -amused -analyst -anchor -ancient -anger -angle -angry -animal -ankle -announce -annual -another -answer -antenna -antique -anxiety -any -apart -apology -appear -apple -approve -april -arch -arctic -area -arena -argue -arm -armed -armor -army -around -arrange -arrest -arrive -arrow -art -artefact -artist -artwork -ask -aspect -assault -asset -assist -assume -asthma -athlete -atom -attack -attend -attitude -attract -auction -audit -august -aunt -author -auto -autumn -average -avocado -avoid -awake -aware -away -awesome -awful -awkward -axis -baby -bachelor -bacon -badge -bag -balance -balcony -ball -bamboo -banana -banner -bar -barely -bargain -barrel -base -basic -basket -battle -beach -bean -beauty -because -become -beef -before -begin -behave -behind -believe -below -belt -bench -benefit -best -betray -better -between -beyond -bicycle -bid -bike -bind -biology -bird -birth -bitter -black -blade -blame -blanket -blast -bleak -bless -blind -blood -blossom -blouse -blue -blur -blush -board -boat -body -boil -bomb -bone -bonus -book -boost -border -boring -borrow -boss -bottom -bounce -box -boy -bracket -brain -brand -brass -brave -bread -breeze -brick -bridge -brief -bright -bring -brisk -broccoli -broken -bronze -broom -brother -brown -brush -bubble -buddy -budget -buffalo -build -bulb -bulk -bullet -bundle -bunker -burden -burger -burst -bus -business -busy -butter -buyer -buzz -cabbage -cabin -cable -cactus -cage -cake -call -calm -camera -camp -can -canal -cancel -candy -cannon -canoe -canvas -canyon -capable -capital -captain -car -carbon -card -cargo -carpet -carry -cart -case -cash -casino -castle -casual -cat -catalog -catch -category -cattle -caught -cause -caution -cave -ceiling -celery -cement -census -century -cereal -certain -chair -chalk -champion -change -chaos -chapter -charge -chase -chat -cheap -check -cheese -chef -cherry -chest -chicken -chief -child -chimney -choice -choose -chronic -chuckle -chunk -churn -cigar -cinnamon -circle -citizen -city -civil -claim -clap -clarify -claw -clay -clean -clerk -clever -click -client -cliff -climb -clinic -clip -clock -clog -close -cloth -cloud -clown -club -clump -cluster -clutch -coach -coast -coconut -code -coffee -coil -coin -collect -color -column -combine -come -comfort -comic -common -company -concert -conduct -confirm -congress -connect -consider -control -convince -cook -cool -copper -copy -coral -core -corn -correct -cost -cotton -couch -country -couple -course -cousin -cover -coyote -crack -cradle -craft -cram -crane -crash -crater -crawl -crazy -cream -credit -creek -crew -cricket -crime -crisp -critic -crop -cross -crouch -crowd -crucial -cruel -cruise -crumble -crunch -crush -cry -crystal -cube -culture -cup -cupboard -curious -current -curtain -curve -cushion -custom -cute -cycle -dad -damage -damp -dance -danger -daring -dash -daughter -dawn -day -deal -debate -debris -decade -december -decide -decline -decorate -decrease -deer -defense -define -defy -degree -delay -deliver -demand -demise -denial -dentist -deny -depart -depend -deposit -depth -deputy -derive -describe -desert -design -desk -despair -destroy -detail -detect -develop -device -devote -diagram -dial -diamond -diary -dice -diesel -diet -differ -digital -dignity -dilemma -dinner -dinosaur -direct -dirt -disagree -discover -disease -dish -dismiss -disorder -display -distance -divert -divide -divorce -dizzy -doctor -document -dog -doll -dolphin -domain -donate -donkey -donor -door -dose -double -dove -draft -dragon -drama -drastic -draw -dream -dress -drift -drill -drink -drip -drive -drop -drum -dry -duck -dumb -dune -during -dust -dutch -duty -dwarf -dynamic -eager -eagle -early -earn -earth -easily -east -easy -echo -ecology -economy -edge -edit -educate -effort -egg -eight -either -elbow -elder -electric -elegant -element -elephant -elevator -elite -else -embark -embody -embrace -emerge -emotion -employ -empower -empty -enable -enact -end -endless -endorse -enemy -energy -enforce -engage -engine -enhance -enjoy -enlist -enough -enrich -enroll -ensure -enter -entire -entry -envelope -episode -equal -equip -era -erase -erode -erosion -error -erupt -escape -essay -essence -estate -eternal -ethics -evidence -evil -evoke -evolve -exact -example -excess -exchange -excite -exclude -excuse -execute -exercise -exhaust -exhibit -exile -exist -exit -exotic -expand -expect -expire -explain -expose -express -extend -extra -eye -eyebrow -fabric -face -faculty -fade -faint -faith -fall -false -fame -family -famous -fan -fancy -fantasy -farm -fashion -fat -fatal -father -fatigue -fault -favorite -feature -february -federal -fee -feed -feel -female -fence -festival -fetch -fever -few -fiber -fiction -field -figure -file -film -filter -final -find -fine -finger -finish -fire -firm -first -fiscal -fish -fit -fitness -fix -flag -flame -flash -flat -flavor -flee -flight -flip -float -flock -floor -flower -fluid -flush -fly -foam -focus -fog -foil -fold -follow -food -foot -force -forest -forget -fork -fortune -forum -forward -fossil -foster -found -fox -fragile -frame -frequent -fresh -friend -fringe -frog -front -frost -frown -frozen -fruit -fuel -fun -funny -furnace -fury -future -gadget -gain -galaxy -gallery -game -gap -garage -garbage -garden -garlic -garment -gas -gasp -gate -gather -gauge -gaze -general -genius -genre -gentle -genuine -gesture -ghost -giant -gift -giggle -ginger -giraffe -girl -give -glad -glance -glare -glass -glide -glimpse -globe -gloom -glory -glove -glow -glue -goat -goddess -gold -good -goose -gorilla -gospel -gossip -govern -gown -grab -grace -grain -grant -grape -grass -gravity -great -green -grid -grief -grit -grocery -group -grow -grunt -guard -guess -guide -guilt -guitar -gun -gym -habit -hair -half -hammer -hamster -hand -happy -harbor -hard -harsh -harvest -hat -have -hawk -hazard -head -health -heart -heavy -hedgehog -height -hello -helmet -help -hen -hero -hidden -high -hill -hint -hip -hire -history -hobby -hockey -hold -hole -holiday -hollow -home -honey -hood -hope -horn -horror -horse -hospital -host -hotel -hour -hover -hub -huge -human -humble -humor -hundred -hungry -hunt -hurdle -hurry -hurt -husband -hybrid -ice -icon -idea -identify -idle -ignore -ill -illegal -illness -image -imitate -immense -immune -impact -impose -improve -impulse -inch -include -income -increase -index -indicate -indoor -industry -infant -inflict -inform -inhale -inherit -initial -inject -injury -inmate -inner -innocent -input -inquiry -insane -insect -inside -inspire -install -intact -interest -into -invest -invite -involve -iron -island -isolate -issue -item -ivory -jacket -jaguar -jar -jazz -jealous -jeans -jelly -jewel -job -join -joke -journey -joy -judge -juice -jump -jungle -junior -junk -just -kangaroo -keen -keep -ketchup -key -kick -kid -kidney -kind -kingdom -kiss -kit -kitchen -kite -kitten -kiwi -knee -knife -knock -know -lab -label -labor -ladder -lady -lake -lamp -language -laptop -large -later -latin -laugh -laundry -lava -law -lawn -lawsuit -layer -lazy -leader -leaf -learn -leave -lecture -left -leg -legal -legend -leisure -lemon -lend -length -lens -leopard -lesson -letter -level -liar -liberty -library -license -life -lift -light -like -limb -limit -link -lion -liquid -list -little -live -lizard -load -loan -lobster -local -lock -logic -lonely -long -loop -lottery -loud -lounge -love -loyal -lucky -luggage -lumber -lunar -lunch -luxury -lyrics -machine -mad -magic -magnet -maid -mail -main -major -make -mammal -man -manage -mandate -mango -mansion -manual -maple -marble -march -margin -marine -market -marriage -mask -mass -master -match -material -math -matrix -matter -maximum -maze -meadow -mean -measure -meat -mechanic -medal -media -melody -melt -member -memory -mention -menu -mercy -merge -merit -merry -mesh -message -metal -method -middle -midnight -milk -million -mimic -mind -minimum -minor -minute -miracle -mirror -misery -miss -mistake -mix -mixed -mixture -mobile -model -modify -mom -moment -monitor -monkey -monster -month -moon -moral -more -morning -mosquito -mother -motion -motor -mountain -mouse -move -movie -much -muffin -mule -multiply -muscle -museum -mushroom -music -must -mutual -myself -mystery -myth -naive -name -napkin -narrow -nasty -nation -nature -near -neck -need -negative -neglect -neither -nephew -nerve -nest -net -network -neutral -never -news -next -nice -night -noble -noise -nominee -noodle -normal -north -nose -notable -note -nothing -notice -novel -now -nuclear -number -nurse -nut -oak -obey -object -oblige -obscure -observe -obtain -obvious -occur -ocean -october -odor -off -offer -office -often -oil -okay -old -olive -olympic -omit -once -one -onion -online -only -open -opera -opinion -oppose -option -orange -orbit -orchard -order -ordinary -organ -orient -original -orphan -ostrich -other -outdoor -outer -output -outside -oval -oven -over -own -owner -oxygen -oyster -ozone -pact -paddle -page -pair -palace -palm -panda -panel -panic -panther -paper -parade -parent -park -parrot -party -pass -patch -path -patient -patrol -pattern -pause -pave -payment -peace -peanut -pear -peasant -pelican -pen -penalty -pencil -people -pepper -perfect -permit -person -pet -phone -photo -phrase -physical -piano -picnic -picture -piece -pig -pigeon -pill -pilot -pink -pioneer -pipe -pistol -pitch -pizza -place -planet -plastic -plate -play -please -pledge -pluck -plug -plunge -poem -poet -point -polar -pole -police -pond -pony -pool -popular -portion -position -possible -post -potato -pottery -poverty -powder -power -practice -praise -predict -prefer -prepare -present -pretty -prevent -price -pride -primary -print -priority -prison -private -prize -problem -process -produce -profit -program -project -promote -proof -property -prosper -protect -proud -provide -public -pudding -pull -pulp -pulse -pumpkin -punch -pupil -puppy -purchase -purity -purpose -purse -push -put -puzzle -pyramid -quality -quantum -quarter -question -quick -quit -quiz -quote -rabbit -raccoon -race -rack -radar -radio -rail -rain -raise -rally -ramp -ranch -random -range -rapid -rare -rate -rather -raven -raw -razor -ready -real -reason -rebel -rebuild -recall -receive -recipe -record -recycle -reduce -reflect -reform -refuse -region -regret -regular -reject -relax -release -relief -rely -remain -remember -remind -remove -render -renew -rent -reopen -repair -repeat -replace -report -require -rescue -resemble -resist -resource -response -result -retire -retreat -return -reunion -reveal -review -reward -rhythm -rib -ribbon -rice -rich -ride -ridge -rifle -right -rigid -ring -riot -ripple -risk -ritual -rival -river -road -roast -robot -robust -rocket -romance -roof -rookie -room -rose -rotate -rough -round -route -royal -rubber -rude -rug -rule -run -runway -rural -sad -saddle -sadness -safe -sail -salad -salmon -salon -salt -salute -same -sample -sand -satisfy -satoshi -sauce -sausage -save -say -scale -scan -scare -scatter -scene -scheme -school -science -scissors -scorpion -scout -scrap -screen -script -scrub -sea -search -season -seat -second -secret -section -security -seed -seek -segment -select -sell -seminar -senior -sense -sentence -series -service -session -settle -setup -seven -shadow -shaft -shallow -share -shed -shell -sheriff -shield -shift -shine -ship -shiver -shock -shoe -shoot -shop -short -shoulder -shove -shrimp -shrug -shuffle -shy -sibling -sick -side -siege -sight -sign -silent -silk -silly -silver -similar -simple -since -sing -siren -sister -situate -six -size -skate -sketch -ski -skill -skin -skirt -skull -slab -slam -sleep -slender -slice -slide -slight -slim -slogan -slot -slow -slush -small -smart -smile -smoke -smooth -snack -snake -snap -sniff -snow -soap -soccer -social -sock -soda -soft -solar -soldier -solid -solution -solve -someone -song -soon -sorry -sort -soul -sound -soup -source -south -space -spare -spatial -spawn -speak -special -speed -spell -spend -sphere -spice -spider -spike -spin -spirit -split -spoil -sponsor -spoon -sport -spot -spray -spread -spring -spy -square -squeeze -squirrel -stable -stadium -staff -stage -stairs -stamp -stand -start -state -stay -steak -steel -stem -step -stereo -stick -still -sting -stock -stomach -stone -stool -story -stove -strategy -street -strike -strong -struggle -student -stuff -stumble -style -subject -submit -subway -success -such -sudden -suffer -sugar -suggest -suit -summer -sun -sunny -sunset -super -supply -supreme -sure -surface -surge -surprise -surround -survey -suspect -sustain -swallow -swamp -swap -swarm -swear -sweet -swift -swim -swing -switch -sword -symbol -symptom -syrup -system -table -tackle -tag -tail -talent -talk -tank -tape -target -task -taste -tattoo -taxi -teach -team -tell -ten -tenant -tennis -tent -term -test -text -thank -that -theme -then -theory -there -they -thing -this -thought -three -thrive -throw -thumb -thunder -ticket -tide -tiger -tilt -timber -time -tiny -tip -tired -tissue -title -toast -tobacco -today -toddler -toe -together -toilet -token -tomato -tomorrow -tone -tongue -tonight -tool -tooth -top -topic -topple -torch -tornado -tortoise -toss -total -tourist -toward -tower -town -toy -track -trade -traffic -tragic -train -transfer -trap -trash -travel -tray -treat -tree -trend -trial -tribe -trick -trigger -trim -trip -trophy -trouble -truck -true -truly -trumpet -trust -truth -try -tube -tuition -tumble -tuna -tunnel -turkey -turn -turtle -twelve -twenty -twice -twin -twist -two -type -typical -ugly -umbrella -unable -unaware -uncle -uncover -under -undo -unfair -unfold -unhappy -uniform -unique -unit -universe -unknown -unlock -until -unusual -unveil -update -upgrade -uphold -upon -upper -upset -urban -urge -usage -use -used -useful -useless -usual -utility -vacant -vacuum -vague -valid -valley -valve -van -vanish -vapor -various -vast -vault -vehicle -velvet -vendor -venture -venue -verb -verify -version -very -vessel -veteran -viable -vibrant -vicious -victory -video -view -village -vintage -violin -virtual -virus -visa -visit -visual -vital -vivid -vocal -voice -void -volcano -volume -vote -voyage -wage -wagon -wait -walk -wall -walnut -want -warfare -warm -warrior -wash -wasp -waste -water -wave -way -wealth -weapon -wear -weasel -weather -web -wedding -weekend -weird -welcome -west -wet -whale -what -wheat -wheel -when -where -whip -whisper -wide -width -wife -wild -will -win -window -wine -wing -wink -winner -winter -wire -wisdom -wise -wish -witness -wolf -woman -wonder -wood -wool -word -work -world -worry -worth -wrap -wreck -wrestle -wrist -write -wrong -yard -year -yellow -you -young -youth -zebra -zero -zone -zoo`.split("\n")); - -// node_modules/@noble/curves/utils.js -var abytes2 = (value, length, title) => abytes(value, length, title); -var anumber3 = anumber; -var bytesToHex2 = bytesToHex; -var concatBytes2 = (...arrays) => concatBytes(...arrays); -var hexToBytes2 = (hex) => hexToBytes(hex); -var isBytes3 = isBytes; -var randomBytes2 = (bytesLength) => randomBytes(bytesLength); -var _0n = /* @__PURE__ */ BigInt(0); -var _1n = /* @__PURE__ */ BigInt(1); -function abool(value, title = "") { - if (typeof value !== "boolean") { - const prefix = title && `"${title}" `; - throw new TypeError(prefix + "expected boolean, got type=" + typeof value); - } - return value; -} -function abignumber(n) { - if (typeof n === "bigint") { - if (!isPosBig(n)) - throw new RangeError("positive bigint expected, got " + n); - } else - anumber3(n); - return n; -} -function asafenumber(value, title = "") { - if (typeof value !== "number") { - const prefix = title && `"${title}" `; - throw new TypeError(prefix + "expected number, got type=" + typeof value); - } - if (!Number.isSafeInteger(value)) { - const prefix = title && `"${title}" `; - throw new RangeError(prefix + "expected safe integer, got " + value); - } -} -function numberToHexUnpadded(num) { - const hex = abignumber(num).toString(16); - return hex.length & 1 ? "0" + hex : hex; -} -function hexToNumber(hex) { - if (typeof hex !== "string") - throw new TypeError("hex string expected, got " + typeof hex); - return hex === "" ? _0n : BigInt("0x" + hex); -} -function bytesToNumberBE(bytes) { - return hexToNumber(bytesToHex(bytes)); -} -function bytesToNumberLE(bytes) { - return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse())); -} -function numberToBytesBE(n, len) { - anumber(len); - if (len === 0) - throw new RangeError("zero length"); - n = abignumber(n); - const hex = n.toString(16); - if (hex.length > len * 2) - throw new RangeError("number too large"); - return hexToBytes(hex.padStart(len * 2, "0")); -} -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); -} -function copyBytes(bytes) { - return Uint8Array.from(abytes2(bytes)); -} -var isPosBig = (n) => typeof n === "bigint" && _0n <= n; -function inRange(n, min, max) { - return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; -} -function aInRange(title, n, min, max) { - if (!inRange(n, min, max)) - throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); -} -function bitLen(n) { - if (n < _0n) - throw new Error("expected non-negative bigint, got " + n); - let len; - for (len = 0; n > _0n; n >>= _1n, len += 1) - ; - return len; -} -var bitMask = (n) => (_1n << BigInt(n)) - _1n; -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - anumber(hashLen, "hashLen"); - anumber(qByteLen, "qByteLen"); - if (typeof hmacFn !== "function") - throw new TypeError("hmacFn must be a function"); - const u8n = (len) => new Uint8Array(len); - const NULL = Uint8Array.of(); - const byte0 = Uint8Array.of(0); - const byte1 = Uint8Array.of(1); - const _maxDrbgIters = 1e3; - let v = u8n(hashLen); - let k = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs)); - const reseed = (seed = NULL) => { - k = h(byte0, seed); - v = h(); - if (seed.length === 0) - return; - k = h(byte1, seed); - v = h(); - }; - const gen2 = () => { - if (i++ >= _maxDrbgIters) - throw new Error("drbg: tried max amount of iterations"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes2(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = void 0; - while ((res = pred(gen2())) === void 0) - reseed(); - reset(); - return res; - }; - return genUntil; -} -function validateObject(object, fields = {}, optFields = {}) { - if (Object.prototype.toString.call(object) !== "[object Object]") - throw new TypeError("expected valid options object"); - function checkField(fieldName, expectedType, isOpt) { - if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName)) - throw new TypeError(`param "${fieldName}" is invalid: expected own property`); - const val = object[fieldName]; - if (isOpt && val === void 0) - return; - const current = typeof val; - if (current !== expectedType || val === null) - throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); - } - const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)); - iter(fields, false); - iter(optFields, true); -} - -// node_modules/@noble/curves/abstract/modular.js -var _0n2 = /* @__PURE__ */ BigInt(0); -var _1n2 = /* @__PURE__ */ BigInt(1); -var _2n = /* @__PURE__ */ BigInt(2); -var _3n = /* @__PURE__ */ BigInt(3); -var _4n = /* @__PURE__ */ BigInt(4); -var _5n = /* @__PURE__ */ BigInt(5); -var _7n = /* @__PURE__ */ BigInt(7); -var _8n = /* @__PURE__ */ BigInt(8); -var _9n = /* @__PURE__ */ BigInt(9); -var _16n = /* @__PURE__ */ BigInt(16); -function mod(a, b) { - if (b <= _0n2) - throw new Error("mod: expected positive modulus, got " + b); - const result = a % b; - return result >= _0n2 ? result : b + result; -} -function pow2(x, power, modulo) { - if (power < _0n2) - throw new Error("pow2: expected non-negative exponent, got " + power); - let res = x; - while (power-- > _0n2) { - res *= res; - res %= modulo; - } - return res; -} -function invert(number, modulo) { - if (number === _0n2) - throw new Error("invert: expected non-zero number"); - if (modulo <= _0n2) - throw new Error("invert: expected positive modulus, got " + modulo); - let a = mod(number, modulo); - let b = modulo; - let x = _0n2, y = _1n2, u = _1n2, v = _0n2; - while (a !== _0n2) { - const q = b / a; - const r = b - a * q; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; - } - const gcd2 = b; - if (gcd2 !== _1n2) - throw new Error("invert: does not exist"); - return mod(x, modulo); -} -function assertIsSquare(Fp, root, n) { - const F3 = Fp; - if (!F3.eql(F3.sqr(root), n)) - throw new Error("Cannot find square root"); -} -function sqrt3mod4(Fp, n) { - const F3 = Fp; - const p1div4 = (F3.ORDER + _1n2) / _4n; - const root = F3.pow(n, p1div4); - assertIsSquare(F3, root, n); - return root; -} -function sqrt5mod8(Fp, n) { - const F3 = Fp; - const p5div8 = (F3.ORDER - _5n) / _8n; - const n2 = F3.mul(n, _2n); - const v = F3.pow(n2, p5div8); - const nv = F3.mul(n, v); - const i = F3.mul(F3.mul(nv, _2n), v); - const root = F3.mul(nv, F3.sub(i, F3.ONE)); - assertIsSquare(F3, root, n); - return root; -} -function sqrt9mod16(P) { - const Fp_ = Field(P); - const tn = tonelliShanks(P); - const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); - const c2 = tn(Fp_, c1); - const c3 = tn(Fp_, Fp_.neg(c1)); - const c4 = (P + _7n) / _16n; - return ((Fp, n) => { - const F3 = Fp; - let tv1 = F3.pow(n, c4); - let tv2 = F3.mul(tv1, c1); - const tv3 = F3.mul(tv1, c2); - const tv4 = F3.mul(tv1, c3); - const e1 = F3.eql(F3.sqr(tv2), n); - const e2 = F3.eql(F3.sqr(tv3), n); - tv1 = F3.cmov(tv1, tv2, e1); - tv2 = F3.cmov(tv4, tv3, e2); - const e3 = F3.eql(F3.sqr(tv2), n); - const root = F3.cmov(tv1, tv2, e3); - assertIsSquare(F3, root, n); - return root; - }); -} -function tonelliShanks(P) { - if (P < _3n) - throw new Error("sqrt is not defined for small field"); - let Q3 = P - _1n2; - let S = 0; - while (Q3 % _2n === _0n2) { - Q3 /= _2n; - S++; - } - let Z = _2n; - const _Fp = Field(P); - while (FpLegendre(_Fp, Z) === 1) { - if (Z++ > 1e3) - throw new Error("Cannot find square root: probably non-prime P"); - } - if (S === 1) - return sqrt3mod4; - let cc = _Fp.pow(Z, Q3); - const Q1div2 = (Q3 + _1n2) / _2n; - return function tonelliSlow(Fp, n) { - const F3 = Fp; - if (F3.is0(n)) - return n; - if (FpLegendre(F3, n) !== 1) - throw new Error("Cannot find square root"); - let M = S; - let c = F3.mul(F3.ONE, cc); - let t = F3.pow(n, Q3); - let R = F3.pow(n, Q1div2); - while (!F3.eql(t, F3.ONE)) { - if (F3.is0(t)) - return F3.ZERO; - let i = 1; - let t_tmp = F3.sqr(t); - while (!F3.eql(t_tmp, F3.ONE)) { - i++; - t_tmp = F3.sqr(t_tmp); - if (i === M) - throw new Error("Cannot find square root"); - } - const exponent = _1n2 << BigInt(M - i - 1); - const b = F3.pow(c, exponent); - M = i; - c = F3.sqr(b); - t = F3.mul(t, c); - R = F3.mul(R, b); - } - return R; - }; -} -function FpSqrt(P) { - if (P % _4n === _3n) - return sqrt3mod4; - if (P % _8n === _5n) - return sqrt5mod8; - if (P % _16n === _9n) - return sqrt9mod16(P); - return tonelliShanks(P); -} -var FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" -]; -function validateField(field) { - const initial = { - ORDER: "bigint", - BYTES: "number", - BITS: "number" - }; - const opts2 = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - validateObject(field, opts2); - asafenumber(field.BYTES, "BYTES"); - asafenumber(field.BITS, "BITS"); - if (field.BYTES < 1 || field.BITS < 1) - throw new Error("invalid field: expected BYTES/BITS > 0"); - if (field.ORDER <= _1n2) - throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER); - return field; -} -function FpPow(Fp, num, power) { - const F3 = Fp; - if (power < _0n2) - throw new Error("invalid exponent, negatives unsupported"); - if (power === _0n2) - return F3.ONE; - if (power === _1n2) - return num; - let p = F3.ONE; - let d = num; - while (power > _0n2) { - if (power & _1n2) - p = F3.mul(p, d); - d = F3.sqr(d); - power >>= _1n2; - } - return p; -} -function FpInvertBatch(Fp, nums, passZero = false) { - const F3 = Fp; - const inverted = new Array(nums.length).fill(passZero ? F3.ZERO : void 0); - const multipliedAcc = nums.reduce((acc, num, i) => { - if (F3.is0(num)) - return acc; - inverted[i] = acc; - return F3.mul(acc, num); - }, F3.ONE); - const invertedAcc = F3.inv(multipliedAcc); - nums.reduceRight((acc, num, i) => { - if (F3.is0(num)) - return acc; - inverted[i] = F3.mul(acc, inverted[i]); - return F3.mul(acc, num); - }, invertedAcc); - return inverted; -} -function FpLegendre(Fp, n) { - const F3 = Fp; - const p1mod2 = (F3.ORDER - _1n2) / _2n; - const powered = F3.pow(n, p1mod2); - const yes = F3.eql(powered, F3.ONE); - const zero = F3.eql(powered, F3.ZERO); - const no = F3.eql(powered, F3.neg(F3.ONE)); - if (!yes && !zero && !no) - throw new Error("invalid Legendre symbol result"); - return yes ? 1 : zero ? 0 : -1; -} -function nLength(n, nBitLength) { - if (nBitLength !== void 0) - anumber3(nBitLength); - if (n <= _0n2) - throw new Error("invalid n length: expected positive n, got " + n); - if (nBitLength !== void 0 && nBitLength < 1) - throw new Error("invalid n length: expected positive bit length, got " + nBitLength); - const bits = bitLen(n); - if (nBitLength !== void 0 && nBitLength < bits) - throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`); - const _nBitLength = nBitLength !== void 0 ? nBitLength : bits; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; -} -var FIELD_SQRT = /* @__PURE__ */ new WeakMap(); -var _Field = class { - constructor(ORDER, opts2 = {}) { - __publicField(this, "ORDER"); - __publicField(this, "BITS"); - __publicField(this, "BYTES"); - __publicField(this, "isLE"); - __publicField(this, "ZERO", _0n2); - __publicField(this, "ONE", _1n2); - __publicField(this, "_lengths"); - __publicField(this, "_mod"); - if (ORDER <= _1n2) - throw new Error("invalid field: expected ORDER > 1, got " + ORDER); - let _nbitLength = void 0; - this.isLE = false; - if (opts2 != null && typeof opts2 === "object") { - if (typeof opts2.BITS === "number") - _nbitLength = opts2.BITS; - if (typeof opts2.sqrt === "function") - Object.defineProperty(this, "sqrt", { value: opts2.sqrt, enumerable: true }); - if (typeof opts2.isLE === "boolean") - this.isLE = opts2.isLE; - if (opts2.allowedLengths) - this._lengths = Object.freeze(opts2.allowedLengths.slice()); - if (typeof opts2.modFromBytes === "boolean") - this._mod = opts2.modFromBytes; - } - const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength); - if (nByteLength > 2048) - throw new Error("invalid field: expected ORDER of <= 2048 bytes"); - this.ORDER = ORDER; - this.BITS = nBitLength; - this.BYTES = nByteLength; - Object.freeze(this); - } - create(num) { - return mod(num, this.ORDER); - } - isValid(num) { - if (typeof num !== "bigint") - throw new TypeError("invalid field element: expected bigint, got " + typeof num); - return _0n2 <= num && num < this.ORDER; - } - is0(num) { - return num === _0n2; - } - // is valid and invertible - isValidNot0(num) { - return !this.is0(num) && this.isValid(num); - } - isOdd(num) { - return (num & _1n2) === _1n2; - } - neg(num) { - return mod(-num, this.ORDER); - } - eql(lhs, rhs) { - return lhs === rhs; - } - sqr(num) { - return mod(num * num, this.ORDER); - } - add(lhs, rhs) { - return mod(lhs + rhs, this.ORDER); - } - sub(lhs, rhs) { - return mod(lhs - rhs, this.ORDER); - } - mul(lhs, rhs) { - return mod(lhs * rhs, this.ORDER); - } - pow(num, power) { - return FpPow(this, num, power); - } - div(lhs, rhs) { - return mod(lhs * invert(rhs, this.ORDER), this.ORDER); - } - // Same as above, but doesn't normalize - sqrN(num) { - return num * num; - } - addN(lhs, rhs) { - return lhs + rhs; - } - subN(lhs, rhs) { - return lhs - rhs; - } - mulN(lhs, rhs) { - return lhs * rhs; - } - inv(num) { - return invert(num, this.ORDER); - } - sqrt(num) { - let sqrt = FIELD_SQRT.get(this); - if (!sqrt) - FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER)); - return sqrt(this, num); - } - toBytes(num) { - return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES); - } - fromBytes(bytes, skipValidation = false) { - abytes2(bytes); - const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this; - if (allowedLengths) { - if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) { - throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length); - } - const padded = new Uint8Array(BYTES); - padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length); - bytes = padded; - } - if (bytes.length !== BYTES) - throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); - let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); - if (modFromBytes) - scalar = mod(scalar, ORDER); - if (!skipValidation) { - if (!this.isValid(scalar)) - throw new Error("invalid field element: outside of range 0..ORDER"); - } - return scalar; - } - // TODO: we don't need it here, move out to separate fn - invertBatch(lst) { - return FpInvertBatch(this, lst); - } - // We can't move this out because Fp6, Fp12 implement it - // and it's unclear what to return in there. - cmov(a, b, condition) { - abool(condition, "condition"); - return condition ? b : a; - } -}; -Object.freeze(_Field.prototype); -function Field(ORDER, opts2 = {}) { - return new _Field(ORDER, opts2); -} -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - if (fieldOrder <= _1n2) - throw new Error("field order must be greater than 1"); - const bitLength = bitLen(fieldOrder - _1n2); - return Math.ceil(bitLength / 8); -} -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); -} -function mapHashToField(key, fieldOrder, isLE2 = false) { - abytes2(key); - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = Math.max(getMinHashLength(fieldOrder), 16); - if (len < minLen || len > 1024) - throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); - const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key); - const reduced = mod(num, fieldOrder - _1n2) + _1n2; - return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); -} - -// node_modules/@noble/curves/abstract/curve.js -var _0n3 = /* @__PURE__ */ BigInt(0); -var _1n3 = /* @__PURE__ */ BigInt(1); -function negateCt(condition, item) { - const neg = item.negate(); - return condition ? neg : item; -} -function normalizeZ(c, points) { - const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z)); - return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); -} -function validateW(W, bits) { - if (!Number.isSafeInteger(W) || W <= 0 || W > bits) - throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); -} -function calcWOpts(W, scalarBits) { - validateW(W, scalarBits); - const windows = Math.ceil(scalarBits / W) + 1; - const windowSize = 2 ** (W - 1); - const maxNumber = 2 ** W; - const mask = bitMask(W); - const shiftBy = BigInt(W); - return { windows, windowSize, mask, maxNumber, shiftBy }; -} -function calcOffsets(n, window, wOpts) { - const { windowSize, mask, maxNumber, shiftBy } = wOpts; - let wbits = Number(n & mask); - let nextN = n >> shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - nextN += _1n3; - } - const offsetStart = window * windowSize; - const offset = offsetStart + Math.abs(wbits) - 1; - const isZero = wbits === 0; - const isNeg = wbits < 0; - const isNegF = window % 2 !== 0; - const offsetF = offsetStart; - return { nextN, offset, isZero, isNeg, isNegF, offsetF }; -} -var pointPrecomputes = /* @__PURE__ */ new WeakMap(); -var pointWindowSizes = /* @__PURE__ */ new WeakMap(); -function getW(P) { - return pointWindowSizes.get(P) || 1; -} -function assert0(n) { - if (n !== _0n3) - throw new Error("invalid wNAF"); -} -var wNAF = class { - // Parametrized with a given Point class (not individual point) - constructor(Point2, bits) { - __publicField(this, "BASE"); - __publicField(this, "ZERO"); - __publicField(this, "Fn"); - __publicField(this, "bits"); - this.BASE = Point2.BASE; - this.ZERO = Point2.ZERO; - this.Fn = Point2.Fn; - this.bits = bits; - } - // non-const time multiplication ladder - _unsafeLadder(elm, n, p = this.ZERO) { - let d = elm; - while (n > _0n3) { - if (n & _1n3) - p = p.add(d); - d = d.double(); - n >>= _1n3; - } - return p; - } - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(๐‘Šโˆ’1) * (Math.ceil(๐‘› / ๐‘Š) + 1), where: - * - ๐‘Š is the window size - * - ๐‘› is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @param point - Point instance - * @param W - window size - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(point, W) { - const { windows, windowSize } = calcWOpts(W, this.bits); - const points = []; - let p = point; - let base = p; - for (let window = 0; window < windows; window++) { - base = p; - points.push(base); - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - } - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * More compact implementation: - * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - if (!this.Fn.isValid(n)) - throw new Error("invalid scalar"); - let p = this.ZERO; - let f = this.BASE; - const wo = calcWOpts(W, this.bits); - for (let window = 0; window < wo.windows; window++) { - const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo); - n = nextN; - if (isZero) { - f = f.add(negateCt(isNegF, precomputes[offsetF])); - } else { - p = p.add(negateCt(isNeg, precomputes[offset])); - } - } - assert0(n); - return { p, f }; - } - /** - * Implements unsafe EC multiplication using precomputed tables - * and w-ary non-adjacent form. - * @param acc - accumulator point to add result of multiplication - * @returns point - */ - wNAFUnsafe(W, precomputes, n, acc = this.ZERO) { - const wo = calcWOpts(W, this.bits); - for (let window = 0; window < wo.windows; window++) { - if (n === _0n3) - break; - const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo); - n = nextN; - if (isZero) { - continue; - } else { - const item = precomputes[offset]; - acc = acc.add(isNeg ? item.negate() : item); - } - } - assert0(n); - return acc; - } - getPrecomputes(W, point, transform) { - let comp = pointPrecomputes.get(point); - if (!comp) { - comp = this.precomputeWindow(point, W); - if (W !== 1) { - if (typeof transform === "function") - comp = transform(comp); - pointPrecomputes.set(point, comp); - } - } - return comp; - } - cached(point, scalar, transform) { - const W = getW(point); - return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar); - } - unsafe(point, scalar, transform, prev) { - const W = getW(point); - if (W === 1) - return this._unsafeLadder(point, scalar, prev); - return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev); - } - // We calculate precomputes for elliptic curve point multiplication - // using windowed method. This specifies window size and - // stores precomputed values. Usually only base point would be precomputed. - createCache(P, W) { - validateW(W, this.bits); - pointWindowSizes.set(P, W); - pointPrecomputes.delete(P); - } - hasCache(elm) { - return getW(elm) !== 1; - } -}; -function mulEndoUnsafe(Point2, point, k1, k2) { - let acc = point; - let p1 = Point2.ZERO; - let p2 = Point2.ZERO; - while (k1 > _0n3 || k2 > _0n3) { - if (k1 & _1n3) - p1 = p1.add(acc); - if (k2 & _1n3) - p2 = p2.add(acc); - acc = acc.double(); - k1 >>= _1n3; - k2 >>= _1n3; - } - return { p1, p2 }; -} -function createField(order, field, isLE2) { - if (field) { - if (field.ORDER !== order) - throw new Error("Field.ORDER must match order: Fp == p, Fn == n"); - validateField(field); - return field; - } else { - return Field(order, { isLE: isLE2 }); - } -} -function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) { - if (FpFnLE === void 0) - FpFnLE = type === "edwards"; - if (!CURVE || typeof CURVE !== "object") - throw new Error(`expected valid ${type} CURVE object`); - for (const p of ["p", "n", "h"]) { - const val = CURVE[p]; - if (!(typeof val === "bigint" && val > _0n3)) - throw new Error(`CURVE.${p} must be positive bigint`); - } - const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); - const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE); - const _b = type === "weierstrass" ? "b" : "d"; - const params = ["Gx", "Gy", "a", _b]; - for (const p of params) { - if (!Fp.isValid(CURVE[p])) - throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); - } - CURVE = Object.freeze(Object.assign({}, CURVE)); - return { CURVE, Fp, Fn: Fn2 }; -} -function createKeygen(randomSecretKey, getPublicKey) { - return function keygen(seed) { - const secretKey = randomSecretKey(seed); - return { secretKey, publicKey: getPublicKey(secretKey) }; - }; -} - -// node_modules/@noble/curves/abstract/fft.js -function checkU32(n) { - if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295) - throw new Error("wrong u32 integer:" + n); - return n; -} -function isPowerOfTwo(x) { - checkU32(x); - return (x & x - 1) === 0 && x !== 0; -} -function reverseBits(n, bits) { - checkU32(n); - if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) - throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`); - let reversed = 0; - for (let i = 0; i < bits; i++, n >>>= 1) - reversed = reversed << 1 | n & 1; - return reversed >>> 0; -} -function log2(n) { - checkU32(n); - return 31 - Math.clz32(n); -} -function bitReversalInplace(values) { - const n = values.length; - if (!isPowerOfTwo(n)) - throw new Error("expected positive power-of-two length, got " + n); - const bits = log2(n); - for (let i = 0; i < n; i++) { - const j = reverseBits(i, bits); - if (i < j) { - const tmp = values[i]; - values[i] = values[j]; - values[j] = tmp; - } - } - return values; -} -var FFTCore = (F3, coreOpts) => { - const { N: N3, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts; - const bits = log2(N3); - if (!isPowerOfTwo(N3)) - throw new Error("FFT: Polynomial size should be power of two"); - if (roots.length !== N3) - throw new Error(`FFT: wrong roots length: expected ${N3}, got ${roots.length}`); - const isDit = dit !== invertButterflies; - isDit; - return (values) => { - if (values.length !== N3) - throw new Error("FFT: wrong Polynomial length"); - if (dit && brp) - bitReversalInplace(values); - for (let i = 0, g = 1; i < bits - skipStages; i++) { - const s = dit ? i + 1 + skipStages : bits - i; - const m = 1 << s; - const m2 = m >> 1; - const stride = N3 >> s; - for (let k = 0; k < N3; k += m) { - for (let j = 0, grp = g++; j < m2; j++) { - const rootPos = invertButterflies ? dit ? N3 - grp : grp : j * stride; - const i0 = k + j; - const i1 = k + j + m2; - const omega = roots[rootPos]; - const b = values[i1]; - const a = values[i0]; - if (isDit) { - const t = F3.mul(b, omega); - values[i0] = F3.add(a, t); - values[i1] = F3.sub(a, t); - } else if (invertButterflies) { - values[i0] = F3.add(b, a); - values[i1] = F3.mul(F3.sub(b, a), omega); - } else { - values[i0] = F3.add(a, b); - values[i1] = F3.mul(F3.sub(a, b), omega); - } - } - } - } - if (!dit && brp) - bitReversalInplace(values); - return values; - }; -}; - -// node_modules/@noble/curves/abstract/weierstrass.js -var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den; -function _splitEndoScalar(k, basis, n) { - aInRange("scalar", k, _0n4, n); - const [[a1, b1], [a2, b2]] = basis; - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = k - c1 * a1 - c2 * a2; - let k2 = -c1 * b1 - c2 * b2; - const k1neg = k1 < _0n4; - const k2neg = k2 < _0n4; - if (k1neg) - k1 = -k1; - if (k2neg) - k2 = -k2; - const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4; - if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) { - throw new Error("splitScalar (endomorphism): failed for k"); - } - return { k1neg, k1, k2neg, k2 }; -} -function validateSigFormat(format) { - if (!["compact", "recovered", "der"].includes(format)) - throw new Error('Signature format must be "compact", "recovered", or "der"'); - return format; -} -function validateSigOpts(opts2, def) { - validateObject(opts2); - const optsn = {}; - for (let optName of Object.keys(def)) { - optsn[optName] = opts2[optName] === void 0 ? def[optName] : opts2[optName]; - } - abool(optsn.lowS, "lowS"); - abool(optsn.prehash, "prehash"); - if (optsn.format !== void 0) - validateSigFormat(optsn.format); - return optsn; -} -var DERErr = class extends Error { - constructor(m = "") { - super(m); - } -}; -var DER = { - // asn.1 DER encoding utils - Err: DERErr, - // Basic building block is TLV (Tag-Length-Value) - _tlv: { - encode: (tag, data) => { - const { Err: E } = DER; - asafenumber(tag, "tag"); - if (tag < 0 || tag > 255) - throw new E("tlv.encode: wrong tag"); - if (typeof data !== "string") - throw new TypeError('"data" expected string, got type=' + typeof data); - if (data.length & 1) - throw new E("tlv.encode: unpadded data"); - const dataLen = data.length / 2; - const len = numberToHexUnpadded(dataLen); - if (len.length / 2 & 128) - throw new E("tlv.encode: long form length too big"); - const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; - const t = numberToHexUnpadded(tag); - return t + lenLen + len + data; - }, - // v - value, l - left bytes (unparsed) - decode(tag, data) { - const { Err: E } = DER; - data = abytes2(data, void 0, "DER data"); - let pos = 0; - if (tag < 0 || tag > 255) - throw new E("tlv.encode: wrong tag"); - if (data.length < 2 || data[pos++] !== tag) - throw new E("tlv.decode: wrong tlv"); - const first = data[pos++]; - const isLong = !!(first & 128); - let length = 0; - if (!isLong) - length = first; - else { - const lenLen = first & 127; - if (!lenLen) - throw new E("tlv.decode(long): indefinite length not supported"); - if (lenLen > 4) - throw new E("tlv.decode(long): byte length is too big"); - const lengthBytes = data.subarray(pos, pos + lenLen); - if (lengthBytes.length !== lenLen) - throw new E("tlv.decode: length bytes not complete"); - if (lengthBytes[0] === 0) - throw new E("tlv.decode(long): zero leftmost byte"); - for (const b of lengthBytes) - length = length << 8 | b; - pos += lenLen; - if (length < 128) - throw new E("tlv.decode(long): not minimal encoding"); - } - const v = data.subarray(pos, pos + length); - if (v.length !== length) - throw new E("tlv.decode: wrong value length"); - return { v, l: data.subarray(pos + length) }; - } - }, - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - _int: { - encode(num) { - const { Err: E } = DER; - abignumber(num); - if (num < _0n4) - throw new E("integer: negative integers are not allowed"); - let hex = numberToHexUnpadded(num); - if (Number.parseInt(hex[0], 16) & 8) - hex = "00" + hex; - if (hex.length & 1) - throw new E("unexpected DER parsing assertion: unpadded hex"); - return hex; - }, - decode(data) { - const { Err: E } = DER; - if (data.length < 1) - throw new E("invalid signature integer: empty"); - if (data[0] & 128) - throw new E("invalid signature integer: negative"); - if (data.length > 1 && data[0] === 0 && !(data[1] & 128)) - throw new E("invalid signature integer: unnecessary leading zero"); - return bytesToNumberBE(data); - } - }, - toSig(bytes) { - const { Err: E, _int: int, _tlv: tlv } = DER; - const data = abytes2(bytes, void 0, "signature"); - const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); - if (seqLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); - const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); - if (sLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - return { r: int.decode(rBytes), s: int.decode(sBytes) }; - }, - hexFromSig(sig) { - const { _tlv: tlv, _int: int } = DER; - const rs = tlv.encode(2, int.encode(sig.r)); - const ss = tlv.encode(2, int.encode(sig.s)); - const seq = rs + ss; - return tlv.encode(48, seq); - } -}; -Object.freeze(DER._tlv); -Object.freeze(DER._int); -Object.freeze(DER); -var _0n4 = /* @__PURE__ */ BigInt(0); -var _1n4 = /* @__PURE__ */ BigInt(1); -var _2n2 = /* @__PURE__ */ BigInt(2); -var _3n2 = /* @__PURE__ */ BigInt(3); -var _4n2 = /* @__PURE__ */ BigInt(4); -function weierstrass(params, extraOpts = {}) { - const validated = createCurveFields("weierstrass", params, extraOpts); - const Fp = validated.Fp; - const Fn2 = validated.Fn; - let CURVE = validated.CURVE; - const { h: cofactor, n: CURVE_ORDER } = CURVE; - validateObject(extraOpts, {}, { - allowInfinityPoint: "boolean", - clearCofactor: "function", - isTorsionFree: "function", - fromBytes: "function", - toBytes: "function", - endo: "object" - }); - const { endo, allowInfinityPoint } = extraOpts; - if (endo) { - if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) { - throw new Error('invalid endo: expected "beta": bigint and "basises": array'); - } - } - const lengths = getWLengths(Fp, Fn2); - function assertCompressionIsSupported() { - if (!Fp.isOdd) - throw new Error("compression is not supported: Field does not have .isOdd()"); - } - function pointToBytes(_c, point, isCompressed) { - if (allowInfinityPoint && point.is0()) - return Uint8Array.of(0); - const { x, y } = point.toAffine(); - const bx = Fp.toBytes(x); - abool(isCompressed, "isCompressed"); - if (isCompressed) { - assertCompressionIsSupported(); - const hasEvenY = !Fp.isOdd(y); - return concatBytes2(pprefix(hasEvenY), bx); - } else { - return concatBytes2(Uint8Array.of(4), bx, Fp.toBytes(y)); - } - } - function pointFromBytes(bytes) { - abytes2(bytes, void 0, "Point"); - const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; - const length = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - if (allowInfinityPoint && length === 1 && head === 0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (length === comp && (head === 2 || head === 3)) { - const x = Fp.fromBytes(tail); - if (!Fp.isValid(x)) - throw new Error("bad point: is not on curve, wrong x"); - const y2 = weierstrassEquation(x); - let y; - try { - y = Fp.sqrt(y2); - } catch (sqrtError) { - const err = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("bad point: is not on curve, sqrt error" + err); - } - assertCompressionIsSupported(); - const evenY = Fp.isOdd(y); - const evenH = (head & 1) === 1; - if (evenH !== evenY) - y = Fp.neg(y); - return { x, y }; - } else if (length === uncomp && head === 4) { - const L = Fp.BYTES; - const x = Fp.fromBytes(tail.subarray(0, L)); - const y = Fp.fromBytes(tail.subarray(L, L * 2)); - if (!isValidXY(x, y)) - throw new Error("bad point: is not on curve"); - return { x, y }; - } else { - throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`); - } - } - const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes; - const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes; - function weierstrassEquation(x) { - const x2 = Fp.sqr(x); - const x3 = Fp.mul(x2, x); - return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); - } - function isValidXY(x, y) { - const left = Fp.sqr(y); - const right = weierstrassEquation(x); - return Fp.eql(left, right); - } - if (!isValidXY(CURVE.Gx, CURVE.Gy)) - throw new Error("bad curve params: generator point"); - const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2); - const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); - if (Fp.is0(Fp.add(_4a3, _27b2))) - throw new Error("bad curve params: a or b"); - function acoord(title, n, banZero = false) { - if (!Fp.isValid(n) || banZero && Fp.is0(n)) - throw new Error(`bad point coordinate ${title}`); - return n; - } - function aprjpoint(other) { - if (!(other instanceof Point2)) - throw new Error("Weierstrass Point expected"); - } - function splitEndoScalarN(k) { - if (!endo || !endo.basises) - throw new Error("no endo"); - return _splitEndoScalar(k, endo.basises, Fn2.ORDER); - } - function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { - k2p = new Point2(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); - k1p = negateCt(k1neg, k1p); - k2p = negateCt(k2neg, k2p); - return k1p.add(k2p); - } - const _Point = class _Point { - /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ - constructor(X, Y, Z) { - __publicField(this, "X"); - __publicField(this, "Y"); - __publicField(this, "Z"); - this.X = acoord("x", X); - this.Y = acoord("y", Y, true); - this.Z = acoord("z", Z); - Object.freeze(this); - } - static CURVE() { - return CURVE; - } - /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof _Point) - throw new Error("projective point not allowed"); - if (Fp.is0(x) && Fp.is0(y)) - return _Point.ZERO; - return new _Point(x, y, Fp.ONE); - } - static fromBytes(bytes) { - const P = _Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point"))); - P.assertValidity(); - return P; - } - static fromHex(hex) { - return _Point.fromBytes(hexToBytes2(hex)); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * - * @param windowSize - * @param isLazy - true will defer table computation until the first multiplication - * @returns - */ - precompute(windowSize = 8, isLazy = true) { - wnaf.createCache(this, windowSize); - if (!isLazy) - this.multiply(_3n2); - return this; - } - // TODO: return `this` - /** A point on curve is valid if it conforms to equation. */ - assertValidity() { - const p = this; - if (p.is0()) { - if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) - return; - throw new Error("bad point: ZERO"); - } - const { x, y } = p.toAffine(); - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("bad point: x or y not field elements"); - if (!isValidXY(x, y)) - throw new Error("bad point: equation left != right"); - if (!p.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - } - hasEvenY() { - const { y } = this.toAffine(); - if (!Fp.isOdd) - throw new Error("Field doesn't support isOdd"); - return !Fp.isOdd(y); - } - /** Compare one point to another. */ - equals(other) { - aprjpoint(other); - const { X: X1, Y: Y1, Z: Z1 } = this; - const { X: X2, Y: Y2, Z: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; - } - /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ - negate() { - return new _Point(this.X, Fp.neg(this.Y), this.Z); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n2); - const { X: X1, Y: Y1, Z: Z1 } = this; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - let t0 = Fp.mul(X1, X1); - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); - Z3 = Fp.add(Z3, Z3); - return new _Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - aprjpoint(other); - const { X: X1, Y: Y1, Z: Z1 } = this; - const { X: X2, Y: Y2, Z: Z2 } = other; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n2); - let t0 = Fp.mul(X1, X2); - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); - return new _Point(X3, Y3, Z3); - } - subtract(other) { - aprjpoint(other); - return this.add(other.negate()); - } - is0() { - return this.equals(_Point.ZERO); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar - by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - const { endo: endo2 } = extraOpts; - if (!Fn2.isValidNot0(scalar)) - throw new RangeError("invalid scalar: out of range"); - let point, fake; - const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(_Point, p)); - if (endo2) { - const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); - const { p: k1p, f: k1f } = mul(k1); - const { p: k2p, f: k2f } = mul(k2); - fake = k1f.add(k2f); - point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg); - } else { - const { p, f } = mul(scalar); - point = p; - fake = f; - } - return normalizeZ(_Point, [point, fake])[0]; - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed secret key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(scalar) { - const { endo: endo2 } = extraOpts; - const p = this; - const sc = scalar; - if (!Fn2.isValid(sc)) - throw new RangeError("invalid scalar: out of range"); - if (sc === _0n4 || p.is0()) - return _Point.ZERO; - if (sc === _1n4) - return p; - if (wnaf.hasCache(this)) - return this.multiply(sc); - if (endo2) { - const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); - const { p1, p2 } = mulEndoUnsafe(_Point, p, k1, k2); - return finishEndo(endo2.beta, p1, p2, k1neg, k2neg); - } else { - return wnaf.unsafe(p, sc); - } - } - /** - * Converts Projective point to affine (x, y) coordinates. - * (X, Y, Z) โˆ‹ (x=X/Z, y=Y/Z). - * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch - */ - toAffine(invertedZ) { - const p = this; - let iz = invertedZ; - const { X, Y, Z } = p; - if (Fp.eql(Z, Fp.ONE)) - return { x: X, y: Y }; - const is0 = p.is0(); - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(Z); - const x = Fp.mul(X, iz); - const y = Fp.mul(Y, iz); - const zz = Fp.mul(Z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error("invZ was invalid"); - return { x, y }; - } - /** - * Checks whether Point is free of torsion elements (is in prime subgroup). - * Always torsion-free for cofactor=1 curves. - */ - isTorsionFree() { - const { isTorsionFree } = extraOpts; - if (cofactor === _1n4) - return true; - if (isTorsionFree) - return isTorsionFree(_Point, this); - return wnaf.unsafe(this, CURVE_ORDER).is0(); - } - clearCofactor() { - const { clearCofactor } = extraOpts; - if (cofactor === _1n4) - return this; - if (clearCofactor) - return clearCofactor(_Point, this); - return this.multiplyUnsafe(cofactor); - } - isSmallOrder() { - if (cofactor === _1n4) - return this.is0(); - return this.clearCofactor().is0(); - } - toBytes(isCompressed = true) { - abool(isCompressed, "isCompressed"); - this.assertValidity(); - return encodePoint(_Point, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex2(this.toBytes(isCompressed)); - } - toString() { - return ``; - } - }; - // base / generator point - __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp.ONE)); - // zero / infinity / identity point - __publicField(_Point, "ZERO", new _Point(Fp.ZERO, Fp.ONE, Fp.ZERO)); - // 0, 1, 0 - // math field - __publicField(_Point, "Fp", Fp); - // scalar field - __publicField(_Point, "Fn", Fn2); - let Point2 = _Point; - const bits = Fn2.BITS; - const wnaf = new wNAF(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits); - if (bits >= 8) - Point2.BASE.precompute(8); - Object.freeze(Point2.prototype); - Object.freeze(Point2); - return Point2; -} -function pprefix(hasEvenY) { - return Uint8Array.of(hasEvenY ? 2 : 3); -} -function getWLengths(Fp, Fn2) { - return { - secretKey: Fn2.BYTES, - publicKey: 1 + Fp.BYTES, - publicKeyUncompressed: 1 + 2 * Fp.BYTES, - publicKeyHasPrefix: true, - // Raw compact `(r || s)` signature width; DER and recovered signatures use - // different lengths outside this helper. - signature: 2 * Fn2.BYTES - }; -} -function ecdh(Point2, ecdhOpts = {}) { - const { Fn: Fn2 } = Point2; - const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes; - const lengths = Object.assign(getWLengths(Point2.Fp, Fn2), { - seed: Math.max(getMinHashLength(Fn2.ORDER), 16) - }); - function isValidSecretKey(secretKey) { - try { - const num = Fn2.fromBytes(secretKey); - return Fn2.isValidNot0(num); - } catch (error) { - return false; - } - } - function isValidPublicKey(publicKey, isCompressed) { - const { publicKey: comp, publicKeyUncompressed } = lengths; - try { - const l = publicKey.length; - if (isCompressed === true && l !== comp) - return false; - if (isCompressed === false && l !== publicKeyUncompressed) - return false; - return !!Point2.fromBytes(publicKey); - } catch (error) { - return false; - } - } - function randomSecretKey(seed) { - seed = seed === void 0 ? randomBytes_(lengths.seed) : seed; - return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn2.ORDER); - } - function getPublicKey(secretKey, isCompressed = true) { - return Point2.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed); - } - function isProbPub(item) { - const { secretKey, publicKey, publicKeyUncompressed } = lengths; - const allowedLengths = Fn2._lengths; - if (!isBytes3(item)) - return void 0; - const l = abytes2(item, void 0, "key").length; - const isPub = l === publicKey || l === publicKeyUncompressed; - const isSec = l === secretKey || !!allowedLengths?.includes(l); - if (isPub && isSec) - return void 0; - return isPub; - } - function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) { - if (isProbPub(secretKeyA) === true) - throw new Error("first arg must be private key"); - if (isProbPub(publicKeyB) === false) - throw new Error("second arg must be public key"); - const s = Fn2.fromBytes(secretKeyA); - const b = Point2.fromBytes(publicKeyB); - return b.multiply(s).toBytes(isCompressed); - } - const utils2 = { - isValidSecretKey, - isValidPublicKey, - randomSecretKey - }; - const keygen = createKeygen(randomSecretKey, getPublicKey); - Object.freeze(utils2); - Object.freeze(lengths); - return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point: Point2, utils: utils2, lengths }); -} -function ecdsa(Point2, hash, ecdsaOpts = {}) { - const hash_ = hash; - ahash(hash_); - validateObject(ecdsaOpts, {}, { - hmac: "function", - lowS: "boolean", - randomBytes: "function", - bits2int: "function", - bits2int_modN: "function" - }); - ecdsaOpts = Object.assign({}, ecdsaOpts); - const randomBytes4 = ecdsaOpts.randomBytes === void 0 ? randomBytes2 : ecdsaOpts.randomBytes; - const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac; - const { Fp, Fn: Fn2 } = Point2; - const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2; - const { keygen, getPublicKey, getSharedSecret, utils: utils2, lengths } = ecdh(Point2, ecdsaOpts); - const defaultSigOpts = { - prehash: true, - lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true, - format: "compact", - extraEntropy: false - }; - const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER; - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n4; - return number > HALF; - } - function validateRS(title, num) { - if (!Fn2.isValidNot0(num)) - throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); - return num; - } - function assertRecoverableCurve() { - if (hasLargeRecoveryLifts) - throw new Error('"recovered" sig type is not supported for cofactor >2 curves'); - } - function validateSigLength(bytes, format) { - validateSigFormat(format); - const size = lengths.signature; - const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0; - return abytes2(bytes, sizer); - } - class Signature { - constructor(r, s, recovery) { - __publicField(this, "r"); - __publicField(this, "s"); - __publicField(this, "recovery"); - this.r = validateRS("r", r); - this.s = validateRS("s", s); - if (recovery != null) { - assertRecoverableCurve(); - if (![0, 1, 2, 3].includes(recovery)) - throw new Error("invalid recovery id"); - this.recovery = recovery; - } - Object.freeze(this); - } - static fromBytes(bytes, format = defaultSigOpts.format) { - validateSigLength(bytes, format); - let recid; - if (format === "der") { - const { r: r2, s: s2 } = DER.toSig(abytes2(bytes)); - return new Signature(r2, s2); - } - if (format === "recovered") { - recid = bytes[0]; - format = "compact"; - bytes = bytes.subarray(1); - } - const L = lengths.signature / 2; - const r = bytes.subarray(0, L); - const s = bytes.subarray(L, L * 2); - return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid); - } - static fromHex(hex, format) { - return this.fromBytes(hexToBytes2(hex), format); - } - assertRecovery() { - const { recovery } = this; - if (recovery == null) - throw new Error("invalid recovery id: must be present"); - return recovery; - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - // Unlike the top-level helper below, this method expects a digest that has - // already been hashed to the curve's message representative. - recoverPublicKey(messageHash) { - const { r, s } = this; - const recovery = this.assertRecovery(); - const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r; - if (!Fp.isValid(radj)) - throw new Error("invalid recovery id: sig.r+curve.n != R.x"); - const x = Fp.toBytes(radj); - const R = Point2.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x)); - const ir = Fn2.inv(radj); - const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash")); - const u1 = Fn2.create(-h * ir); - const u2 = Fn2.create(s * ir); - const Q3 = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); - if (Q3.is0()) - throw new Error("invalid recovery: point at infinify"); - Q3.assertValidity(); - return Q3; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - toBytes(format = defaultSigOpts.format) { - validateSigFormat(format); - if (format === "der") - return hexToBytes2(DER.hexFromSig(this)); - const { r, s } = this; - const rb = Fn2.toBytes(r); - const sb = Fn2.toBytes(s); - if (format === "recovered") { - assertRecoverableCurve(); - return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb); - } - return concatBytes2(rb, sb); - } - toHex(format) { - return bytesToHex2(this.toBytes(format)); - } - } - Object.freeze(Signature.prototype); - Object.freeze(Signature); - const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) { - if (bytes.length > 8192) - throw new Error("input is too large"); - const num = bytesToNumberBE(bytes); - const delta = bytes.length * 8 - fnBits; - return delta > 0 ? num >> BigInt(delta) : num; - } : ecdsaOpts.bits2int; - const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) { - return Fn2.create(bits2int(bytes)); - } : ecdsaOpts.bits2int_modN; - const ORDER_MASK = bitMask(fnBits); - function int2octets(num) { - aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK); - return Fn2.toBytes(num); - } - function validateMsgAndHash(message, prehash) { - abytes2(message, void 0, "message"); - return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message; - } - function prepSig(message, secretKey, opts2) { - const { lowS, prehash, extraEntropy } = validateSigOpts(opts2, defaultSigOpts); - message = validateMsgAndHash(message, prehash); - const h1int = bits2int_modN(message); - const d = Fn2.fromBytes(secretKey); - if (!Fn2.isValidNot0(d)) - throw new Error("invalid private key"); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (extraEntropy != null && extraEntropy !== false) { - const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy; - seedArgs.push(abytes2(e, void 0, "extraEntropy")); - } - const seed = concatBytes2(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!Fn2.isValidNot0(k)) - return; - const ik = Fn2.inv(k); - const q = Point2.BASE.multiply(k).toAffine(); - const r = Fn2.create(q.x); - if (r === _0n4) - return; - const s = Fn2.create(ik * Fn2.create(m + r * d)); - if (s === _0n4) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = Fn2.neg(s); - recovery ^= 1; - } - return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery); - } - return { seed, k2sig }; - } - function sign(message, secretKey, opts2 = {}) { - const { seed, k2sig } = prepSig(message, secretKey, opts2); - const drbg = createHmacDrbg(hash_.outputLen, Fn2.BYTES, hmac2); - const sig = drbg(seed, k2sig); - return sig.toBytes(opts2.format); - } - function verify(signature, message, publicKey, opts2 = {}) { - const { lowS, prehash, format } = validateSigOpts(opts2, defaultSigOpts); - publicKey = abytes2(publicKey, void 0, "publicKey"); - message = validateMsgAndHash(message, prehash); - if (!isBytes3(signature)) { - const end = signature instanceof Signature ? ", use sig.toBytes()" : ""; - throw new Error("verify expects Uint8Array signature" + end); - } - validateSigLength(signature, format); - try { - const sig = Signature.fromBytes(signature, format); - const P = Point2.fromBytes(publicKey); - if (lowS && sig.hasHighS()) - return false; - const { r, s } = sig; - const h = bits2int_modN(message); - const is = Fn2.inv(s); - const u1 = Fn2.create(h * is); - const u2 = Fn2.create(r * is); - const R = Point2.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); - if (R.is0()) - return false; - const v = Fn2.create(R.x); - return v === r; - } catch (e) { - return false; - } - } - function recoverPublicKey(signature, message, opts2 = {}) { - const { prehash } = validateSigOpts(opts2, defaultSigOpts); - message = validateMsgAndHash(message, prehash); - return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes(); - } - return Object.freeze({ - keygen, - getPublicKey, - getSharedSecret, - utils: utils2, - lengths, - Point: Point2, - sign, - verify, - recoverPublicKey, - Signature, - hash: hash_ - }); -} - -// node_modules/@noble/curves/secp256k1.js -var secp256k1_CURVE = { - p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), - n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), - h: BigInt(1), - a: BigInt(0), - b: BigInt(7), - Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"), - Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8") -}; -var secp256k1_ENDO = { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - basises: [ - [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], - [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")] - ] -}; -var _2n3 = /* @__PURE__ */ BigInt(2); -function sqrtMod(y) { - const P = secp256k1_CURVE.p; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n3, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n3, P); - if (!Fpk1.eql(Fpk1.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; -} -var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod }); -var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, { - Fp: Fpk1, - endo: secp256k1_ENDO -}); -var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256); - -// node_modules/@noble/hashes/legacy.js -var Rho160 = /* @__PURE__ */ Uint8Array.from([ - 7, - 4, - 13, - 1, - 10, - 6, - 15, - 3, - 12, - 0, - 9, - 5, - 2, - 14, - 11, - 8 -]); -var Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))(); -var Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))(); -var idxLR = /* @__PURE__ */ (() => { - const L = [Id160]; - const R = [Pi160]; - const res = [L, R]; - for (let i = 0; i < 4; i++) - for (let j of res) - j.push(j[i].map((k) => Rho160[k])); - return res; -})(); -var idxL = /* @__PURE__ */ (() => idxLR[0])(); -var idxR = /* @__PURE__ */ (() => idxLR[1])(); -var shifts160 = /* @__PURE__ */ [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] -].map((i) => Uint8Array.from(i)); -var shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j])); -var shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j])); -var Kl160 = /* @__PURE__ */ Uint32Array.from([ - 0, - 1518500249, - 1859775393, - 2400959708, - 2840853838 -]); -var Kr160 = /* @__PURE__ */ Uint32Array.from([ - 1352829926, - 1548603684, - 1836072691, - 2053994217, - 0 -]); -function ripemd_f(group, x, y, z) { - if (group === 0) - return x ^ y ^ z; - if (group === 1) - return x & y | ~x & z; - if (group === 2) - return (x | ~y) ^ z; - if (group === 3) - return x & z | y & ~z; - return x ^ (y | ~z); -} -var BUF_160 = /* @__PURE__ */ new Uint32Array(16); -var _RIPEMD160 = class extends HashMD { - constructor() { - super(64, 20, 8, true); - __publicField(this, "h0", 1732584193 | 0); - __publicField(this, "h1", 4023233417 | 0); - __publicField(this, "h2", 2562383102 | 0); - __publicField(this, "h3", 271733878 | 0); - __publicField(this, "h4", 3285377520 | 0); - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - BUF_160[i] = view.getUint32(offset, true); - let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl160[group], hbr = Kr160[group]; - const rl = idxL[group], rr = idxR[group]; - const sl = shiftsL160[group], sr = shiftsR160[group]; - for (let i = 0; i < 16; i++) { - const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0; - al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; - } - for (let i = 0; i < 16; i++) { - const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0; - ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; - } - } - this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0); - } - roundClean() { - clean(BUF_160); - } - destroy() { - this.destroyed = true; - clean(this.buffer); - this.set(0, 0, 0, 0, 0); - } -}; -var ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160()); - -// node_modules/@scure/bip32/index.js -var Point = /* @__PURE__ */ (() => secp256k1.Point)(); -var Fn = /* @__PURE__ */ (() => Point.Fn)(); -var base58check = /* @__PURE__ */ createBase58check(sha256); -var MASTER_SECRET = /* @__PURE__ */ (() => { - return Uint8Array.from("Bitcoin seed".split(""), (char) => char.charCodeAt(0)); -})(); -var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 }; -var HARDENED_OFFSET = 2147483648; -var hash160 = (data) => ripemd160(sha256(data)); -var fromU32 = (data) => createView(data).getUint32(0, false); -var toU32 = (n) => { - if (typeof n !== "number") - throw new TypeError("invalid number, should be from 0 to 2**32-1, got " + n); - if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) - throw new RangeError("invalid number, should be from 0 to 2**32-1, got " + n); - const buf = new Uint8Array(4); - createView(buf).setUint32(0, n, false); - return buf; -}; -var HDKey = class _HDKey { - constructor(opt) { - __publicField(this, "versions"); - __publicField(this, "depth", 0); - __publicField(this, "index", 0); - __publicField(this, "chainCode", null); - __publicField(this, "parentFingerprint", 0); - __publicField(this, "_privateKey"); - __publicField(this, "_publicKey"); - __publicField(this, "pubHash"); - if (!opt || typeof opt !== "object") { - throw new Error("HDKey.constructor must not be called directly"); - } - this.versions = opt.versions || BITCOIN_VERSIONS; - this.depth = opt.depth || 0; - this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null; - this.index = opt.index || 0; - this.parentFingerprint = opt.parentFingerprint || 0; - if (!this.depth) { - if (this.parentFingerprint || this.index) { - throw new Error("HDKey: zero depth with non-zero index/parent fingerprint"); - } - } - if (this.depth > 255) { - throw new Error("HDKey: depth exceeds the serializable value 255"); - } - if (opt.publicKey && opt.privateKey) { - throw new Error("HDKey: publicKey and privateKey at same time."); - } - if (opt.privateKey) { - if (!secp256k1.utils.isValidSecretKey(opt.privateKey)) - throw new Error("Invalid private key"); - this._privateKey = Uint8Array.from(opt.privateKey); - this._publicKey = secp256k1.getPublicKey(this._privateKey, true); - } else if (opt.publicKey) { - this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); - } else { - throw new Error("HDKey: no public or private key provided"); - } - this.pubHash = hash160(this._publicKey); - } - get fingerprint() { - if (!this.pubHash) { - throw new Error("No publicKey set!"); - } - return fromU32(this.pubHash); - } - get identifier() { - return this.pubHash; - } - get pubKeyHash() { - return this.pubHash; - } - // Returns the live private key buffer for this instance. - // Copy it first if you need an immutable snapshot. - get privateKey() { - return this._privateKey || null; - } - get publicKey() { - return this._publicKey || null; - } - get privateExtendedKey() { - const priv = this._privateKey; - if (!priv) { - throw new Error("No private key"); - } - return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))); - } - get publicExtendedKey() { - if (!this._publicKey) { - throw new Error("No public key"); - } - return base58check.encode(this.serialize(this.versions.public, this._publicKey)); - } - static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { - abytes(seed); - if (8 * seed.length < 128 || 8 * seed.length > 512) { - throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length); - } - const I = hmac(sha512, MASTER_SECRET, seed); - const privateKey = I.slice(0, 32); - const chainCode = I.slice(32); - return new _HDKey({ versions, chainCode, privateKey }); - } - static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { - const keyBuffer = base58check.decode(base58key); - const keyView = createView(keyBuffer); - const version = keyView.getUint32(0, false); - const opt = { - versions, - depth: keyBuffer[4], - parentFingerprint: keyView.getUint32(5, false), - index: keyView.getUint32(9, false), - chainCode: keyBuffer.slice(13, 45) - }; - const key = keyBuffer.slice(45); - const isPriv = key[0] === 0; - if (version !== versions[isPriv ? "private" : "public"]) { - throw new Error("Version mismatch"); - } - if (isPriv) { - return new _HDKey({ ...opt, privateKey: key.slice(1) }); - } else { - return new _HDKey({ ...opt, publicKey: key }); - } - } - static fromJSON(json) { - return _HDKey.fromExtendedKey(json.xpriv); - } - derive(path) { - if (!/^[mM]'?/.test(path)) { - throw new Error('Path must start with "m" or "M"'); - } - if (/^[mM]'?$/.test(path)) { - return this; - } - const parts = path.replace(/^[mM]'?\//, "").split("/"); - let child = this; - for (const c of parts) { - const m = /^(\d+)('?)$/.exec(c); - const m1 = m && m[1]; - if (!m || m.length !== 3 || typeof m1 !== "string") - throw new Error("invalid child index: " + c); - let idx = +m1; - if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { - throw new Error("Invalid index"); - } - if (m[2] === "'") { - idx += HARDENED_OFFSET; - } - child = child.deriveChild(idx); - } - return child; - } - /** - * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it. - */ - deriveChild(index, _I) { - if (!this._publicKey || !this.chainCode) { - throw new Error("No publicKey or chainCode set"); - } - let data = toU32(index); - if (index >= HARDENED_OFFSET) { - const priv = this._privateKey; - if (!priv) { - throw new Error("Could not derive hardened child key"); - } - data = concatBytes(Uint8Array.of(0), priv, data); - } else { - data = concatBytes(this._publicKey, data); - } - const out = _I || hmac(sha512, this.chainCode, data); - abytes(out, 64); - const childTweak = out.slice(0, 32); - const chainCode = out.slice(32); - const opt = { - versions: this.versions, - chainCode, - depth: this.depth + 1, - parentFingerprint: this.fingerprint, - index - }; - if (opt.depth > 255) { - throw new Error("HDKey: depth exceeds the serializable value 255"); - } - try { - const ctweak = Fn.fromBytes(childTweak); - if (this._privateKey) { - const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak); - if (!Fn.isValidNot0(added)) { - throw new Error("The tweak was out of range or the resulted private key is invalid"); - } - opt.privateKey = Fn.toBytes(added); - } else { - const point = Point.fromBytes(this._publicKey); - const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak)); - if (added.equals(Point.ZERO)) { - throw new Error("The tweak was equal to negative P, which made the result key invalid"); - } - opt.publicKey = added.toBytes(true); - } - return new _HDKey(opt); - } catch (err) { - return this.deriveChild(index + 1); - } - } - sign(hash) { - if (!this._privateKey) { - throw new Error("No privateKey set!"); - } - abytes(hash, 32); - return secp256k1.sign(hash, this._privateKey, { prehash: false }); - } - verify(hash, signature) { - abytes(hash, 32); - abytes(signature, 64); - if (!this._publicKey) { - throw new Error("No publicKey set!"); - } - return secp256k1.verify(signature, hash, this._publicKey, { prehash: false }); - } - wipePrivateData() { - if (this._privateKey) { - this._privateKey.fill(0); - this._privateKey = void 0; - } - return this; - } - toJSON() { - return { - xpriv: this.privateExtendedKey, - xpub: this.publicExtendedKey - }; - } - serialize(version, key) { - if (!this.chainCode) { - throw new Error("No chainCode set"); - } - abytes(key, 33); - return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); - } -}; - -// node_modules/@noble/hashes/hkdf.js -function extract(hash, ikm, salt) { - ahash(hash); - if (salt === void 0) - salt = new Uint8Array(hash.outputLen); - return hmac(hash, salt, ikm); -} -var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); -var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); -function expand(hash, prk, info, length = 32) { - ahash(hash); - anumber(length, "length"); - abytes(prk, void 0, "prk"); - const olen = hash.outputLen; - if (prk.length < olen) - throw new Error('"prk" must be at least HashLen octets'); - if (length > 255 * olen) - throw new Error("Length must be <= 255*HashLen"); - const blocks = Math.ceil(length / olen); - if (info === void 0) - info = EMPTY_BUFFER; - else - abytes(info, void 0, "info"); - const okm = new Uint8Array(blocks * olen); - const HMAC = hmac.create(hash, prk); - const HMACTmp = HMAC._cloneInto(); - const T = new Uint8Array(HMAC.outputLen); - for (let counter = 0; counter < blocks; counter++) { - HKDF_COUNTER[0] = counter + 1; - HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T); - okm.set(T, olen * counter); - HMAC._cloneInto(HMACTmp); - } - HMAC.destroy(); - HMACTmp.destroy(); - clean(T, HKDF_COUNTER); - return okm.slice(0, length); -} -var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); - -// node_modules/@noble/hashes/sha3.js -var _0n5 = BigInt(0); -var _1n5 = BigInt(1); -var _2n4 = BigInt(2); -var _7n2 = BigInt(7); -var _256n = BigInt(256); -var _0x71n = BigInt(113); -var SHA3_PI = []; -var SHA3_ROTL = []; -var _SHA3_IOTA = []; -for (let round = 0, R = _1n5, x = 1, y = 0; round < 24; round++) { - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); - let t = _0n5; - for (let j = 0; j < 7; j++) { - R = (R << _1n5 ^ (R >> _7n2) * _0x71n) % _256n; - if (R & _2n4) - t ^= _1n5 << (_1n5 << BigInt(j)) - _1n5; - } - _SHA3_IOTA.push(t); -} -var IOTAS = split(_SHA3_IOTA, true); -var SHA3_IOTA_H = IOTAS[0]; -var SHA3_IOTA_L = IOTAS[1]; -var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); -var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); -function keccakP(s, rounds = 24) { - anumber(rounds, "rounds"); - if (rounds < 1 || rounds > 24) - throw new Error('"rounds" expected integer 1..24'); - const B = new Uint32Array(5 * 2); - for (let round = 24 - rounds; round < 24; round++) { - for (let x = 0; x < 10; x++) - B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; - for (let x = 0; x < 10; x += 2) { - const idx1 = (x + 8) % 10; - const idx0 = (x + 2) % 10; - const B0 = B[idx0]; - const B1 = B[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0; y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - for (let y = 0; y < 50; y += 10) { - const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3]; - s[y] ^= ~s[y + 2] & s[y + 4]; - s[y + 1] ^= ~s[y + 3] & s[y + 5]; - s[y + 2] ^= ~s[y + 4] & s[y + 6]; - s[y + 3] ^= ~s[y + 5] & s[y + 7]; - s[y + 4] ^= ~s[y + 6] & s[y + 8]; - s[y + 5] ^= ~s[y + 7] & s[y + 9]; - s[y + 6] ^= ~s[y + 8] & b0; - s[y + 7] ^= ~s[y + 9] & b1; - s[y + 8] ^= ~b0 & b2; - s[y + 9] ^= ~b1 & b3; - } - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - clean(B); -} -var Keccak = class _Keccak { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - __publicField(this, "state"); - __publicField(this, "pos", 0); - __publicField(this, "posOut", 0); - __publicField(this, "finished", false); - __publicField(this, "state32"); - __publicField(this, "destroyed", false); - __publicField(this, "blockLen"); - __publicField(this, "suffix"); - __publicField(this, "outputLen"); - __publicField(this, "canXOF"); - __publicField(this, "enableXOF", false); - __publicField(this, "rounds"); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.canXOF = enableXOF; - this.rounds = rounds; - anumber(outputLen, "outputLen"); - if (!(0 < blockLen && blockLen < 200)) - throw new Error("only keccak-f1600 function is supported"); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - clone() { - return this._cloneInto(); - } - keccak() { - swap32IfBE(this.state32); - keccakP(this.state32, this.rounds); - swap32IfBE(this.state32); - this.posOut = 0; - this.pos = 0; - } - update(data) { - aexists(this); - abytes(data); - const { blockLen, state } = this; - const len = data.length; - for (let pos = 0; pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); - } - writeInto(out) { - aexists(this, false); - abytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); - } - xof(bytes) { - anumber(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - aoutput(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out.subarray(0, this.outputLen)); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.outputLen); - this.digestInto(out); - return out; - } - destroy() { - this.destroyed = true; - clean(this.state); - } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.blockLen = blockLen; - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.canXOF = this.canXOF; - to.destroyed = this.destroyed; - return to; - } -}; -var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); -var sha3_256 = /* @__PURE__ */ genKeccak( - 6, - 136, - 32, - /* @__PURE__ */ oidNist(8) -); -var sha3_512 = /* @__PURE__ */ genKeccak( - 6, - 72, - 64, - /* @__PURE__ */ oidNist(10) -); -var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info); -var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11)); -var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12)); - -// node_modules/@noble/post-quantum/utils.js -var abytesDoc = abytes; -var randomBytes3 = randomBytes; -function equalBytes(a, b) { - if (a.length !== b.length) - return false; - let diff = 0; - for (let i = 0; i < a.length; i++) - diff |= a[i] ^ b[i]; - return diff === 0; -} -function copyBytes2(bytes) { - return Uint8Array.from(abytes(bytes)); -} -function validateOpts(opts2) { - if (Object.prototype.toString.call(opts2) !== "[object Object]") - throw new TypeError("expected valid options object"); -} -function validateVerOpts(opts2) { - validateOpts(opts2); - if (opts2.context !== void 0) - abytes(opts2.context, void 0, "opts.context"); -} -function validateSigOpts2(opts2) { - validateVerOpts(opts2); - if (opts2.extraEntropy !== false && opts2.extraEntropy !== void 0) - abytes(opts2.extraEntropy, void 0, "opts.extraEntropy"); -} -function splitCoder(label, ...lengths) { - const getLength = (c) => typeof c === "number" ? c : c.bytesLen; - const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0); - return { - bytesLen, - encode: (bufs) => { - const res = new Uint8Array(bytesLen); - for (let i = 0, pos = 0; i < lengths.length; i++) { - const c = lengths[i]; - const l = getLength(c); - const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]); - abytes(b, l, label); - res.set(b, pos); - if (typeof c !== "number") - b.fill(0); - pos += l; - } - return res; - }, - decode: (buf) => { - abytes(buf, bytesLen, label); - const res = []; - for (const c of lengths) { - const l = getLength(c); - const b = buf.subarray(0, l); - res.push(typeof c === "number" ? b : c.decode(b)); - buf = buf.subarray(l); - } - return res; - } - }; -} -function vecCoder(c, vecLen) { - const coder = c; - const bytesLen = vecLen * coder.bytesLen; - return { - bytesLen, - encode: (u) => { - if (u.length !== vecLen) - throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`); - const res = new Uint8Array(bytesLen); - for (let i = 0, pos = 0; i < u.length; i++) { - const b = coder.encode(u[i]); - res.set(b, pos); - b.fill(0); - pos += b.length; - } - return res; - }, - decode: (a) => { - abytes(a, bytesLen); - const r = []; - for (let i = 0; i < a.length; i += coder.bytesLen) - r.push(coder.decode(a.subarray(i, i + coder.bytesLen))); - return r; - } - }; -} -function cleanBytes(...list) { - for (const t of list) { - if (Array.isArray(t)) - for (const b of t) - b.fill(0); - else - t.fill(0); - } -} -function getMask(bits) { - if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) - throw new RangeError(`expected bits in [0..32], got ${bits}`); - return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0; -} -var EMPTY = /* @__PURE__ */ Uint8Array.of(); -function getMessage(msg, ctx = EMPTY) { - abytes(msg); - abytes(ctx); - if (ctx.length > 255) - throw new RangeError("context should be 255 bytes or less"); - return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg); -} -var oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2]); -function checkHash(hash, requiredStrength = 0) { - if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP)) - throw new Error("hash.oid is invalid: expected NIST hash"); - const collisionResistance = hash.outputLen * 8 / 2; - if (requiredStrength > collisionResistance) { - throw new Error("Pre-hash security strength too low: " + collisionResistance + ", required: " + requiredStrength); - } -} -function getMessagePrehash(hash, msg, ctx = EMPTY) { - abytes(msg); - abytes(ctx); - if (ctx.length > 255) - throw new RangeError("context should be 255 bytes or less"); - const hashed = hash(msg); - return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed); -} - -// node_modules/@noble/post-quantum/_crystals.js -var genCrystals = (opts2) => { - const { newPoly: newPoly2, N: N3, Q: Q3, F: F3, ROOT_OF_UNITY: ROOT_OF_UNITY3, brvBits, isKyber } = opts2; - const mod2 = (a, modulo = Q3) => { - const result = a % modulo | 0; - return (result >= 0 ? result | 0 : modulo + result | 0) | 0; - }; - const smod = (a, modulo = Q3) => { - const r = mod2(a, modulo) | 0; - return (r > modulo >> 1 ? r - modulo | 0 : r) | 0; - }; - function getZettas() { - const out = newPoly2(N3); - for (let i = 0; i < N3; i++) { - const b = reverseBits(i, brvBits); - const p = BigInt(ROOT_OF_UNITY3) ** BigInt(b) % BigInt(Q3); - out[i] = Number(p) | 0; - } - return out; - } - const nttZetas = getZettas(); - const field = { - add: (a, b) => mod2((a | 0) + (b | 0)) | 0, - sub: (a, b) => mod2((a | 0) - (b | 0)) | 0, - mul: (a, b) => mod2((a | 0) * (b | 0)) | 0, - inv: (_a) => { - throw new Error("not implemented"); - } - }; - const nttOpts = { - N: N3, - roots: nttZetas, - invertButterflies: true, - skipStages: isKyber ? 1 : 0, - brp: false - }; - const dif = FFTCore(field, { dit: false, ...nttOpts }); - const dit = FFTCore(field, { dit: true, ...nttOpts }); - const NTT = { - encode: (r) => { - return dif(r); - }, - decode: (r) => { - dit(r); - for (let i = 0; i < r.length; i++) - r[i] = mod2(F3 * r[i]); - return r; - } - }; - const bitsCoder = (d, c) => { - const mask = getMask(d); - const bytesLen = d * (N3 / 8); - return { - bytesLen, - encode: (poly_) => { - const poly = poly_; - const r = new Uint8Array(bytesLen); - for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { - buf |= (c.encode(poly[i]) & mask) << bufLen; - bufLen += d; - for (; bufLen >= 8; bufLen -= 8, buf >>= 8) - r[pos++] = buf & getMask(bufLen); - } - return r; - }, - decode: (bytes) => { - const r = newPoly2(N3); - for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { - buf |= bytes[i] << bufLen; - bufLen += 8; - for (; bufLen >= d; bufLen -= d, buf >>= d) - r[pos++] = c.decode(buf & mask); - } - return r; - } - }; - }; - return { - mod: mod2, - smod, - nttZetas, - NTT: { - encode: (r) => NTT.encode(r), - decode: (r) => NTT.decode(r) - }, - bitsCoder - }; -}; -var createXofShake = (shake) => (seed, blockLen) => { - if (!blockLen) - blockLen = shake.blockLen; - const _seed = new Uint8Array(seed.length + 2); - _seed.set(seed); - const seedLen = seed.length; - const buf = new Uint8Array(blockLen); - let h = shake.create({}); - let calls = 0; - let xofs = 0; - return { - stats: () => ({ calls, xofs }), - get: (x, y) => { - _seed[seedLen + 0] = x; - _seed[seedLen + 1] = y; - h.destroy(); - h = shake.create({}).update(_seed); - calls++; - return () => { - xofs++; - return h.xofInto(buf); - }; - }, - clean: () => { - h.destroy(); - cleanBytes(buf, _seed); - } - }; -}; -var XOF128 = /* @__PURE__ */ createXofShake(shake128); -var XOF256 = /* @__PURE__ */ createXofShake(shake256); - -// node_modules/@noble/post-quantum/ml-dsa.js -function validateInternalOpts(opts2) { - validateOpts(opts2); - if (opts2.externalMu !== void 0) - abool(opts2.externalMu, "opts.externalMu"); -} -var N = 256; -var Q = 8380417; -var ROOT_OF_UNITY = 1753; -var F = 8347681; -var D = 13; -var GAMMA2_1 = Math.floor((Q - 1) / 88) | 0; -var GAMMA2_2 = Math.floor((Q - 1) / 32) | 0; -var PARAMS = /* @__PURE__ */ (() => Object.freeze({ - 2: Object.freeze({ - K: 4, - L: 4, - D, - GAMMA1: 2 ** 17, - GAMMA2: GAMMA2_1, - TAU: 39, - ETA: 2, - OMEGA: 80 - }), - 3: Object.freeze({ - K: 6, - L: 5, - D, - GAMMA1: 2 ** 19, - GAMMA2: GAMMA2_2, - TAU: 49, - ETA: 4, - OMEGA: 55 - }), - 5: Object.freeze({ - K: 8, - L: 7, - D, - GAMMA1: 2 ** 19, - GAMMA2: GAMMA2_2, - TAU: 60, - ETA: 2, - OMEGA: 75 - }) -}))(); -var newPoly = (n) => new Int32Array(n); -var crystals = /* @__PURE__ */ genCrystals({ - N, - Q, - F, - ROOT_OF_UNITY, - newPoly, - isKyber: false, - brvBits: 8 -}); -var id = (n) => n; -var polyCoder = (d, compress2 = id, verify = id) => crystals.bitsCoder(d, { - encode: (i) => compress2(verify(i)), - decode: (i) => verify(compress2(i)) -}); -var polyAdd = (a_, b_) => { - const a = a_; - const b = b_; - for (let i = 0; i < a.length; i++) - a[i] = crystals.mod(a[i] + b[i]); - return a; -}; -var polySub = (a_, b_) => { - const a = a_; - const b = b_; - for (let i = 0; i < a.length; i++) - a[i] = crystals.mod(a[i] - b[i]); - return a; -}; -var polyShiftl = (p_) => { - const p = p_; - for (let i = 0; i < N; i++) - p[i] <<= D; - return p; -}; -var polyChknorm = (p_, B) => { - const p = p_; - for (let i = 0; i < N; i++) - if (Math.abs(crystals.smod(p[i])) >= B) - return true; - return false; -}; -var MultiplyNTTs = (a_, b_) => { - const a = a_; - const b = b_; - const c = newPoly(N); - for (let i = 0; i < a.length; i++) - c[i] = crystals.mod(a[i] * b[i]); - return c; -}; -function RejNTTPoly(xof_) { - const xof = xof_; - const r = newPoly(N); - for (let j = 0; j < N; ) { - const b = xof(); - if (b.length % 3) - throw new Error("RejNTTPoly: unaligned block"); - for (let i = 0; j < N && i <= b.length - 3; i += 3) { - const t = (b[i + 0] | b[i + 1] << 8 | b[i + 2] << 16) & 8388607; - if (t < Q) - r[j++] = t; - } - } - return r; -} -function getDilithium(opts_) { - const opts2 = opts_; - const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts2; - const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128: XOF1282, XOF256: XOF2562, securityLevel } = opts2; - if (![2, 4].includes(ETA)) - throw new Error("Wrong ETA"); - if (![1 << 17, 1 << 19].includes(GAMMA1)) - throw new Error("Wrong GAMMA1"); - if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) - throw new Error("Wrong GAMMA2"); - const BETA = TAU * ETA; - const decompose = (r) => { - const rPlus = crystals.mod(r); - const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0; - if (rPlus - r0 === Q - 1) - return { r1: 0 | 0, r0: r0 - 1 | 0 }; - const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0; - return { r1, r0 }; - }; - const HighBits = (r) => decompose(r).r1; - const LowBits = (r) => decompose(r).r0; - const MakeHint = (z, r) => { - const res0 = z <= GAMMA2 || z > Q - GAMMA2 || z === Q - GAMMA2 && r === 0 ? 0 : 1; - return res0; - }; - const UseHint = (h, r) => { - const m = Math.floor((Q - 1) / (2 * GAMMA2)); - const { r1, r0 } = decompose(r); - if (h === 1) - return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0; - return r1 | 0; - }; - const Power2Round = (r) => { - const rPlus = crystals.mod(r); - const r0 = crystals.smod(rPlus, 2 ** D) | 0; - return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 }; - }; - const hintCoder = { - bytesLen: OMEGA + K, - encode: (h_) => { - const h = h_; - if (h === false) - throw new Error("hint.encode: hint is false"); - const res = new Uint8Array(OMEGA + K); - for (let i = 0, k = 0; i < K; i++) { - for (let j = 0; j < N; j++) - if (h[i][j] !== 0) - res[k++] = j; - res[OMEGA + i] = k; - } - return res; - }, - decode: (buf) => { - const h = []; - let k = 0; - for (let i = 0; i < K; i++) { - const hi = newPoly(N); - if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA) - return false; - for (let j = k; j < buf[OMEGA + i]; j++) { - if (j > k && buf[j] <= buf[j - 1]) - return false; - hi[buf[j]] = 1; - } - k = buf[OMEGA + i]; - h.push(hi); - } - for (let j = k; j < OMEGA; j++) - if (buf[j] !== 0) - return false; - return h; - } - }; - const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => { - if (!(-ETA <= i && i <= ETA)) - throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`); - return i; - }); - const T0Coder = polyCoder(13, (i) => (1 << D - 1) - i); - const T1Coder = polyCoder(10); - const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i)); - const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4); - const W1Vec = vecCoder(W1Coder, K); - const publicCoder = splitCoder("publicKey", 32, vecCoder(T1Coder, K)); - const secretCoder = splitCoder("secretKey", 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K)); - const sigCoder = splitCoder("signature", C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder); - const CoefFromHalfByte = ETA === 2 ? (n) => n < 15 ? 2 - n % 5 : false : (n) => n < 9 ? 4 - n : false; - function RejBoundedPoly(xof_) { - const xof = xof_; - const r = newPoly(N); - for (let j = 0; j < N; ) { - const b = xof(); - for (let i = 0; j < N && i < b.length; i += 1) { - const d1 = CoefFromHalfByte(b[i] & 15); - const d2 = CoefFromHalfByte(b[i] >> 4 & 15); - if (d1 !== false) - r[j++] = d1; - if (j < N && d2 !== false) - r[j++] = d2; - } - } - return r; - } - const SampleInBall = (seed) => { - const pre = newPoly(N); - const s = shake256.create({}).update(seed); - const buf = new Uint8Array(shake256.blockLen); - s.xofInto(buf); - const masks = buf.slice(0, 8); - for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) { - let b = i + 1; - for (; b > i; ) { - b = buf[pos++]; - if (pos < shake256.blockLen) - continue; - s.xofInto(buf); - pos = 0; - } - pre[i] = pre[b]; - pre[b] = 1 - ((masks[maskPos] >> maskBit++ & 1) << 1); - if (maskBit >= 8) { - maskPos++; - maskBit = 0; - } - } - return pre; - }; - const polyPowerRound = (p_) => { - const p = p_; - const res0 = newPoly(N); - const res1 = newPoly(N); - for (let i = 0; i < p.length; i++) { - const { r0, r1 } = Power2Round(p[i]); - res0[i] = r0; - res1[i] = r1; - } - return { r0: res0, r1: res1 }; - }; - const polyUseHint = (u_, h_) => { - const u = u_; - const h = h_; - for (let i = 0; i < N; i++) - u[i] = UseHint(h[i], u[i]); - return u; - }; - const polyMakeHint = (a_, b_) => { - const a = a_; - const b = b_; - const v = newPoly(N); - let cnt = 0; - for (let i = 0; i < N; i++) { - const h = MakeHint(a[i], b[i]); - v[i] = h; - cnt += h; - } - return { v, cnt }; - }; - const signRandBytes = 32; - const seedCoder = splitCoder("seed", 32, 64, 32); - const internal = Object.freeze({ - info: Object.freeze({ type: "internal-ml-dsa" }), - lengths: Object.freeze({ - secretKey: secretCoder.bytesLen, - publicKey: publicCoder.bytesLen, - seed: 32, - signature: sigCoder.bytesLen, - signRand: signRandBytes - }), - keygen: (seed) => { - const seedDst = new Uint8Array(32 + 2); - const randSeed = seed === void 0; - if (randSeed) - seed = randomBytes3(32); - abytesDoc(seed, 32, "seed"); - seedDst.set(seed); - if (randSeed) - cleanBytes(seed); - seedDst[32] = K; - seedDst[33] = L; - const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen })); - const xofPrime = XOF2562(rhoPrime); - const s1 = []; - for (let i = 0; i < L; i++) - s1.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255))); - const s2 = []; - for (let i = L; i < L + K; i++) - s2.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255))); - const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice())); - const t0 = []; - const t1 = []; - const xof = XOF1282(rho); - const t = newPoly(N); - for (let i = 0; i < K; i++) { - cleanBytes(t); - for (let j = 0; j < L; j++) { - const aij = RejNTTPoly(xof.get(j, i)); - polyAdd(t, MultiplyNTTs(aij, s1Hat[j])); - } - crystals.NTT.decode(t); - const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); - t0.push(r0); - t1.push(r1); - } - const publicKey = publicCoder.encode([rho, t1]); - const tr = shake256(publicKey, { dkLen: TR_BYTES }); - const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]); - xof.clean(); - xofPrime.clean(); - cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst); - return { - publicKey, - secretKey - }; - }, - getPublicKey: (secretKey) => { - const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey); - const xof = XOF1282(rho); - const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice())); - const t1 = []; - const tmp = newPoly(N); - for (let i = 0; i < K; i++) { - tmp.fill(0); - for (let j = 0; j < L; j++) { - const aij = RejNTTPoly(xof.get(j, i)); - polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); - } - crystals.NTT.decode(tmp); - polyAdd(tmp, s2[i]); - const { r1 } = polyPowerRound(tmp); - t1.push(r1); - } - xof.clean(); - cleanBytes(tmp, s1Hat, _t0, s1, s2); - return publicCoder.encode([rho, t1]); - }, - // NOTE: random is optional. - sign: (msg, secretKey, opts3 = {}) => { - validateSigOpts2(opts3); - validateInternalOpts(opts3); - let { extraEntropy: random, externalMu = false } = opts3; - const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey); - const A = []; - const xof = XOF1282(rho); - for (let i = 0; i < K; i++) { - const pv = []; - for (let j = 0; j < L; j++) - pv.push(RejNTTPoly(xof.get(j, i))); - A.push(pv); - } - xof.clean(); - for (let i = 0; i < L; i++) - crystals.NTT.encode(s1[i]); - for (let i = 0; i < K; i++) { - crystals.NTT.encode(s2[i]); - crystals.NTT.encode(t0[i]); - } - const mu = externalMu ? msg : ( - // 6: ยต โ† H(tr||M, 512) - // โ–ท Compute message representative ยต - shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest() - ); - const rnd = random === false ? new Uint8Array(32) : random === void 0 ? randomBytes3(signRandBytes) : random; - abytesDoc(rnd, 32, "extraEntropy"); - const rhoprime = shake256.create({ dkLen: CRH_BYTES }).update(_K).update(rnd).update(mu).digest(); - abytesDoc(rhoprime, CRH_BYTES); - const x256 = XOF2562(rhoprime, ZCoder.bytesLen); - main_loop: for (let kappa = 0; ; ) { - const y = []; - for (let i = 0; i < L; i++, kappa++) - y.push(ZCoder.decode(x256.get(kappa & 255, kappa >> 8)())); - const z = y.map((i) => crystals.NTT.encode(i.slice())); - const w = []; - for (let i = 0; i < K; i++) { - const wi = newPoly(N); - for (let j = 0; j < L; j++) - polyAdd(wi, MultiplyNTTs(A[i][j], z[j])); - crystals.NTT.decode(wi); - w.push(wi); - } - const w1 = w.map((j) => j.map(HighBits)); - const cTilde = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(w1)).digest(); - const cHat = crystals.NTT.encode(SampleInBall(cTilde)); - const cs1 = s1.map((i) => MultiplyNTTs(i, cHat)); - for (let i = 0; i < L; i++) { - polyAdd(crystals.NTT.decode(cs1[i]), y[i]); - if (polyChknorm(cs1[i], GAMMA1 - BETA)) - continue main_loop; - } - let cnt = 0; - const h = []; - for (let i = 0; i < K; i++) { - const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); - const r0 = polySub(w[i], cs2).map(LowBits); - if (polyChknorm(r0, GAMMA2 - BETA)) - continue main_loop; - const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); - if (polyChknorm(ct0, GAMMA2)) - continue main_loop; - polyAdd(r0, ct0); - const hint = polyMakeHint(r0, w1[i]); - h.push(hint.v); - cnt += hint.cnt; - } - if (cnt > OMEGA) - continue; - x256.clean(); - const res = sigCoder.encode([cTilde, cs1, h]); - cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A); - if (!externalMu) - cleanBytes(mu); - return res; - } - throw new Error("Unreachable code path reached, report this error"); - }, - verify: (sig, msg, publicKey, opts3 = {}) => { - validateInternalOpts(opts3); - const { externalMu = false } = opts3; - const [rho, t1] = publicCoder.decode(publicKey); - const tr = shake256(publicKey, { dkLen: TR_BYTES }); - if (sig.length !== sigCoder.bytesLen) - return false; - const [cTilde, z, h] = sigCoder.decode(sig); - if (h === false) - return false; - for (let i = 0; i < L; i++) - if (polyChknorm(z[i], GAMMA1 - BETA)) - return false; - const mu = externalMu ? msg : ( - // 7: ยต โ† H(tr||M, 512) - shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest() - ); - const c = crystals.NTT.encode(SampleInBall(cTilde)); - const zNtt = z.map((i) => i.slice()); - for (let i = 0; i < L; i++) - crystals.NTT.encode(zNtt[i]); - const wTick1 = []; - const xof = XOF1282(rho); - for (let i = 0; i < K; i++) { - const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); - const Az = newPoly(N); - for (let j = 0; j < L; j++) { - const aij = RejNTTPoly(xof.get(j, i)); - polyAdd(Az, MultiplyNTTs(aij, zNtt[j])); - } - const wApprox = crystals.NTT.decode(polySub(Az, ct12d)); - wTick1.push(polyUseHint(wApprox, h[i])); - } - xof.clean(); - const c2 = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(wTick1)).digest(); - for (const t of h) { - const sum = t.reduce((acc, i) => acc + i, 0); - if (!(sum <= OMEGA)) - return false; - } - for (const t of z) - if (polyChknorm(t, GAMMA1 - BETA)) - return false; - return equalBytes(cTilde, c2); - } - }); - return Object.freeze({ - info: Object.freeze({ type: "ml-dsa" }), - internal, - securityLevel, - keygen: internal.keygen, - lengths: internal.lengths, - getPublicKey: internal.getPublicKey, - sign: (msg, secretKey, opts3 = {}) => { - validateSigOpts2(opts3); - const M = getMessage(msg, opts3.context); - const res = internal.sign(M, secretKey, opts3); - cleanBytes(M); - return res; - }, - verify: (sig, msg, publicKey, opts3 = {}) => { - validateVerOpts(opts3); - return internal.verify(sig, getMessage(msg, opts3.context), publicKey); - }, - prehash: (hash) => { - checkHash(hash, securityLevel); - return Object.freeze({ - info: Object.freeze({ type: "hashml-dsa" }), - securityLevel, - lengths: internal.lengths, - keygen: internal.keygen, - getPublicKey: internal.getPublicKey, - sign: (msg, secretKey, opts3 = {}) => { - validateSigOpts2(opts3); - const M = getMessagePrehash(hash, msg, opts3.context); - const res = internal.sign(M, secretKey, opts3); - cleanBytes(M); - return res; - }, - verify: (sig, msg, publicKey, opts3 = {}) => { - validateVerOpts(opts3); - return internal.verify(sig, getMessagePrehash(hash, msg, opts3.context), publicKey); - } - }); - } - }); -} -var ml_dsa65 = /* @__PURE__ */ (() => getDilithium({ - ...PARAMS[3], - CRH_BYTES: 64, - TR_BYTES: 64, - C_TILDE_BYTES: 48, - XOF128, - XOF256, - securityLevel: 192 -}))(); - -// node_modules/@noble/post-quantum/slh-dsa.js -var PARAMS2 = /* @__PURE__ */ (() => Object.freeze({ - "128f": Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }), - "128s": Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }), - "192f": Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }), - "192s": Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }), - "256f": Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }), - "256s": Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }) -}))(); -var AddressType = { - WOTS: 0, - WOTSPK: 1, - HASHTREE: 2, - FORSTREE: 3, - FORSPK: 4, - WOTSPRF: 5, - FORSPRF: 6 -}; -function hexToNumber2(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - return BigInt(hex === "" ? "0" : "0x" + hex); -} -function bytesToNumberBE2(bytes) { - return hexToNumber2(bytesToHex(bytes)); -} -function numberToBytesBE2(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, "0")); -} -var base2b = (outLen, b) => { - const mask = getMask(b); - return (bytes) => { - const baseB = new Uint32Array(outLen); - for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) { - while (bits < b) { - total = total << 8 | bytes[pos++]; - bits += 8; - } - bits -= b; - baseB[out] = total >>> bits & mask; - } - return baseB; - }; -}; -function getMaskBig(bits) { - return (1n << BigInt(bits)) - 1n; -} -function gen(opts2, hashOpts_) { - const hashOpts = hashOpts_; - const { N: N3, W, H, D: D2, K, A, securityLevel } = opts2; - const getContext = hashOpts.getContext(opts2); - if (W !== 16) - throw new Error("Unsupported Winternitz parameter"); - const WOTS_LOGW = 4; - const WOTS_LEN1 = Math.floor(8 * N3 / WOTS_LOGW); - const WOTS_LEN2 = N3 <= 8 ? 2 : N3 <= 136 ? 3 : 4; - const TREE_HEIGHT = Math.floor(H / D2); - const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2; - let ADDR_BYTES = 22; - let OFFSET_LAYER = 0; - let OFFSET_TREE = 1; - let OFFSET_TYPE = 9; - let OFFSET_KP_ADDR2 = 12; - let OFFSET_KP_ADDR1 = 13; - let OFFSET_CHAIN_ADDR = 17; - let OFFSET_TREE_INDEX = 18; - let OFFSET_HASH_ADDR = 21; - if (!hashOpts.isCompressed) { - ADDR_BYTES = 32; - OFFSET_LAYER += 3; - OFFSET_TREE += 7; - OFFSET_TYPE += 10; - OFFSET_KP_ADDR2 += 10; - OFFSET_KP_ADDR1 += 10; - OFFSET_CHAIN_ADDR += 10; - OFFSET_TREE_INDEX += 10; - OFFSET_HASH_ADDR += 10; - } - const setAddr = (opts3, addr = new Uint8Array(ADDR_BYTES)) => { - const { type, height, tree, layer, index, chain: chain2, hash, keypair } = opts3; - const { subtreeAddr, keypairAddr } = opts3; - const v = createView(addr); - if (height !== void 0) - addr[OFFSET_CHAIN_ADDR] = height; - if (layer !== void 0) - addr[OFFSET_LAYER] = layer; - if (type !== void 0) - addr[OFFSET_TYPE] = type; - if (chain2 !== void 0) - addr[OFFSET_CHAIN_ADDR] = chain2; - if (hash !== void 0) - addr[OFFSET_HASH_ADDR] = hash; - if (index !== void 0) - v.setUint32(OFFSET_TREE_INDEX, index, false); - if (subtreeAddr) - addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8)); - if (tree !== void 0) - v.setBigUint64(OFFSET_TREE, tree, false); - if (keypair !== void 0) { - addr[OFFSET_KP_ADDR1] = keypair; - if (TREE_HEIGHT > 8) - addr[OFFSET_KP_ADDR2] = keypair >>> 8; - } - if (keypairAddr) { - addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8)); - addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1]; - if (TREE_HEIGHT > 8) - addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2]; - } - return addr; - }; - const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW); - const chainLengths = (msg) => { - const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg); - let csum = 0; - for (let i = 0; i < W1.length; i++) - csum += W - 1 - W1[i]; - csum <<= (8 - WOTS_LEN2 * WOTS_LOGW % 8) % 8; - const W2 = chainCoder(numberToBytesBE2(csum, Math.ceil(WOTS_LEN2 * WOTS_LOGW / 8))); - const lengths = new Uint32Array(WOTS_LEN); - lengths.set(W1); - lengths.set(W2, W1.length); - return lengths; - }; - const messageToIndices = base2b(K, A); - const TREE_BITS = TREE_HEIGHT * (D2 - 1); - const LEAF_BITS = TREE_HEIGHT; - const hashMsgCoder = splitCoder("hashedMessage", Math.ceil(A * K / 8), Math.ceil(TREE_BITS / 8), Math.ceil(TREE_HEIGHT / 8)); - const hashMessage = (R, pkSeed, msg, context) => { - const rawContext = context; - const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen); - const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest); - const tree = bytesToNumberBE2(tmpIdxTree) & getMaskBig(TREE_BITS); - const leafIdx = Number(bytesToNumberBE2(tmpIdxLeaf)) & getMask(LEAF_BITS); - return { tree, leafIdx, md }; - }; - const treehash = (height, fn) => function treehash_i(context, leafIdx, idxOffset, treeAddr, info) { - const rawContext = context; - const leafFn = fn; - const maxIdx = (1 << height) - 1; - const stack = new Uint8Array(height * N3); - const authPath = new Uint8Array(height * N3); - for (let idx = 0; ; idx++) { - const current = new Uint8Array(2 * N3); - const cur0 = current.subarray(0, N3); - const cur1 = current.subarray(N3); - const addrOffset = idx + idxOffset; - cur1.set(leafFn(leafIdx, addrOffset, rawContext, info)); - let h = 0; - for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) { - if (h === height) - return { root: cur1, authPath }; - if ((i ^ l) === 1) - authPath.subarray(h * N3).set(cur1); - if ((i & 1) === 0 && idx < maxIdx) - break; - setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr); - cur0.set(stack.subarray(h * N3).subarray(0, N3)); - cur1.set(rawContext.thashN(2, current, treeAddr)); - } - stack.subarray(h * N3).set(cur1); - } - throw new Error("Unreachable code path reached, report this error"); - }; - const wotsTreehash = treehash(TREE_HEIGHT, (leafIdx, addrOffset, context, info) => { - const rawContext = context; - const wotsPk = new Uint8Array(WOTS_LEN * N3); - const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0; - setAddr({ keypair: addrOffset }, info.leafAddr); - setAddr({ keypair: addrOffset }, info.pkAddr); - for (let i = 0; i < WOTS_LEN; i++) { - const wotsK = info.wotsSteps[i] | wotsKmask; - const pk = wotsPk.subarray(i * N3, (i + 1) * N3); - setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr); - pk.set(rawContext.PRFaddr(info.leafAddr)); - setAddr({ type: AddressType.WOTS }, info.leafAddr); - for (let k = 0; ; k++) { - if (k === wotsK) - info.wotsSig.subarray(i * N3).set(pk); - if (k === W - 1) - break; - setAddr({ hash: k }, info.leafAddr); - pk.set(rawContext.thash1(pk, info.leafAddr)); - } - } - return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr); - }); - const forsTreehash = treehash(A, (_, addrOffset, context, forsLeafAddr) => { - const rawContext = context; - setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr); - const prf = rawContext.PRFaddr(forsLeafAddr); - setAddr({ type: AddressType.FORSTREE }, forsLeafAddr); - return rawContext.thash1(prf, forsLeafAddr); - }); - const merkleSign = (context, wotsAddr, treeAddr, leafIdx, prevRoot = new Uint8Array(N3)) => { - setAddr({ type: AddressType.HASHTREE }, treeAddr); - const info = { - wotsSig: new Uint8Array(wotsCoder.bytesLen), - wotsSteps: chainLengths(prevRoot), - leafAddr: setAddr({ subtreeAddr: wotsAddr }), - pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }) - }; - const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info); - return { - root, - sigWots: info.wotsSig.subarray(0, WOTS_LEN * N3), - sigAuth: authPath - }; - }; - const computeRoot = (leaf, leafIdx, idxOffset, authPath, treeHeight, context, addr) => { - const rawContext = context; - const buffer = new Uint8Array(2 * N3); - const b0 = buffer.subarray(0, N3); - const b1 = buffer.subarray(N3, 2 * N3); - if ((leafIdx & 1) !== 0) { - b1.set(leaf.subarray(0, N3)); - b0.set(authPath.subarray(0, N3)); - } else { - b0.set(leaf.subarray(0, N3)); - b1.set(authPath.subarray(0, N3)); - } - leafIdx >>>= 1; - idxOffset >>>= 1; - for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) { - setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr); - const a = authPath.subarray((i + 1) * N3, (i + 2) * N3); - if ((leafIdx & 1) !== 0) { - b1.set(rawContext.thashN(2, buffer, addr)); - b0.set(a); - } else { - buffer.set(rawContext.thashN(2, buffer, addr)); - b1.set(a); - } - } - setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr); - return rawContext.thashN(2, buffer, addr); - }; - const seedCoder = splitCoder("seed", N3, N3, N3); - const publicCoder = splitCoder("publicKey", N3, N3); - const secretCoder = splitCoder("secretKey", N3, N3, publicCoder.bytesLen); - const forsCoder = vecCoder(splitCoder("fors", N3, N3 * A), K); - const wotsCoder = vecCoder(splitCoder("wots", WOTS_LEN * N3, TREE_HEIGHT * N3), D2); - const sigCoder = splitCoder("signature", N3, forsCoder, wotsCoder); - const internal = Object.freeze({ - info: Object.freeze({ type: "internal-slh-dsa" }), - lengths: Object.freeze({ - publicKey: publicCoder.bytesLen, - secretKey: secretCoder.bytesLen, - signature: sigCoder.bytesLen, - seed: seedCoder.bytesLen, - signRand: N3 - }), - keygen(seed) { - if (seed !== void 0) - abytesDoc(seed, seedCoder.bytesLen, "seed"); - seed = seed === void 0 ? randomBytes3(seedCoder.bytesLen) : copyBytes2(seed); - const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed); - const context = getContext(publicSeed, secretSeed); - const topTreeAddr = setAddr({ layer: D2 - 1 }); - const wotsAddr = setAddr({ layer: D2 - 1 }); - const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0); - const publicKey = publicCoder.encode([publicSeed, root]); - const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]); - context.clean(); - cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr); - return { - publicKey, - secretKey - }; - }, - getPublicKey: (secretKey) => { - const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey); - return Uint8Array.from(pk); - }, - sign: (msg, sk, opts3 = {}) => { - validateSigOpts2(opts3); - let { extraEntropy: random } = opts3; - const [skSeed, skPRF, pk] = secretCoder.decode(sk); - const [pkSeed, _] = publicCoder.decode(pk); - if (random === false) - random = copyBytes2(pkSeed); - else if (random === void 0) - random = randomBytes3(N3); - else - random = copyBytes2(random); - abytesDoc(random, N3); - const context = getContext(pkSeed, skSeed); - const R = context.PRFmsg(skPRF, random, msg); - let { tree, leafIdx, md } = hashMessage(R, pk, msg, context); - const wotsAddr = setAddr({ - type: AddressType.WOTS, - tree, - keypair: leafIdx - }); - const roots = []; - const forsLeaf = setAddr({ keypairAddr: wotsAddr }); - const forsTreeAddr = setAddr({ keypairAddr: wotsAddr }); - const indices = messageToIndices(md); - const fors = []; - for (let i = 0; i < indices.length; i++) { - const idxOffset = i << A; - setAddr({ - type: AddressType.FORSPRF, - height: 0, - index: indices[i] + idxOffset - }, forsTreeAddr); - const prf = context.PRFaddr(forsTreeAddr); - setAddr({ type: AddressType.FORSTREE }, forsTreeAddr); - const { root: root2, authPath } = forsTreehash(context, indices[i], idxOffset, forsTreeAddr, forsLeaf); - roots.push(root2); - fors.push([prf, authPath]); - } - const forsPkAddr = setAddr({ - type: AddressType.FORSPK, - keypairAddr: wotsAddr - }); - const root = context.thashN(K, concatBytes(...roots), forsPkAddr); - const treeAddr = setAddr({ type: AddressType.HASHTREE }); - const wots = []; - for (let i = 0; i < D2; i++, tree >>= BigInt(TREE_HEIGHT)) { - setAddr({ tree, layer: i }, treeAddr); - setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); - const { sigWots, sigAuth, root: r } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root); - root.set(r); - cleanBytes(r); - wots.push([sigWots, sigAuth]); - leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); - } - context.clean(); - const SIG = sigCoder.encode([R, fors, wots]); - cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots); - return SIG; - }, - verify: (sig, msg, publicKey) => { - const [pkSeed, pubRoot] = publicCoder.decode(publicKey); - const [random, forsVec, wotsVec] = sigCoder.decode(sig); - const pk = publicKey; - if (sig.length !== sigCoder.bytesLen) - return false; - const context = getContext(pkSeed); - let { tree, leafIdx, md } = hashMessage(random, pk, msg, context); - const wotsAddr = setAddr({ - type: AddressType.WOTS, - tree, - keypair: leafIdx - }); - const roots = []; - const forsTreeAddr = setAddr({ - type: AddressType.FORSTREE, - keypairAddr: wotsAddr - }); - const indices = messageToIndices(md); - for (let i = 0; i < forsVec.length; i++) { - const [prf, authPath] = forsVec[i]; - const idxOffset = i << A; - setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr); - const leaf = context.thash1(prf, forsTreeAddr); - roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr)); - } - const forsPkAddr = setAddr({ - type: AddressType.FORSPK, - keypairAddr: wotsAddr - }); - let root = context.thashN(K, concatBytes(...roots), forsPkAddr); - const treeAddr = setAddr({ type: AddressType.HASHTREE }); - const wotsPkAddr = setAddr({ type: AddressType.WOTSPK }); - const wotsPk = new Uint8Array(WOTS_LEN * N3); - for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) { - const [wots, sigAuth] = wotsVec[i]; - setAddr({ tree, layer: i }, treeAddr); - setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); - setAddr({ keypairAddr: wotsAddr }, wotsPkAddr); - const lengths = chainLengths(root); - for (let i2 = 0; i2 < WOTS_LEN; i2++) { - setAddr({ chain: i2 }, wotsAddr); - const steps = W - 1 - lengths[i2]; - const start = lengths[i2]; - const out = wotsPk.subarray(i2 * N3); - out.set(wots.subarray(i2 * N3, (i2 + 1) * N3)); - for (let j = start; j < start + steps && j < W; j++) { - setAddr({ hash: j }, wotsAddr); - out.set(context.thash1(out, wotsAddr)); - } - } - const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr); - root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr); - leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); - } - return equalBytes(root, pubRoot); - } - }); - return Object.freeze({ - info: Object.freeze({ type: "slh-dsa" }), - internal, - securityLevel, - lengths: internal.lengths, - keygen: internal.keygen, - getPublicKey: internal.getPublicKey, - sign: (msg, secretKey, opts3 = {}) => { - validateSigOpts2(opts3); - const M = getMessage(msg, opts3.context); - const res = internal.sign(M, secretKey, opts3); - cleanBytes(M); - return res; - }, - verify: (sig, msg, publicKey, opts3 = {}) => { - validateVerOpts(opts3); - return internal.verify(sig, getMessage(msg, opts3.context), publicKey); - }, - prehash: (hash) => { - checkHash(hash, securityLevel); - const rawHash = hash; - return Object.freeze({ - info: Object.freeze({ type: "hashslh-dsa" }), - lengths: internal.lengths, - keygen: internal.keygen, - getPublicKey: internal.getPublicKey, - sign: (msg, secretKey, opts3 = {}) => { - validateSigOpts2(opts3); - const M = getMessagePrehash(rawHash, msg, opts3.context); - const res = internal.sign(M, secretKey, opts3); - cleanBytes(M); - return res; - }, - verify: (sig, msg, publicKey, opts3 = {}) => { - validateVerOpts(opts3); - return internal.verify(sig, getMessagePrehash(rawHash, msg, opts3.context), publicKey); - } - }); - } - }); -} -var genSha = (h0, h1) => (opts2) => (pub_seed, sk_seed) => { - const { N: N3 } = opts2; - const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 }; - const counterB = new Uint8Array(4); - const counterV = createView(counterB); - const h0ps = h0.create().update(pub_seed).update(new Uint8Array(h0.blockLen - N3)); - const h1ps = h1.create().update(pub_seed).update(new Uint8Array(h1.blockLen - N3)); - const h0tmp = h0ps.clone(); - const h1tmp = h1ps.clone(); - function mgf1(seed, length, hash) { - stats.mgf1++; - const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen); - if (length > 2 ** 32) - throw new Error("mask too long"); - for (let counter = 0, o = out; o.length; counter++) { - counterV.setUint32(0, counter, false); - hash.create().update(seed).update(counterB).digestInto(o); - o = o.subarray(hash.outputLen); - } - cleanBytes(out.subarray(length)); - return out.subarray(0, length); - } - const thash = (_, h, hTmp) => (blocks, input, addr) => { - stats.thash++; - const d = h._cloneInto(hTmp).update(addr).update(input.subarray(0, blocks * N3)).digest(); - return d.subarray(0, N3); - }; - return { - PRFaddr: (addr) => { - if (!sk_seed) - throw new Error("No sk seed"); - stats.prf++; - const res = h0ps._cloneInto(h0tmp).update(addr).update(sk_seed).digest().subarray(0, N3); - return res; - }, - PRFmsg: (skPRF, random, msg) => { - stats.gen_message_random++; - return hmac.create(h1, skPRF).update(random).update(msg).digest().subarray(0, N3); - }, - Hmsg: (R, pk, m, outLen) => { - stats.hmsg++; - const seed = concatBytes(R.subarray(0, N3), pk.subarray(0, N3), h1.create().update(R.subarray(0, N3)).update(pk).update(m).digest()); - return mgf1(seed, outLen, h1); - }, - thash1: thash(h0, h0ps, h0tmp).bind(null, 1), - thashN: thash(h1, h1ps, h1tmp), - clean: () => { - h0ps.destroy(); - h1ps.destroy(); - h0tmp.destroy(); - h1tmp.destroy(); - } - }; -}; -var SHA256_SIMPLE = /* @__PURE__ */ (() => ({ - isCompressed: true, - getContext: genSha(sha256, sha256) -}))(); -var slh_dsa_sha2_128s = /* @__PURE__ */ (() => gen(PARAMS2["128s"], SHA256_SIMPLE))(); - -// node_modules/@noble/post-quantum/ml-kem.js -var N2 = 256; -var Q2 = 3329; -var F2 = 3303; -var ROOT_OF_UNITY2 = 17; -var crystals2 = /* @__PURE__ */ genCrystals({ - N: N2, - Q: Q2, - F: F2, - ROOT_OF_UNITY: ROOT_OF_UNITY2, - newPoly: (n) => new Uint16Array(n), - brvBits: 7, - isKyber: true -}); -var PARAMS3 = /* @__PURE__ */ (() => Object.freeze({ - 512: Object.freeze({ N: N2, Q: Q2, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }), - 768: Object.freeze({ N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }), - 1024: Object.freeze({ N: N2, Q: Q2, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }) -}))(); -var compress = (d) => { - if (d >= 12) - return { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i }; - const a = 2 ** (d - 1); - return { - // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d). - encode: (i) => ((i << d) + Q2 / 2) / Q2, - // const decompress = (i: number) => round((Q / 2 ** d) * i); - decode: (i) => i * Q2 + a >>> d - }; -}; -var byteCoder = (d) => crystals2.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i } : { encode: (i) => i, decode: (i) => i }); -var polyCoder2 = (d) => d === 12 ? byteCoder(12) : crystals2.bitsCoder(d, compress(d)); -function polyAdd2(a_, b_) { - const a = a_; - const b = b_; - for (let i = 0; i < N2; i++) - a[i] = crystals2.mod(a[i] + b[i]); -} -function polySub2(a_, b_) { - const a = a_; - const b = b_; - for (let i = 0; i < N2; i++) - a[i] = crystals2.mod(a[i] - b[i]); -} -function BaseCaseMultiply(a0, a1, b0, b1, zeta) { - const c0 = crystals2.mod(a1 * b1 * zeta + a0 * b0); - const c1 = crystals2.mod(a0 * b1 + a1 * b0); - return { c0, c1 }; -} -function MultiplyNTTs2(f_, g_) { - const f = f_; - const g = g_; - for (let i = 0; i < N2 / 2; i++) { - let z = crystals2.nttZetas[64 + (i >> 1)]; - if (i & 1) - z = -z; - const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z); - f[2 * i + 0] = c0; - f[2 * i + 1] = c1; - } - return f; -} -function SampleNTT(xof_) { - const xof = xof_; - const r = new Uint16Array(N2); - for (let j = 0; j < N2; ) { - const b = xof(); - if (b.length % 3) - throw new Error("SampleNTT: unaligned block"); - for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) { - const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095; - const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095; - if (d1 < Q2) - r[j++] = d1; - if (j < N2 && d2 < Q2) - r[j++] = d2; - } - } - return r; -} -var sampleCBDBytes = (buf, eta) => { - const r = new Uint16Array(N2); - const b32 = u32(buf); - swap32IfBE(b32); - let len = 0; - for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) { - let b = b32[i]; - for (let j = 0; j < 32; j++) { - bb += b & 1; - b >>= 1; - len += 1; - if (len === eta) { - t0 = bb; - bb = 0; - } else if (len === 2 * eta) { - r[p++] = crystals2.mod(t0 - bb); - bb = 0; - len = 0; - } - } - } - swap32IfBE(b32); - if (len) - throw new Error(`sampleCBD: leftover bits: ${len}`); - return r; -}; -function sampleCBD(PRF_, seed, nonce, eta) { - const PRF = PRF_; - return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta); -} -var genKPKE = (opts_) => { - const opts2 = opts_; - const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2; - const poly1 = polyCoder2(1); - const polyV = polyCoder2(dv); - const polyU = polyCoder2(du); - const publicCoder = splitCoder("publicKey", vecCoder(polyCoder2(12), K), 32); - const secretCoder = vecCoder(polyCoder2(12), K); - const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV); - const seedCoder = splitCoder("seed", 32, 32); - return { - secretCoder, - lengths: { - secretKey: secretCoder.bytesLen, - publicKey: publicCoder.bytesLen, - cipherText: cipherCoder.bytesLen - }, - keygen: (seed) => { - abytesDoc(seed, 32, "seed"); - const seedDst = new Uint8Array(33); - seedDst.set(seed); - seedDst[32] = K; - const seedHash = HASH512(seedDst); - const [rho, sigma] = seedCoder.decode(seedHash); - const sHat = []; - const tHat = []; - for (let i = 0; i < K; i++) - sHat.push(crystals2.NTT.encode(sampleCBD(PRF, sigma, i, ETA1))); - const x = XOF(rho); - for (let i = 0; i < K; i++) { - const e = crystals2.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1)); - for (let j = 0; j < K; j++) { - const aji = SampleNTT(x.get(j, i)); - polyAdd2(e, MultiplyNTTs2(aji, sHat[j])); - } - tHat.push(e); - } - x.clean(); - const res = { - publicKey: publicCoder.encode([tHat, rho]), - secretKey: secretCoder.encode(sHat) - }; - cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash); - return res; - }, - encrypt: (publicKey, msg, seed) => { - const [tHat, rho] = publicCoder.decode(publicKey); - const rHat = []; - for (let i = 0; i < K; i++) - rHat.push(crystals2.NTT.encode(sampleCBD(PRF, seed, i, ETA1))); - const x = XOF(rho); - const tmp2 = new Uint16Array(N2); - const u = []; - for (let i = 0; i < K; i++) { - const e1 = sampleCBD(PRF, seed, K + i, ETA2); - const tmp = new Uint16Array(N2); - for (let j = 0; j < K; j++) { - const aij = SampleNTT(x.get(i, j)); - polyAdd2(tmp, MultiplyNTTs2(aij, rHat[j])); - } - polyAdd2(e1, crystals2.NTT.decode(tmp)); - u.push(e1); - polyAdd2(tmp2, MultiplyNTTs2(tHat[i], rHat[i])); - cleanBytes(tmp); - } - x.clean(); - const e2 = sampleCBD(PRF, seed, 2 * K, ETA2); - polyAdd2(e2, crystals2.NTT.decode(tmp2)); - const v = poly1.decode(msg); - polyAdd2(v, e2); - cleanBytes(tHat, rHat, tmp2, e2); - return cipherCoder.encode([u, v]); - }, - decrypt: (cipherText, privateKey) => { - const [u, v] = cipherCoder.decode(cipherText); - const sk = secretCoder.decode(privateKey); - const tmp = new Uint16Array(N2); - for (let i = 0; i < K; i++) - polyAdd2(tmp, MultiplyNTTs2(sk[i], crystals2.NTT.encode(u[i]))); - polySub2(v, crystals2.NTT.decode(tmp)); - cleanBytes(tmp, sk, u); - return poly1.encode(v); - } - }; -}; -function createKyber(opts2) { - const rawOpts = opts2; - const KPKE = genKPKE(rawOpts); - const { HASH256, HASH512, KDF } = rawOpts; - const { secretCoder: KPKESecretCoder, lengths } = KPKE; - const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32); - const msgLen = 32; - const seedLen = 64; - const kemLengths = Object.freeze({ - ...lengths, - seed: 64, - msg: msgLen, - msgRand: msgLen, - secretKey: secretCoder.bytesLen - }); - return Object.freeze({ - info: Object.freeze({ type: "ml-kem" }), - lengths: kemLengths, - keygen: (seed = randomBytes3(seedLen)) => { - abytesDoc(seed, seedLen, "seed"); - const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32)); - const publicKeyHash = HASH256(publicKey); - const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]); - cleanBytes(sk, publicKeyHash); - return { - publicKey, - secretKey - }; - }, - getPublicKey: (secretKey) => { - const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey); - return Uint8Array.from(publicKey); - }, - encapsulate: (publicKey, msg = randomBytes3(msgLen)) => { - abytesDoc(publicKey, lengths.publicKey, "publicKey"); - abytesDoc(msg, msgLen, "message"); - const eke = publicKey.subarray(0, 384 * opts2.K); - const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke))); - if (!equalBytes(ek, eke)) { - cleanBytes(ek); - throw new Error("ML-KEM.encapsulate: wrong publicKey modulus"); - } - cleanBytes(ek); - const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest(); - const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); - cleanBytes(kr.subarray(32)); - return { - cipherText, - sharedSecret: kr.subarray(0, 32) - }; - }, - decapsulate: (cipherText, secretKey) => { - abytesDoc(secretKey, secretCoder.bytesLen, "secretKey"); - abytesDoc(cipherText, lengths.cipherText, "cipherText"); - const k768 = secretCoder.bytesLen - 96; - const start = k768 + 32; - const test = HASH256(secretKey.subarray(k768 / 2, start)); - if (!equalBytes(test, secretKey.subarray(start, start + 32))) - throw new Error("invalid secretKey: hash check failed"); - const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey); - const msg = KPKE.decrypt(cipherText, sk); - const kr = HASH512.create().update(msg).update(publicKeyHash).digest(); - const Khat = kr.subarray(0, 32); - const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); - const isValid = equalBytes(cipherText, cipherText2); - const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest(); - cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar); - return isValid ? Khat : Kbar; - } - }); -} -function shakePRF(dkLen, key, nonce) { - return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest(); -} -var opts = /* @__PURE__ */ (() => ({ - HASH256: sha3_256, - HASH512: sha3_512, - KDF: shake256, - XOF: XOF128, - PRF: shakePRF -}))(); -var mk = (params) => createKyber({ - ...opts, - ...params -}); -var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS3[768]))(); - -// www/js/pq-crypto.mjs -function generateSeedPhrase() { - return generateMnemonic(wordlist, 128); -} -function mnemonicToSeed(mnemonic, passphrase = "") { - if (!validateMnemonic(mnemonic, wordlist)) { - throw new Error("Invalid mnemonic"); - } - return mnemonicToSeedSync(mnemonic, passphrase); -} -function isValidMnemonic(mnemonic) { - return validateMnemonic(mnemonic, wordlist); -} -function deriveSecp256k1FromSeed(seed, accountIndex = 0) { - const hdKey = HDKey.fromMasterSeed(seed); - const path = `m/44'/1237'/${accountIndex}'/0/0`; - const child = hdKey.derive(path); - if (!child.privateKey) { - throw new Error("Failed to derive private key"); - } - return { - privateKey: child.privateKey, - publicKey: child.publicKey - }; -} -function derivePQSeed(bip39Seed, label, length) { - const info = new TextEncoder().encode(label); - return hkdf(sha512, bip39Seed, void 0, info, length); -} -function derivePQKeysFromSeed(bip39Seed) { - const mlDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-dsa-65", 32); - const mlDsa = ml_dsa65.keygen(mlDsaSeed); - const slhDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-slh-dsa-128s", 48); - const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed); - const mlKemSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-kem-768", 64); - const mlKem = ml_kem768.keygen(mlKemSeed); - return { mlDsa, slhDsa, mlKem }; -} -function signWithMLDSA(message, secretKey) { - return ml_dsa65.sign(message, secretKey); -} -function verifyMLDSA(signature, message, publicKey) { - return ml_dsa65.verify(signature, message, publicKey); -} -function signWithSLHDSA(message, secretKey) { - return slh_dsa_sha2_128s.sign(message, secretKey); -} -function verifySLHDSA(signature, message, publicKey) { - return slh_dsa_sha2_128s.verify(signature, message, publicKey); -} -function bytesToBase64(bytes) { - let binary = ""; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} -function base64ToBytes(base64) { - const binary = atob(base64); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes; -} -function bytesToHex3(bytes) { - return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); -} -function hexToBytes3(hex) { - const bytes = new Uint8Array(hex.length / 2); - for (let i = 0; i < hex.length; i += 2) { - bytes[i / 2] = parseInt(hex.substr(i, 2), 16); - } - return bytes; -} -function buildNIPQRContent(npub, successorNpub, pqKeys) { - let statement; - if (successorNpub) { - statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`; - } else { - statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`; - } - const statementBytes = new TextEncoder().encode(statement); - const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey); - const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey); - const content = { - statement, - pq_keys: [ - { - algorithm: "ml-dsa-65", - public_key: bytesToBase64(pqKeys.mlDsa.publicKey), - signature: bytesToBase64(mlDsaSig) - }, - { - algorithm: "slh-dsa-128s", - public_key: bytesToBase64(pqKeys.slhDsa.publicKey), - signature: bytesToBase64(slhDsaSig) - }, - { - algorithm: "ml-kem-768", - public_key: bytesToBase64(pqKeys.mlKem.publicKey), - note: "KEM key for encryption; ownership asserted by secp256k1 signature over this content" - } - ] - }; - if (successorNpub) { - content.successor_pubkey = successorNpub; - } - return { statement, content, statementBytes }; -} -function verifyNIPQRContent(content) { - const results = []; - for (const keyEntry of content.pq_keys) { - if (keyEntry.algorithm === "ml-kem-768") { - results.push({ algorithm: keyEntry.algorithm, valid: true, note: "KEM (no signature to verify)" }); - continue; - } - const pubKey = base64ToBytes(keyEntry.public_key); - const sig = base64ToBytes(keyEntry.signature); - const msg = new TextEncoder().encode(content.statement); - let valid = false; - if (keyEntry.algorithm === "ml-dsa-65") { - valid = verifyMLDSA(sig, msg, pubKey); - } else if (keyEntry.algorithm === "slh-dsa-128s") { - valid = verifySLHDSA(sig, msg, pubKey); - } - results.push({ algorithm: keyEntry.algorithm, valid }); - } - return { - valid: results.every((r) => r.valid), - results - }; -} -var PQ_KEY_INFO = { - "ml-dsa-65": { - name: "ML-DSA-65 (Dilithium)", - publicKeySize: 1952, - signatureSize: 3309, - fips: "FIPS 204", - type: "signature" - }, - "slh-dsa-128s": { - name: "SLH-DSA-128s (SPHINCS+)", - publicKeySize: 32, - signatureSize: 7856, - fips: "FIPS 205", - type: "signature" - }, - "ml-kem-768": { - name: "ML-KEM-768 (Kyber)", - publicKeySize: 1184, - ciphertextSize: 1088, - fips: "FIPS 203", - type: "kem" - } -}; -export { - PQ_KEY_INFO, - base64ToBytes, - buildNIPQRContent, - bytesToBase64, - bytesToHex3 as bytesToHex, - derivePQKeysFromSeed, - deriveSecp256k1FromSeed, - generateSeedPhrase, - hexToBytes3 as hexToBytes, - isValidMnemonic, - mnemonicToSeed, - signWithMLDSA, - signWithSLHDSA, - verifyMLDSA, - verifyNIPQRContent, - verifySLHDSA -}; -/*! Bundled license information: - -@scure/base/index.js: - (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/bip39/index.js: - (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) - -@noble/curves/utils.js: -@noble/curves/abstract/modular.js: -@noble/curves/abstract/curve.js: -@noble/curves/abstract/weierstrass.js: -@noble/curves/secp256k1.js: - (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) - -@scure/bip32/index.js: - (*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) - -@noble/post-quantum/utils.js: -@noble/post-quantum/_crystals.js: -@noble/post-quantum/ml-dsa.js: -@noble/post-quantum/slh-dsa.js: -@noble/post-quantum/ml-kem.js: - (*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *) -*/ -//# sourceMappingURL=pq-crypto.bundle.js.map diff --git a/www/pq-crypto.bundle.js.map b/www/pq-crypto.bundle.js.map deleted file mode 100644 index b56a767..0000000 --- a/www/pq-crypto.bundle.js.map +++ /dev/null @@ -1,7 +0,0 @@ -{ - "version": 3, - "sources": ["../node_modules/@noble/hashes/src/utils.ts", "../node_modules/@noble/hashes/src/hmac.ts", "../node_modules/@noble/hashes/src/pbkdf2.ts", "../node_modules/@noble/hashes/src/_md.ts", "../node_modules/@noble/hashes/src/_u64.ts", "../node_modules/@noble/hashes/src/sha2.ts", "../node_modules/@scure/base/index.ts", "../node_modules/@scure/bip39/index.js", "../node_modules/@scure/bip39/wordlists/english.js", "../node_modules/@noble/curves/src/utils.ts", "../node_modules/@noble/curves/src/abstract/modular.ts", "../node_modules/@noble/curves/src/abstract/curve.ts", "../node_modules/@noble/curves/src/abstract/fft.ts", "../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../node_modules/@noble/curves/src/secp256k1.ts", "../node_modules/@noble/hashes/src/legacy.ts", "../node_modules/@scure/bip32/index.ts", "../node_modules/@noble/hashes/src/hkdf.ts", "../node_modules/@noble/hashes/src/sha3.ts", "../node_modules/@noble/post-quantum/src/utils.ts", "../node_modules/@noble/post-quantum/src/_crystals.ts", "../node_modules/@noble/post-quantum/src/ml-dsa.ts", "../node_modules/@noble/post-quantum/src/slh-dsa.ts", "../node_modules/@noble/post-quantum/src/ml-kem.ts", "js/pq-crypto.mjs"], - "sourcesContent": ["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n/**\n * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.\n * @param a - value to test\n * @returns `true` when the value is a Uint8Array-compatible view.\n * @example\n * Check whether a value is a Uint8Array-compatible view.\n * ```ts\n * isBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.\n // The fallback still requires a real ArrayBuffer view, so plain\n // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and\n // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a non-negative integer option.\n * ```ts\n * anumber(32, 'length');\n * ```\n */\nexport function anumber(n: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\n\n/**\n * Asserts something is Uint8Array.\n * @param value - value to validate\n * @param length - optional exact length constraint\n * @param title - label included in thrown errors\n * @returns The validated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate that a value is a byte array.\n * ```ts\n * abytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function abytes(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\n\n/**\n * Copies bytes into a fresh Uint8Array.\n * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.\n * @param bytes - source bytes to clone\n * @returns Freshly allocated copy of `bytes`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Clone a byte array before mutating it.\n * ```ts\n * const copy = copyBytes(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Asserts something is a wrapped hash constructor.\n * @param h - hash constructor to validate\n * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}\n * @throws On invalid hash metadata ranges or values. {@link RangeError}\n * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}\n * @example\n * Validate a callable hash wrapper.\n * ```ts\n * import { ahash } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * ahash(sha256);\n * ```\n */\nexport function ahash(h: TArg): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass\n // validation and can produce empty outputs instead of failing fast.\n if (h.outputLen < 1) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\n\n/**\n * Asserts a hash instance has not been destroyed or finished.\n * @param instance - hash instance to validate\n * @param checkFinished - whether to reject finalized instances\n * @throws If the hash instance has already been destroyed or finalized. {@link Error}\n * @example\n * Validate that a hash instance is still usable.\n * ```ts\n * import { aexists } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aexists(hash);\n * ```\n */\nexport function aexists(instance: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\n/**\n * Asserts output is a sufficiently-sized byte array.\n * @param out - destination buffer\n * @param instance - hash instance providing output length\n * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a caller-provided digest buffer.\n * ```ts\n * import { aoutput } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const hash = sha256.create();\n * aoutput(new Uint8Array(hash.outputLen), hash);\n * ```\n */\nexport function aoutput(out: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n/**\n * Casts a typed array view to Uint8Array.\n * @param arr - source typed array\n * @returns Uint8Array view over the same buffer.\n * @example\n * Reinterpret a typed array as bytes.\n * ```ts\n * u8(new Uint32Array([1, 2]));\n * ```\n */\nexport function u8(arr: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\n\n/**\n * Casts a typed array view to Uint32Array.\n * `arr.byteOffset` must already be 4-byte aligned or the platform\n * Uint32Array constructor will throw.\n * @param arr - source typed array\n * @returns Uint32Array view over the same buffer.\n * @example\n * Reinterpret a byte array as 32-bit words.\n * ```ts\n * u32(new Uint8Array(8));\n * ```\n */\nexport function u32(arr: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\n\n/**\n * Zeroizes typed arrays in place. Warning: JS provides no guarantees.\n * @param arrays - arrays to overwrite with zeros\n * @example\n * Zeroize sensitive buffers in place.\n * ```ts\n * clean(new Uint8Array([1, 2, 3]));\n * ```\n */\nexport function clean(...arrays: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n\n/**\n * Creates a DataView for byte-level manipulation.\n * @param arr - source typed array\n * @returns DataView over the same buffer region.\n * @example\n * Create a DataView over an existing buffer.\n * ```ts\n * createView(new Uint8Array(4));\n * ```\n */\nexport function createView(arr: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n\n/**\n * Rotate-right operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the right.\n * ```ts\n * rotr(0x12345678, 8);\n * ```\n */\nexport function rotr(word: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\n\n/**\n * Rotate-left operation for uint32 values.\n * @param word - source word\n * @param shift - shift amount in bits\n * @returns Rotated word.\n * @example\n * Rotate a 32-bit word to the left.\n * ```ts\n * rotl(0x12345678, 8);\n * ```\n */\nexport function rotl(word: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\n/**\n * Byte-swap operation for uint32 values.\n * @param word - source word\n * @returns Word with reversed byte order.\n * @example\n * Reverse the byte order of a 32-bit word.\n * ```ts\n * byteSwap(0x11223344);\n * ```\n */\nexport function byteSwap(word: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\n}\n/**\n * Conditionally byte-swaps one 32-bit word on big-endian platforms.\n * @param n - source word\n * @returns Original or byte-swapped word depending on platform endianness.\n * @example\n * Normalize a 32-bit word for host endianness.\n * ```ts\n * swap8IfBE(0x11223344);\n * ```\n */\nexport const swap8IfBE: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\n/**\n * Byte-swaps every word of a Uint32Array in place.\n * @param arr - array to mutate\n * @returns The same array after mutation; callers pass live state arrays here.\n * @example\n * Reverse the byte order of every word in place.\n * ```ts\n * byteSwap32(new Uint32Array([0x11223344]));\n * ```\n */\nexport function byteSwap32(arr: TArg): TRet {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet;\n}\n\n/**\n * Conditionally byte-swaps a Uint32Array on big-endian platforms.\n * @param u - array to normalize for host endianness\n * @returns Original or byte-swapped array depending on platform endianness.\n * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.\n * @example\n * Normalize a word array for host endianness.\n * ```ts\n * swap32IfBE(new Uint32Array([0x11223344]));\n * ```\n */\nexport const swap32IfBE: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\n * Convert byte array to hex string.\n * Uses the built-in function when available and assumes it matches the tested\n * fallback semantics.\n * @param bytes - bytes to encode\n * @returns Lowercase hexadecimal string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Convert bytes to lowercase hexadecimal.\n * ```ts\n * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'\n * ```\n */\nexport function bytesToHex(bytes: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @param hex - hexadecimal string to decode\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode lowercase hexadecimal into bytes.\n * ```ts\n * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n * ```\n */\nexport function hexToBytes(hex: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * milliseconds to avoid blocking long loops.\n * @param iters - number of loop iterations to run\n * @param tick - maximum time slice in milliseconds\n * @param cb - callback executed on each iteration\n * @example\n * Run a loop that periodically yields back to the event loop.\n * ```ts\n * await asyncLoop(2, 0, () => {});\n * ```\n */\nexport async function asyncLoop(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * Converts string to bytes using UTF8 encoding.\n * Built-in doesn't validate input to be string: we do the check.\n * Non-ASCII details are delegated to the platform `TextEncoder`.\n * @param str - string to encode\n * @returns UTF-8 encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode a string as UTF-8 bytes.\n * ```ts\n * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])\n * ```\n */\nexport function utf8ToBytes(str: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\n\n/**\n * Helper for KDFs: consumes Uint8Array or string.\n * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.\n * @param data - user-provided KDF input\n * @param errorTitle - label included in thrown errors\n * @returns Byte representation of the input.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Normalize KDF input to bytes.\n * ```ts\n * kdfInputToBytes('password');\n * ```\n */\nexport function kdfInputToBytes(data: TArg, errorTitle = ''): TRet {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\n\n/**\n * Copies several Uint8Arrays into one.\n * @param arrays - arrays to concatenate\n * @returns Concatenated byte array.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Concatenate multiple byte arrays.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nexport function concatBytes(...arrays: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Merge user overrides onto default options.\n * ```ts\n * checkOpts({ dkLen: 32 }, { asyncTick: 10 });\n * ```\n */\nexport function checkOpts(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg): TRet;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet;\n};\n/** Callable hash function type. */\nexport type CHash = Hash, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg): TRet;\n create(): T;\n }\n : {\n (msg: TArg, opts?: TArg): TRet;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\n\n/**\n * Creates a callable hash function from a stateful class constructor.\n * @param hashCons - hash constructor or factory\n * @param info - optional metadata such as DER OID\n * @returns Frozen callable hash wrapper with `.create()`.\n * Wrapper construction eagerly calls `hashCons(undefined)` once to read\n * `outputLen` / `blockLen`, so constructor side effects happen at module\n * init time.\n * @example\n * Wrap a stateful hash constructor into a callable helper.\n * ```ts\n * import { createHasher } from '@noble/hashes/utils.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const wrapped = createHasher(sha256.create, { oid: sha256.oid });\n * wrapped(new Uint8Array([1]));\n * ```\n */\nexport function createHasher, Opts = undefined>(\n hashCons: HasherCons,\n info: TArg = {}\n): TRet> {\n const hashC: any = (msg: TArg, opts?: TArg) =>\n hashCons(opts as Opts)\n .update(msg)\n .digest();\n const tmp = hashCons(undefined);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.canXOF = tmp.canXOF;\n hashC.create = (opts?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet>;\n}\n\n/**\n * Cryptographically secure PRNG backed by `crypto.getRandomValues`.\n * @param bytesLength - number of random bytes to generate\n * @returns Random bytes.\n * The platform `getRandomValues()` implementation still defines any\n * single-call length cap, and this helper rejects oversize requests\n * with a stable library `RangeError` instead of host-specific errors.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}\n * @example\n * Generate a fresh random key or nonce.\n * ```ts\n * const key = randomBytes(16);\n * ```\n */\nexport function randomBytes(bytesLength = 32): TRet {\n // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.\n anumber(bytesLength, 'bytesLength');\n const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null;\n if (typeof cr?.getRandomValues !== 'function')\n throw new Error('crypto.getRandomValues must be defined');\n // Web Cryptography API Level 2 \u00A710.1.1:\n // if `byteLength > 65536`, throw `QuotaExceededError`.\n // Keep the guard explicit so callers can see the quota in code\n // instead of discovering it by reading the spec or host errors.\n // This wrapper surfaces the same quota as a stable library RangeError.\n if (bytesLength > 65536)\n throw new RangeError(`\"bytesLength\" expected <= 65536, got ${bytesLength}`);\n return cr.getRandomValues(new Uint8Array(bytesLength));\n}\n\n/**\n * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.\n * @param suffix - final OID byte for the selected hash.\n * The helper accepts any byte even though only the documented NIST hash\n * suffixes are meaningful downstream.\n * @returns Object containing the DER-encoded OID.\n * @example\n * Build OID metadata for a NIST hash.\n * ```ts\n * oidNist(0x01);\n * ```\n */\nexport const oidNist = (suffix: number): TRet> => ({\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 * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Internal class for HMAC.\n * Accepts any byte key, although RFC 2104 \u00A73 recommends keys at least\n * `HashLen` bytes long.\n */\nexport class _HMAC> implements Hash<_HMAC> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg, key: TArg) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: TArg): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const buf = out.subarray(0, this.outputLen);\n // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before\n // overwriting that same prefix with the final tag, leaving any oversized tail untouched.\n this.iHash.digestInto(buf);\n this.oHash.update(buf);\n this.oHash.digestInto(buf);\n this.destroy();\n }\n digest(): TRet {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n _cloneInto(to?: _HMAC): _HMAC {\n // Create new instance without calling constructor since the key\n // is already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg, key: TArg, message: TArg): TRet;\n create(hash: TArg, key: TArg): TRet<_HMAC>;\n};\nexport const hmac: TRet = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg,\n key: TArg,\n message: TArg\n ): TRet => new _HMAC(hash, key).update(message).digest()) as TRet;\n hmac_.create = (hash: TArg, key: TArg): TRet<_HMAC> =>\n new _HMAC(hash, key) as TRet<_HMAC>;\n return hmac_;\n})();\n", "/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, kdfInputToBytes,\n type CHash,\n type Hash,\n type KDFInput,\n type TArg,\n type TRet\n} from './utils.ts';\n\n/**\n * PBKDF2 options:\n * * c: iterations, should probably be higher than 100_000\n * * dkLen: desired length of derived key in bytes, must be `>= 1` per RFC 8018 \u00A75.2\n * * asyncTick: max time in ms for which async function can block execution\n */\nexport type Pbkdf2Opt = {\n /** Iteration count. Higher values increase CPU cost. */\n c: number;\n /** Desired derived key length in bytes, must be `>= 1` per RFC 8018 \u00A75.2. */\n dkLen?: number;\n /** Max scheduler block time in milliseconds for the async variant. */\n asyncTick?: number;\n};\n// Common start and end for sync/async functions\nfunction pbkdf2Init(\n hash: TArg,\n _password: TArg,\n _salt: TArg,\n _opts: TArg\n) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1) throw new Error('iterations (c) must be >= 1');\n // RFC 8018 \u00A75.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1) throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 \u00A75.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen) throw new Error('derived key too long');\n const password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: TArg>,\n PRFSalt: TArg>,\n DK: TArg,\n prfW: TArg | undefined>,\n u: TArg\n): TRet {\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK as TRet;\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(\n hash: TArg,\n password: TArg,\n salt: TArg,\n opts: TArg\n): TRet {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc\u22121)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n */\nexport async function pbkdf2Async(\n hash: TArg,\n password: TArg,\n salt: TArg,\n opts: TArg\n): Promise> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc\u22121)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/**\n * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.\n * Returns bits from `b` when `a` is set, otherwise from `c`.\n * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never\n * set the same bit.\n * @param a - selector word\n * @param b - word chosen when selector bit is set\n * @param c - word chosen when selector bit is clear\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit choice primitive.\n * ```ts\n * Chi(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Chi(a: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\n\n/**\n * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.\n * Returns bits shared by at least two inputs.\n * @param a - first input word\n * @param b - second input word\n * @param c - third input word\n * @returns Mixed 32-bit word.\n * @example\n * Combine three words with the shared 32-bit majority primitive.\n * ```ts\n * Maj(0xffffffff, 0x12345678, 0x87654321);\n * ```\n */\nexport function Maj(a: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit\n * strings with partial-byte tails.\n * @param blockLen - internal block size in bytes\n * @param outputLen - digest size in bytes\n * @param padOffset - trailing length field size in bytes\n * @param isLE - whether length and state words are encoded in little-endian\n * @example\n * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.\n * ```ts\n * import { _SHA1 } from '@noble/hashes/legacy.js';\n * const hash = new _SHA1();\n * hash.update(new Uint8Array([97, 98, 99]));\n * hash.digest();\n * ```\n */\nexport abstract class HashMD> implements Hash {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n const { view, buffer, blockLen } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path only when there is no buffered partial block: `take === blockLen` implies\n // `this.pos === 0`, so we can process full blocks directly from the input view.\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg): void {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(pos));\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from\n // the padding fill above, and JS will overflow before user input can make that half non-zero.\n // So we only need to write the low 64 bits here.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return\n // fresh bytes to the caller.\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res as TRet;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.destroyed = destroyed;\n to.finished = finished;\n to.length = length;\n to.pos = pos;\n // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and\n // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.\n if (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n\n/** Initial SHA256 state from RFC 6234 \u00A76.1: the first 32 bits of the fractional parts of the\n * square roots of the first eight prime numbers. Exported as a shared table; callers must treat\n * it as read-only because constructors copy words from it by index. */\nexport const SHA256_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n\n/** Initial SHA224 state `H(0)` from RFC 6234 \u00A76.1. Exported as a shared table; callers must\n * treat it as read-only because constructors copy words from it by index. */\nexport const SHA224_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n\n/** Initial SHA384 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth\n * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only\n * because constructors copy halves from it by index. */\nexport const SHA384_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n\n/** Initial SHA512 state from RFC 6234 \u00A76.3: eight RFC 64-bit `H(0)` words stored as sixteen\n * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first\n * eight prime numbers. Exported as a shared table; callers must treat it as read-only because\n * constructors copy halves from it by index. */\nexport const SHA512_IV: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high\n// }` to match little-endian word order rather than the property names.\nfunction fromBig(\n n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\n// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array\n// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.\nfunction split(lst: bigint[], le = false): TRet {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al] as TRet;\n}\n\n// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS\n// bitwise results back to uint32 first, and little-endian callers must swap.\nconst toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`.\nconst rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s);\n// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32));\n// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s));\n// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half.\nconst rotr32H = (_h: number, l: number): number => l;\n// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half.\nconst rotr32L = (h: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\n// Add two split 64-bit words and return the split `{ h, l }` sum.\n// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out\n// of the low sum and instead use division.\nfunction add(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\n// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`.\nconst add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\n// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`.\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number): number =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`.\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\n// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`.\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\n// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`.\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\n// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`.\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\n", "/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\n/**\n * SHA-224 / SHA-256 round constants from RFC 6234 \u00A75.1: the first 32 bits\n * of the cube roots of the first 64 primes (2..311).\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 \u00A76.2 step 1. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\n\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class 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 protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\n// SHA-384 / SHA-512 round constants from RFC 6234 \u00A75.2:\n// 80 full 64-bit words split into high/low halves.\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n\n// Reusable high-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\n// Reusable low-half schedule buffer for the RFC 6234 \u00A76.4 64-bit `W_t` words.\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class 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 protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\n}\n\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`.\n * These IV literals are checked against that script rather than a dedicated\n * local RFC section.\n */\n\n/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n\n/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and\n * stored as sixteen big-endian 32-bit halves. */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\n\n/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_224 extends SHA2_64B<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\n}\n\n/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared\n * RFC 6234 \u00A76.4 compression engine. */\nexport class _SHA512_256 extends SHA2_64B<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\n}\n\n/**\n * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:\n *\n * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.\n * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n * - Each sha256 hash is executing 2^18 bit operations.\n * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-256.\n * ```ts\n * sha256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-224.\n * ```ts\n * sha224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512.\n * ```ts\n * sha512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-384.\n * ```ts\n * sha384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha384: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/256.\n * ```ts\n * sha512_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_256: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA2-512/224.\n * ```ts\n * sha512_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha512_224: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n/** Transforms values between two representations. */\nexport interface Coder {\n /**\n * Converts a value from the input representation to the output representation.\n * @param from - Value in the source representation.\n * @returns Converted value.\n */\n encode(from: F): T;\n /**\n * Converts a value from the output representation back to the input representation.\n * @param to - Value in the target representation.\n * @returns Converted value.\n */\n decode(to: T): F;\n}\n\n/** Coder that works with byte arrays and strings. */\nexport interface BytesCoder extends Coder {\n /**\n * Encodes bytes into a string representation.\n * @param data - Bytes to encode.\n * @returns Encoded string.\n */\n encode: (data: Uint8Array) => string;\n /**\n * Decodes a string representation into raw bytes.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n */\n decode: (str: string) => Uint8Array;\n}\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n\nfunction isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n // fallback on byte-oriented views.\n return (\n a instanceof Uint8Array ||\n (ArrayBuffer.isView(a) &&\n a.constructor.name === 'Uint8Array' &&\n 'BYTES_PER_ELEMENT' in a &&\n a.BYTES_PER_ELEMENT === 1)\n );\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: TArg): void {\n if (!isBytes(b)) throw new TypeError('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new TypeError('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new TypeError(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (typeof n !== 'number') throw new TypeError(`number expected, got ${typeof n}`);\n if (!Number.isSafeInteger(n)) throw new RangeError(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new TypeError('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new TypeError(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new TypeError(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.\n // Multi-character tokens need a separator that cannot appear inside the chunks.\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n // Mutates the intermediate token array in place while appending pad chars.\n // utils.padding callers that need to preserve their input should pass a copy.\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2)\n throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n// Maximum carry width before the `pos` cycle repeats.\n// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new RangeError(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new RangeError(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n // Canonical decode paths reject leftover whole input words and non-zero pad bits.\n // For Bech32 5->8 regrouping, this is the \"4 bits or less, all zeroes\" tail rule.\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): TRet> {\n anumber(num);\n const _256 = 2 ** 8;\n // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.\n return {\n encode: (bytes: TArg) => {\n if (!isBytes(bytes)) throw new TypeError('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): TRet> {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new RangeError('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new RangeError('radix2: carry overflow');\n // revPadding flips which direction allows a partial zero tail.\n // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.\n return {\n encode: (bytes: TArg) => {\n if (!isBytes(bytes)) throw new TypeError('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\ntype BytesFn = (data: TArg) => TRet;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n // Do not wrap code that needs to preserve exception details.\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(len: number, fn: TArg): TRet> {\n anumber(len);\n // Reject degenerate zero-byte checksums up front so callers don't accidentally\n // build a no-op checksum stage.\n if (len <= 0) throw new RangeError(`checksum length must be positive: ${len}`);\n afn(fn);\n const _fn = fn as BytesFn;\n // Uses the first `len` bytes of fn(data) in both directions.\n // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n return {\n encode(data: TArg) {\n if (!isBytes(data)) throw new TypeError('checksum.encode: input should be Uint8Array');\n const sum = _fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: TArg) {\n if (!isBytes(data)) throw new TypeError('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = _fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\n/**\n * Low-level building blocks used by the exported codecs.\n * @example\n * Build a radix-32 coder from the low-level helpers.\n * ```ts\n * import { utils } from '@scure/base';\n * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = /* @__PURE__ */ Object.freeze({\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n});\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 \u00A78 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(4), alphabet('0123456789ABCDEF'), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 \u00A76 Table 3 uses uppercase letters, and RFC 4648 \u00A73.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 \u00A77 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n )\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 \u00A73.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const alphabet = isUrl ? 'base64url' : 'base64';\n // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n // And checking just for whitespace makes decoding about 3x faster than a full range check.\n // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n )\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n));\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n )\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')\n);\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ')\n);\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz')\n);\n\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr: BytesCoder = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n astr('base58xmr.decode', str);\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n});\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256: TArg): BytesCoder => {\n // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n afn(sha256);\n const _sha256 = sha256 as BytesFn;\n return chain(\n checksum(4, (data: TArg) => _sha256(_sha256(data))),\n base58\n );\n};\n\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check: (sha256: TArg) => BytesCoder = createBase58check;\n\n// Bech32 code\n// -----------\n/** Result of bech32 decoding. */\nexport interface Bech32Decoded {\n /** Human-readable bech32 prefix. */\n prefix: Prefix;\n /** Decoded 5-bit word payload. */\n words: number[];\n}\n/** Result of bech32 decoding with original bytes attached. */\nexport interface Bech32DecodedWithArray {\n /** Human-readable bech32 prefix. */\n prefix: Prefix;\n /** Decoded 5-bit word payload. */\n words: number[];\n /** Decoded payload converted back into raw bytes. */\n bytes: Uint8Array;\n}\n\n// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\n/** bech32 codec surface. */\nexport interface Bech32 {\n /**\n * Encodes a human-readable prefix and 5-bit words into a bech32 string.\n * @param prefix - Human-readable prefix.\n * @param words - 5-bit words or raw bytes.\n * @param limit - Maximum accepted output length, or `false` to disable the limit.\n * @returns Encoded bech32 string.\n */\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n /**\n * Decodes a bech32 string into prefix and words.\n * @param str - Encoded bech32 string.\n * @param limit - Maximum accepted input length, or `false` to disable the limit.\n * @returns Decoded prefix and 5-bit words.\n */\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n decode(str: string, limit?: number | false): Bech32Decoded;\n /**\n * Encodes raw bytes by first converting them to 5-bit words.\n * @param prefix - Human-readable prefix.\n * @param bytes - Raw bytes to encode.\n * @returns Encoded bech32 string.\n */\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n /**\n * Decodes a bech32 string and converts the payload back into bytes.\n * @param str - Encoded bech32 string.\n * @returns Decoded prefix, words, and bytes.\n */\n decodeToBytes(str: string): Bech32DecodedWithArray;\n /**\n * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input.\n * @param str - Encoded bech32 string.\n * @param limit - Maximum accepted input length, or `false` to disable the limit.\n * @returns Decoded prefix and words, or `undefined` for invalid input.\n */\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n /**\n * Converts 5-bit words back into raw bytes.\n * @param to - 5-bit words to decode.\n * @returns Decoded bytes.\n */\n fromWords(to: number[]): Uint8Array;\n /**\n * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing.\n * @param to - 5-bit words to decode.\n * @returns Decoded bytes, or `undefined` for invalid input.\n */\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n /**\n * Converts raw bytes into 5-bit words for bech32 encoding.\n * @param from - Raw bytes to convert.\n * @returns 5-bit words.\n */\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): TRet {\n // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: TArg,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): TRet {\n // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n const { prefix, words } = decode(str, false);\n return {\n prefix,\n words,\n bytes: fromWords(words) as TRet,\n } as TRet;\n }\n\n function encodeFromBytes(prefix: string, bytes: TArg) {\n // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32'));\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii: TRet = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i++) {\n const byte = data[i]!;\n // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n // Latin-1/UTF-8.\n if (byte > 127) throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);\n res += String.fromCharCode(byte);\n }\n return res;\n },\n decode(str: string) {\n if (typeof str !== 'string') throw new TypeError('ascii string expected, got ' + typeof str);\n const res = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n // exact error positions.\n const charCode = str.charCodeAt(i);\n if (charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${str[i]}\" with code ${charCode} at position ${i}`\n );\n }\n res[i] = charCode;\n }\n return res;\n },\n});\n\nconst _isWellFormedShim = (str: string): boolean => {\n // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n // isWellFormed on our tests/fuzz corpus.\n try {\n return encodeURI(str) !== null;\n } catch {\n return false;\n }\n};\nconst _isWellFormed: (str: string) => boolean = /* @__PURE__ */ (() =>\n // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\n typeof ('' as any).isWellFormed === 'function'\n ? (str) => (str as any).isWellFormed()\n : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8Fallback: BytesCoder = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; ) {\n const a = data[i++]!;\n if (a < 0b1000_0000) {\n res += String.fromCharCode(a);\n continue;\n }\n if (a < 0b1100_0010 || i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const b = data[i++]!;\n if ((b & 0b1100_0000) !== 0b1000_0000) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n if (a >= 0b1110_0000) {\n if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const c = data[i++]!;\n if (\n (c & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1110_0000 && b < 0b1010_0000) ||\n (a === 0xed && b >= 0b1010_0000)\n )\n throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n if (a >= 0b1111_0000) {\n if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const d = data[i++]!;\n if (\n a > 0b1111_0100 ||\n (d & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1111_0000 && b < 0b1001_0000) ||\n (a === 0b1111_0100 && b >= 0b1001_0000)\n )\n throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n cp =\n ((a & 7) << 18) |\n ((b & 0b0011_1111) << 12) |\n ((c & 0b0011_1111) << 6) |\n (d & 0b0011_1111);\n }\n }\n if (cp < 0x10000) res += String.fromCharCode(cp);\n else {\n cp -= 0x10000;\n res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n }\n }\n return res;\n },\n decode(str: string) {\n astr('utf8', str);\n if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n // large Node inputs.\n const res = new Uint8Array(str.length * 3);\n let pos = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0b1000_0000) {\n res[pos++] = c;\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n const d = str.charCodeAt(++i);\n c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n }\n if (c >= 0x10000) {\n res[pos++] = (c >> 18) | 0b1111_0000;\n res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n } else if (c >= 0x800) res[pos++] = (c >> 12) | 0b1110_0000;\n else res[pos++] = (c >> 6) | 0b1100_0000;\n if (c >= 0x800) res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n }\n return res.subarray(0, pos);\n },\n});\n\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n * throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n * lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = /* @__PURE__ */ (() => {\n let _utf8Encoder: any;\n let _utf8Decoder: any;\n const utf8Builtin: BytesCoder = {\n // ignoreBOM preserves an explicit leading U+FEFF;\n // fatal rejects invalid UTF-8 bytes instead of replacing them.\n encode(data) {\n abytes(data);\n return (\n _utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))\n ).decode(data);\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n },\n };\n return Object.freeze({\n // Select each direction once at module init, since\n // TextEncoder and TextDecoder can exist independently.\n encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n });\n})();\n// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.\nexport const __TESTS: {\n utf8Fallback: BytesCoder;\n _isWellFormedShim: (str: string) => boolean;\n} = /* @__PURE__ */ Object.freeze({\n utf8Fallback: utf8Fallback,\n _isWellFormedShim: _isWellFormedShim,\n});\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // Require both directions before enabling the native hex path so encode/decode stay symmetric.\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n // Keep local type guards so the native path preserves library-level input errors.\n // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n encode(data) { abytes(data); return (data as any).toHex(); },\n // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n )\n);\n\n/** Built-in codecs exposed through the deprecated string conversion helpers. */\nexport type SomeCoders = {\n /** UTF-8 string codec. */\n utf8: BytesCoder;\n /** Hex codec. */\n hex: BytesCoder;\n /** Uppercase RFC 4648 base16 codec. */\n base16: BytesCoder;\n /** RFC 4648 base32 codec with padding. */\n base32: BytesCoder;\n /** RFC 4648 base64 codec with padding. */\n base64: BytesCoder;\n /** URL-safe base64 codec without `+` or `/`. */\n base64url: BytesCoder;\n /** Bitcoin-style base58 codec. */\n base58: BytesCoder;\n /** Monero-style base58 codec. */\n base58xmr: BytesCoder;\n};\n// prettier-ignore\n// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/**\n * Encodes bytes with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.encode(bytes)`.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * bytesToString('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const bytesToString = (type: CoderType, bytes: TArg): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/**\n * Alias for `bytesToString`.\n * @deprecated Use {@link bytesToString} or the codec directly instead.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @example\n * ```ts\n * str('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const str: (type: CoderType, bytes: TArg) => string = bytesToString; // as in python, but for bytes only\n\n/**\n * Decodes a string with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.decode(text)`.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * stringToBytes('hex', '0102ff');\n * ```\n */\nexport const stringToBytes = (type: CoderType, str: string): TRet => {\n // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str) as TRet;\n};\n/**\n * Alias for `stringToBytes`.\n * @deprecated Use {@link stringToBytes} or the codec directly instead.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @example\n * ```ts\n * bytes('hex', '0102ff');\n * ```\n */\nexport const bytes: (type: CoderType, str: string) => TRet = stringToBytes;\n", "/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\n// The canonical BIP-39 Japanese wordlist starts with \u3042\u3044\u3053\u304F\u3057\u3093.\n// Use that sentinel so generated phrases use U+3000 ideographic spaces.\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\n// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.\n// It also applies NFKD to the \"mnemonic\" + passphrase salt.\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\n// BIP-39 mnemonics are consumed in NFKD form.\n// They must contain 12, 15, 18, 21, or 24 words before checksum validation.\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\n// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new RangeError('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist - Imported wordlist for a specific language.\n * @param strength - Mnemonic strength, from 128 to 256 bits.\n * @returns 12-24 word mnemonic phrase.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new English mnemonic.\n * ```ts\n * import { generateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnemonic = generateMnemonic(wordlist, 128);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new RangeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new TypeError('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new TypeError('wordlist: non-string element: ' + i);\n });\n // BIP-39 appends checksum bits to entropy.\n // It then splits the bitstream into 11-bit indexes for a 2048-word list.\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns Raw entropy bytes.\n * @throws If the mnemonic shape or checksum is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode a mnemonic back into its original entropy bytes.\n * ```ts\n * import { mnemonicToEntropy } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const entropy = mnemonicToEntropy(mnem, wordlist);\n * // Produces the original 16-byte entropy payload.\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n * ```\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy - Byte array.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns 12-24 words.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Convert raw entropy into an English mnemonic.\n * ```ts\n * import { entropyToMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * const mnemonic = entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns `true` when mnemonic checksum and words are valid.\n * @example\n * Validate one English mnemonic.\n * ```ts\n * import { validateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ok = validateMnemonic(\n * 'legal winner thank year wave sausage worth useful legal winner thank yellow',\n * wordlist\n * );\n * // => true\n * ```\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\n// BIP-39 salts PBKDF2 with the UTF-8 NFKD string \"mnemonic\" + passphrase.\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the async PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeed(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\n// BIP-39 seed derivation is independent from mnemonic generation.\n// These helpers normalize the phrase but do not verify checksum or wordlist membership.\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the sync PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = mnemonicToSeedSync(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed with the native WebCrypto PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n//# sourceMappingURL=index.js.map", "/** English BIP39 wordlist. */\nexport const wordlist = /* @__PURE__ */ Object.freeze(`abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n'));\n//# sourceMappingURL=english.js.map", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n/**\n * Validates that a value is a byte array.\n * @param value - Value to validate.\n * @param length - Optional exact byte length.\n * @param title - Optional field name.\n * @returns Original byte array.\n * @example\n * Reject non-byte input before passing data into curve code.\n *\n * ```ts\n * abytes(new Uint8Array(1));\n * ```\n */\nexport const abytes = >(value: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\n/**\n * Validates that a value is a non-negative safe integer.\n * @param n - Value to validate.\n * @param title - Optional field name.\n * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\n/**\n * Encodes bytes as lowercase hex.\n * @param bytes - Bytes to encode.\n * @returns Lowercase hex string.\n * @example\n * Serialize bytes as hex for logging or fixtures.\n *\n * ```ts\n * bytesToHex(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport const bytesToHex: typeof bytesToHex_ = bytesToHex_;\n/**\n * Concatenates byte arrays.\n * @param arrays - Byte arrays to join.\n * @returns Concatenated bytes.\n * @example\n * Join domain-separated chunks into one buffer.\n *\n * ```ts\n * concatBytes(Uint8Array.of(1), Uint8Array.of(2));\n * ```\n */\nexport const concatBytes = (...arrays: TArg): TRet =>\n concatBytes_(...arrays) as TRet;\n/**\n * Decodes lowercase or uppercase hex into bytes.\n * @param hex - Hex string to decode.\n * @returns Decoded bytes.\n * @example\n * Parse fixture hex into bytes before hashing.\n *\n * ```ts\n * hexToBytes('0102');\n * ```\n */\nexport const hexToBytes = (hex: string): TRet => hexToBytes_(hex) as TRet;\n/**\n * Checks whether a value is a Uint8Array.\n * @param a - Value to inspect.\n * @returns `true` when `a` is a Uint8Array.\n * @example\n * Branch on byte input before decoding it.\n *\n * ```ts\n * isBytes(new Uint8Array(1));\n * ```\n */\nexport const isBytes: typeof isBytes_ = isBytes_;\n/**\n * Reads random bytes from the platform CSPRNG.\n * @param bytesLength - Number of random bytes to read.\n * @returns Fresh random bytes.\n * @example\n * Generate a random seed for a keypair.\n *\n * ```ts\n * randomBytes(2);\n * ```\n */\nexport const randomBytes = (bytesLength?: number): TRet =>\n randomBytes_(bytesLength) as TRet;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg): TRet;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg) => TRet;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg, message: TArg) => TRet;\n/**\n * Validates that a flag is boolean.\n * @param value - Value to validate.\n * @param title - Optional field name.\n * @returns Original value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Reject non-boolean option flags early.\n *\n * ```ts\n * abool(true);\n * ```\n */\nexport function abool(value: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\n\n/**\n * Validates that a value is a non-negative bigint or safe integer.\n * @param n - Value to validate.\n * @returns The same validated value.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate one integer-like value before serializing it.\n *\n * ```ts\n * abignumber(1n);\n * ```\n */\nexport function abignumber(n: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\n}\n\n/**\n * Validates that a value is a safe integer.\n * @param value - Integer to validate.\n * @param title - Optional field name.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Validate a window size before scalar arithmetic uses it.\n *\n * ```ts\n * asafenumber(1);\n * ```\n */\nexport function asafenumber(value: number, title: string = ''): void {\n if (typeof value !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected number, got type=' + typeof value);\n }\n if (!Number.isSafeInteger(value)) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(prefix + 'expected safe integer, got ' + value);\n }\n}\n\n/**\n * Encodes a bigint into even-length big-endian hex.\n * The historical \"unpadded\" name only means \"no fixed-width field padding\"; odd-length hex still\n * gets one leading zero nibble so the result always represents whole bytes.\n * @param num - Number to encode.\n * @returns Big-endian hex string.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Encode a scalar into hex without a `0x` prefix.\n *\n * ```ts\n * numberToHexUnpadded(255n);\n * ```\n */\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\n\n/**\n * Parses a big-endian hex string into bigint.\n * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the\n * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error.\n * @param hex - Hex string without `0x`.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Parse a scalar from fixture hex.\n *\n * ```ts\n * hexToNumber('ff');\n * ```\n */\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian\n/**\n * Parses big-endian bytes into bigint.\n * @param bytes - Bytes in big-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in network byte order.\n *\n * ```ts\n * bytesToNumberBE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberBE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex_(bytes));\n}\n/**\n * Parses little-endian bytes into bigint.\n * @param bytes - Bytes in little-endian order.\n * @returns Parsed bigint value.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Read a scalar encoded in little-endian form.\n *\n * ```ts\n * bytesToNumberLE(Uint8Array.of(1, 0));\n * ```\n */\nexport function bytesToNumberLE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\n\n/**\n * Encodes a bigint into fixed-length big-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes. Must be greater than zero.\n * @returns Big-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\n const hex = n.toString(16);\n // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error.\n if (hex.length > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet;\n}\n/**\n * Encodes a bigint into fixed-length little-endian bytes.\n * @param n - Number to encode.\n * @param len - Output length in bytes.\n * @returns Little-endian byte array.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet {\n return numberToBytesBE(n, len).reverse() as TRet;\n}\n// Unpadded, rarely used\n/**\n * Encodes a bigint into variable-length big-endian bytes.\n * @param n - Number to encode.\n * @returns Variable-length big-endian bytes.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Serialize a bigint without fixed-width padding.\n *\n * ```ts\n * numberToVarBytesBE(255n);\n * ```\n */\nexport function numberToVarBytesBE(n: number | bigint): TRet {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet;\n}\n\n// Compares 2 u8a-s in kinda constant time\n/**\n * Compares two byte arrays in constant-ish time.\n * @param a - Left byte array.\n * @param b - Right byte array.\n * @returns `true` when bytes match.\n * @example\n * Compare two encoded points without early exit.\n *\n * ```ts\n * equalBytes(Uint8Array.of(1), Uint8Array.of(1));\n * ```\n */\nexport function equalBytes(a: TArg, b: TArg): boolean {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n * @param bytes - Bytes to copy.\n * @returns Detached copy.\n * @example\n * Make an isolated copy before mutating serialized bytes.\n *\n * ```ts\n * copyBytes(Uint8Array.of(1, 2, 3));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as `TextEncoder` for ASCII or throws.\n * @param ascii - ASCII input text.\n * @returns Encoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Encode an ASCII domain-separation tag.\n *\n * ```ts\n * asciiToBytes('ABC');\n * ```\n */\nexport function asciiToBytes(ascii: string): TRet {\n if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii);\n return Uint8Array.from(ascii, (c, i) => {\n const charCode = c.charCodeAt(0);\n if (c.length !== 1 || charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n;\n\n/**\n * Checks whether a bigint lies inside a half-open range.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * @returns `true` when the value is inside the range.\n * @example\n * Check whether a candidate scalar fits the field order.\n *\n * ```ts\n * inRange(2n, 1n, 3n);\n * ```\n */\nexport function inRange(n: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n\n/**\n * Asserts `min <= n < max`. NOTE: upper bound is exclusive.\n * @param title - Value label for error messages.\n * @param n - Candidate value.\n * @param min - Inclusive lower bound.\n * @param max - Exclusive upper bound.\n * Wrong-type inputs are not separated from out-of-range values here: they still flow through the\n * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Assert that a bigint stays within one half-open range.\n *\n * ```ts\n * aInRange('x', 2n, 1n, 256n);\n * ```\n */\nexport function aInRange(title: string, n: bigint, min: bigint, max: bigint): void {\n // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n // consider P=256n, min=0n, max=P\n // - a for min=0 would require -1: `inRange('x', x, -1n, P)`\n // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)`\n // - our way is the cleanest: `inRange('x', x, 0n, P)\n if (!inRange(n, min, max))\n throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n * @param n - Value to inspect.\n * @returns Bit length.\n * @throws If the value is negative. {@link Error}\n * @example\n * Measure the bit length of a scalar before serialization.\n *\n * ```ts\n * bitLen(8n);\n * ```\n */\nexport function bitLen(n: bigint): number {\n // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a\n // contract bug and must not silently collapse to zero bits.\n if (n < _0n) throw new Error('expected non-negative bigint, got ' + n);\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw\n * bigint shift semantics; because the mask is built as `1n << pos`,\n * they currently collapse to `0n` and make the helper a no-op.\n * @returns Bit as bigint.\n * @example\n * Gets single bit at position.\n *\n * ```ts\n * bitGet(5n, 0);\n * ```\n */\nexport function bitGet(n: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n * @param n - Source value.\n * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics,\n * so they currently behave like left shifts.\n * @param value - Whether the bit should be set.\n * @returns Updated bigint.\n * @example\n * Sets single bit at position.\n *\n * ```ts\n * bitSet(0n, 1, true);\n * ```\n */\nexport function bitSet(n: bigint, pos: number, value: boolean): bigint {\n const mask = _1n << BigInt(pos);\n // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched.\n return value ? n | mask : n & ~mask;\n}\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift\n * semantics and therefore produce `-1n`.\n * @returns Bitmask value.\n * @example\n * Calculate mask for N bits.\n *\n * ```ts\n * bitMask(4);\n * ```\n */\nexport const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred = (v: TArg) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0`\n * is not rejected here and would make the internal generate loop non-progressing.\n * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length.\n * @param hmacFn - HMAC implementation.\n * @returns Function that will call DRBG until the predicate returns anything\n * other than `undefined`.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Build a deterministic nonce generator for RFC6979-style signing.\n *\n * ```ts\n * import { createHmacDrbg } from '@noble/curves/utils.js';\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg\n): TRet<(seed: Uint8Array, predicate: Pred) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet => new Uint8Array(len) as TRet;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\n // Step B, Step C: set hashLen to 8*ceil(hlen/8).\n // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures.\n let v: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = u8n(hashLen);\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n // hmac(k)(v, ...values)\n const h = (...msgs: TArg) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg = NULL) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: TArg, pred: TArg>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred) => T>;\n}\n\n/**\n * Validates declared required and optional field types on a plain object.\n * Extra keys are intentionally ignored because many callers validate only the subset they use from\n * richer option bags or runtime objects.\n * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Check user options before building a curve helper.\n *\n * ```ts\n * validateObject({ flag: true }, { flag: 'boolean' });\n * ```\n */\nexport function validateObject(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\n\n/**\n * Throws not implemented error.\n * @returns Never returns.\n * @throws If the unfinished code path is reached. {@link Error}\n * @example\n * Surface the placeholder error from an unfinished code path.\n *\n * ```ts\n * try {\n * notImplemented();\n * } catch {}\n * ```\n */\nexport const notImplemented = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\n}\n", "/**\n * Utils for modular division and fields.\n * Field over 11 is a finite (Galois) field is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\n// Numbers aren't used in x25519 / x448 builds\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2);\n// prettier-ignore\nconst _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5);\n// prettier-ignore\nconst _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9);\nconst _16n = /* @__PURE__ */ BigInt(16);\n\n/**\n * @param a - Dividend value.\n * @param b - Positive modulus.\n * @returns Reduced value in `[0, b)` only when `b` is positive.\n * @throws If the modulus is not positive. {@link Error}\n * @example\n * Normalize a bigint into one field residue.\n *\n * ```ts\n * mod(-1n, 5n);\n * ```\n */\nexport function mod(a: bigint, b: bigint): bigint {\n if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b);\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to a power with modular reduction.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen\n * modulus instead of relying on the `power===0/1` fast paths to normalize it.\n * @param num - Base value.\n * @param power - Exponent value.\n * @param modulo - Reduction modulus.\n * @returns Modular exponentiation result.\n * @throws If the modulus or exponent is invalid. {@link Error}\n * @example\n * Raise one bigint to a modular power.\n *\n * ```ts\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n * ```\n */\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\n\n/**\n * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`.\n * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen\n * modulus; the `power===0` fast path intentionally returns the input unchanged.\n * @param x - Base value.\n * @param power - Number of squarings.\n * @param modulo - Reduction modulus.\n * @returns Repeated-squaring result.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Apply repeated squaring inside one field.\n *\n * ```ts\n * pow2(3n, 2n, 11n);\n * ```\n */\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power);\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n/**\n * Inverses number over modulo.\n * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}.\n * @param number - Value to invert.\n * @param modulo - Positive modulus.\n * @returns Multiplicative inverse.\n * @throws If the modulus is invalid or the inverse does not exist. {@link Error}\n * @example\n * Compute one modular inverse with the extended Euclidean algorithm.\n *\n * ```ts\n * invert(3n, 11n);\n * ```\n */\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare(Fp: TArg>, root: T, n: T): void {\n const F = Fp as IField;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\n\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp: TArg>, n: T) {\n const F = Fp as IField;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV\n// pseudocode verbatim.\nfunction sqrt5mod8(Fp: TArg>, n: T) {\n const F = Fp as IField;\n const p5div8 = (F.ORDER - _5n) / _8n;\n const n2 = F.mul(n, _2n);\n const v = F.pow(n2, p5div8);\n const nv = F.mul(n, v);\n const i = F.mul(F.mul(nv, _2n), v);\n const root = F.mul(nv, F.sub(i, F.ONE));\n assertIsSquare(F, root, n);\n return root;\n}\n\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<(Fp: IField, n: T) => T> {\n const Fp_ = Field(P);\n const tn = tonelliShanks(P);\n const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n return ((Fp: TArg>, n: T): T => {\n const F = Fp as IField;\n let tv1 = F.pow(n, c4); // 1. tv1 = x^c4\n let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1\n const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1\n const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1\n const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x\n const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x\n tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x\n const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2\n assertIsSquare(F, root, n);\n return root;\n }) as TRet<(Fp: IField, n: T) => T>;\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * This implementation is variable-time: it searches data-dependently for the first non-residue `Z`\n * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape.\n * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P - field order\n * @returns function that takes field Fp (created from P) and number n\n * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error}\n * @example\n * Construct a square-root helper for primes that need Tonelli-Shanks.\n *\n * ```ts\n * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = tonelliShanks(17n)(Fp, 4n);\n * ```\n */\nexport function tonelliShanks(P: bigint): TRet<(Fp: IField, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\n // Factor P - 1 = Q * 2^S, where Q is odd\n let Q = P - _1n;\n let S = 0;\n while (Q % _2n === _0n) {\n Q /= _2n;\n S++;\n }\n\n // Find the first quadratic non-residue Z >= 2\n let Z = _2n;\n const _Fp = Field(P);\n while (FpLegendre(_Fp, Z) === 1) {\n // Basic primality test for P. After x iterations, chance of\n // not finding quadratic non-residue is 2^x, so 2^1000.\n if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P');\n }\n // Fast-path; usually done before Z, but we do \"primality test\".\n if (S === 1) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>;\n\n // Slow-path\n // TODO: test on Fp2 and others\n let cc = _Fp.pow(Z, Q); // c = z^Q\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp: TArg>, n: T): T {\n const F = Fp as IField;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\n // Initialize variables for the main loop\n let M = S;\n let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor\n let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\n // Find the smallest i >= 1 such that t^(2^i) \u2261 1 (mod P)\n let t_tmp = F.sqr(t); // t^(2^1)\n while (!F.eql(t_tmp, F.ONE)) {\n i++;\n t_tmp = F.sqr(t_tmp); // t^(2^2)...\n if (i === M) throw new Error('Cannot find square root');\n }\n\n // Calculate the exponent for b: 2^(M - i - 1)\n const exponent = _1n << BigInt(M - i - 1); // bigint is important\n const b = F.pow(c, exponent); // b = 2^(M - i - 1)\n\n // Update variables\n M = i;\n c = F.sqr(b); // c = b^2\n t = F.mul(t, c); // t = (t * b^2)\n R = F.mul(R, b); // R = R*b\n }\n return R;\n } as TRet<(Fp: IField, n: T) => T>;\n}\n\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P \u2261 3 (mod 4)\n * 2. P \u2261 5 (mod 8)\n * 3. P \u2261 9 (mod 16)\n * 4. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness\n * (used for hash-to-curve).\n * @param P - Field order.\n * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time\n * behavior and this selector assumes prime-field-style integer moduli.\n * @throws If the field is unsupported or the square root does not exist. {@link Error}\n * @example\n * Choose the square-root helper appropriate for one field modulus.\n *\n * ```ts\n * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrt = FpSqrt(17n)(Fp, 4n);\n * ```\n */\nexport function FpSqrt(P: bigint): TRet<(Fp: IField, n: T) => T> {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<(Fp: IField, n: T) => T>;\n // P \u2261 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4)\n if (P % _16n === _9n) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n/**\n * @param num - Value to inspect.\n * @param modulo - Field modulus.\n * @returns `true` when the least-significant little-endian bit is set.\n * @throws If the modulus is invalid for `mod(...)`. {@link Error}\n * @example\n * Inspect the low bit used by little-endian sign conventions.\n *\n * ```ts\n * isNegativeLE(3n, 11n);\n * ```\n */\nexport const isNegativeLE = (num: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\n// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime\n// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and\n// field-specific extras like `isOdd` are left to the callers that actually need them.\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\n/**\n * @param field - Field implementation.\n * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it\n * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or\n * field-specific extras beyond positive `BYTES` / `BITS`.\n * @throws If the field shape or numeric metadata are invalid. {@link Error}\n * @example\n * Check that a field implementation exposes the operations curve code expects.\n *\n * ```ts\n * import { Field, validateField } from '@noble/curves/abstract/modular.js';\n * const Fp = validateField(Field(17n));\n * ```\n */\nexport function validateField(field: TArg>): TRet> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\n // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the\n // numeric shape checks above but still breaks encoding helpers and cached-length assumptions.\n if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @param Fp - Field implementation.\n * @param num - Base value.\n * @param power - Exponent value.\n * @returns Powered field element.\n * @throws If the exponent is negative. {@link Error}\n * @example\n * Raise one field element to a public exponent.\n *\n * ```ts\n * import { Field, FpPow } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpPow(Fp, 3n, 5n);\n * ```\n */\nexport function FpPow(Fp: TArg>, num: T, power: bigint): T {\n const F = Fp as IField;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch(Fp: TArg>, nums: T[], passZero = false): T[] {\n const F = Fp as IField;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\n // Walk from first to last, multiply them by each other MOD p\n const multipliedAcc = nums.reduce((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = acc;\n return F.mul(acc, num);\n }, F.ONE);\n // Invert last element\n const invertedAcc = F.inv(multipliedAcc);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (F.is0(num)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param lhs - Dividend value.\n * @param rhs - Divisor value.\n * @returns Division result.\n * @throws If the divisor is non-invertible. {@link Error}\n * @example\n * Divide one field element by another.\n *\n * ```ts\n * import { Field, FpDiv } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const x = FpDiv(Fp, 6n, 3n);\n * ```\n */\nexport function FpDiv(Fp: TArg>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\n\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) \u2261 1 if a is a square (mod p), quadratic residue\n * * (a | p) \u2261 -1 if a is not a square (mod p), quadratic non residue\n * * (a | p) \u2261 0 if a \u2261 0 (mod p)\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns Legendre symbol.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Compute the Legendre symbol of one field element.\n *\n * ```ts\n * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const symbol = FpLegendre(Fp, 4n);\n * ```\n */\nexport function FpLegendre(Fp: TArg>, n: T): -1 | 0 | 1 {\n const F = Fp as IField;\n // We can use 3rd argument as optional cache of this value\n // but seems unneeded for now. The operation is very fast.\n const p1mod2 = (F.ORDER - _1n) / _2n;\n const powered = F.pow(n, p1mod2);\n const yes = F.eql(powered, F.ONE);\n const zero = F.eql(powered, F.ZERO);\n const no = F.eql(powered, F.neg(F.ONE));\n if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\n\n/**\n * @param Fp - Field implementation.\n * @param n - Value to inspect.\n * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict \"quadratic\n * residue\" terminology often reserves that name for the non-zero square class.\n * @throws If the field returns an invalid Legendre symbol value. {@link Error}\n * @example\n * Check whether one field element has a square root in the field.\n *\n * ```ts\n * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const isSquare = FpIsSquare(Fp, 4n);\n * ```\n */\nexport function FpIsSquare(Fp: TArg>, n: T): boolean {\n const l = FpLegendre(Fp as IField, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\n};\n/**\n * @param n - Curve order. Callers are expected to pass a positive order.\n * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached\n * value when overriding the derived bit length.\n * @returns Byte and bit lengths.\n * @throws If the order or cached bit length is invalid. {@link Error}\n * @example\n * Measure the encoding sizes needed for one modulus.\n *\n * ```ts\n * nLength(255n);\n * ```\n */\nexport function nLength(n: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n);\n if (nBitLength !== undefined && nBitLength < 1)\n throw new Error('invalid n length: expected positive bit length, got ' + nBitLength);\n const bits = bitLen(n);\n // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison\n // any math that relies on the derived field metadata.\n if (nBitLength !== undefined && nBitLength < bits)\n throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n}>;\n// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the\n// cached helper write would keep the field surface externally mutable.\nconst FIELD_SQRT = new WeakMap>();\nclass _Field implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\n // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv\n // would stop modeling field arithmetic.\n if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = undefined;\n this.isLE = false;\n if (opts != null && typeof opts === 'object') {\n // Cached bit lengths are trusted here and should already be positive / consistent with ORDER.\n if (typeof opts.BITS === 'number') _nbitLength = opts.BITS;\n if (typeof opts.sqrt === 'function')\n // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties\n // explicitly instead of relying on writable prototype shadowing via assignment.\n Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true });\n if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n this.ORDER = ORDER;\n this.BITS = nBitLength;\n this.BYTES = nByteLength;\n Object.freeze(this);\n }\n\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\n if (typeof num !== 'bigint')\n throw new TypeError('invalid field element: expected bigint, got ' + typeof num);\n return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible\n }\n is0(num: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\n // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping\n // the field instance itself mutable.\n let sqrt = FIELD_SQRT.get(this);\n if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\n // Serialize fixed-width limbs without re-validating the field range. Callers that need a\n // canonical encoding must pass a valid element; some protocols intentionally serialize raw\n // residues here and reduce or validate them elsewhere.\n return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);\n }\n fromBytes(bytes: Uint8Array, skipValidation = false) {\n abytes(bytes);\n const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this;\n if (allowedLengths) {\n // `allowedLengths` must list real positive byte lengths; otherwise empty input would get\n // padded into zero and silently decode as a field element.\n if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {\n throw new Error(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\n }\n const padded = new Uint8Array(BYTES);\n // isLE add 0 to right, !isLE to the left.\n padded.set(bytes, isLE ? 0 : padded.length - bytes.length);\n bytes = padded;\n }\n if (bytes.length !== BYTES)\n throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n if (modFromBytes) scalar = mod(scalar, ORDER);\n if (!skipValidation)\n if (!this.isValid(scalar))\n throw new Error('invalid field element: outside of range 0..ORDER');\n // Range validation is optional here because some protocols intentionally decode raw residues\n // and reduce or validate them elsewhere.\n return scalar;\n }\n // TODO: we don't need it here, move out to separate fn\n invertBatch(lst: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\n }\n // We can't move this out because Fp6, Fp12 implement it\n // and it's unclear what to return in there.\n cmov(a: bigint, b: bigint, condition: boolean) {\n // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject\n // non-boolean selectors here instead of letting JS truthiness silently change arithmetic.\n abool(condition, 'condition');\n return condition ? b : a;\n }\n}\n// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\n\n/**\n * Creates a finite field. Major performance optimizations:\n * * 1. Denormalized operations like mulN instead of mul.\n * * 2. Identical object shape: never add or remove keys.\n * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`.\n * Fragile: always run a benchmark on a change.\n * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for\n * all elements for performance and protocol-flexibility reasons; callers are responsible for\n * supplying valid elements when they need canonical field behavior.\n * This is low-level code, please make sure you know what you're doing.\n *\n * Note about field properties:\n * * CHARACTERISTIC p = prime number, number of elements in main subgroup.\n * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.\n *\n * @param ORDER - field order, probably prime, or could be composite\n * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}.\n * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight\n * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`.\n * @example\n * Construct one prime field with optional overrides.\n *\n * ```ts\n * Field(11n);\n * ```\n */\nexport function Field(ORDER: bigint, opts: FieldOpts = {}): TRet> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`,\n * which is the only square root but is not odd.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the odd square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtOdd(Fp, 4n);\n * ```\n */\nexport function FpSqrtOdd(Fp: TArg>, elm: T): T {\n const F = Fp as IField;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? root : F.neg(root);\n}\n\n/**\n * @param Fp - Field implementation.\n * @param elm - Value to square-root.\n * @returns Even square root.\n * @throws If the field lacks oddness checks or the square root does not exist. {@link Error}\n * @example\n * Select the even square root when two roots exist.\n *\n * ```ts\n * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const root = FpSqrtEven(Fp, 4n);\n * ```\n */\nexport function FpSqrtEven(Fp: TArg>, elm: T): T {\n const F = Fp as IField;\n if (!F.isOdd) throw new Error(\"Field doesn't have isOdd\");\n const root = F.sqrt(elm);\n return F.isOdd(root) ? F.neg(root) : root;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an\n * order greater than 1.\n * @returns byte length of field\n * @throws If the field order is not a bigint. {@link Error}\n * @example\n * Read the fixed-width byte length of one field.\n *\n * ```ts\n * getFieldBytesLength(255n);\n * ```\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate.\n if (fieldOrder <= _1n) throw new Error('field order must be greater than 1');\n // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1.\n const bitLength = bitLen(fieldOrder - _1n);\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger\n * absolute floor for policy reasons.\n * @param fieldOrder - number of field elements greater than 1, usually CURVE.n.\n * @returns byte length of target hash\n * @throws If the field order is invalid. {@link Error}\n * @example\n * Compute the minimum hash length needed for field reduction.\n *\n * ```ts\n * getMinHashLength(255n);\n * ```\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard\n * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look\n * accidentally acceptable for real scalar derivation.\n * See {@link https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ | Kudelski's modulo-bias guide},\n * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and\n * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380\n * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`.\n * @param key - Uniform input bytes.\n * @param fieldOrder - Size of subgroup.\n * @param isLE - interpret hash bytes as LE num\n * @returns valid private scalar\n * @throws If the hash length or field order is invalid for scalar reduction. {@link Error}\n * @example\n * Map hash output into a private scalar range.\n *\n * ```ts\n * mapHashToField(new Uint8Array(48).fill(1), 255n);\n * ```\n */\nexport function mapHashToField(\n key: TArg,\n fieldOrder: bigint,\n isLE = false\n): TRet {\n abytes(key);\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = Math.max(getMinHashLength(fieldOrder), 16);\n // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge\n // inputs: easier to reason about JS timing / allocation behavior.\n if (len < minLen || len > 1024)\n throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons

> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns the affine field type for a point instance (`P_F

== P.F`). */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F == PC.P.F`). */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P == PC.P`). */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\n/**\n * Validates the static surface of a point constructor.\n * This is only a cheap sanity check for the constructor hooks and fields consumed by generic\n * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself.\n * @param Point - Runtime point constructor.\n * @throws On missing constructor hooks or malformed field metadata. {@link TypeError}\n * @example\n * Check that one point constructor exposes the static hooks generic helpers need.\n *\n * ```ts\n * import { ed25519 } from '@noble/curves/ed25519.js';\n * import { validatePointCons } from '@noble/curves/abstract/curve.js';\n * validatePointCons(ed25519.Point);\n * ```\n */\nexport function validatePointCons

>(Point: CurvePointCons

): void {\n const pc = Point as unknown as CurvePointCons;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * Input points are left unchanged; the normalized points are returned as fresh instances.\n * @param c - Point constructor.\n * @param points - Projective points.\n * @returns Fresh projective points reconstructed from normalized affine coordinates.\n * @example\n * Batch-normalize projective points with a single shared inversion.\n *\n * ```ts\n * import { normalizeZ } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);\n * ```\n */\nexport function normalizeZ

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\n\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param scalars - array of L scalars (aka secret keys / bigints)\n * @returns MSM result point. Empty input is accepted and returns the identity.\n * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error}\n * @example\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { pippenger } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]);\n * ```\n */\nexport function pippenger

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\n const fieldN = c.Fn;\n validateMSMPoints(points, c);\n validateMSMScalars(scalars, fieldN);\n const plength = points.length;\n const slength = scalars.length;\n if (plength !== slength) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) windowSize = 2;\n const MASK = bitMask(windowSize);\n const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n let sum = zero;\n for (let i = lastBits; i >= 0; i -= windowSize) {\n buckets.fill(zero);\n for (let j = 0; j < slength; j++) {\n const scalar = scalars[j];\n const wbits = Number((scalar >> BigInt(i)) & MASK);\n buckets[wbits] = buckets[wbits].add(points[j]);\n }\n let resI = zero; // not using this will do small speed-up, but will lose ct\n // Skip first bucket, because it is zero\n for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n sumI = sumI.add(buckets[j]);\n resI = resI.add(sumI);\n }\n sum = sum.add(resI);\n if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: TArg>, isLE?: boolean): TRet> {\n if (field) {\n // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback\n // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov\n // behavior.\n if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet>;\n } else {\n return Field(order, { isLE }) as unknown as TRet>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn = {\n /** Base field used for curve coordinates. */\n Fp: IField;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField;\n};\n\n/**\n * Validates basic CURVE shape and field membership, then creates fields.\n * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or\n * that the curve equation itself is otherwise sane.\n * @param type - Curve family.\n * @param CURVE - Curve parameters.\n * @param curveOpts - Optional field overrides:\n * - `Fp` (optional): Optional base-field override.\n * - `Fn` (optional): Optional scalar-field override.\n * @param FpFnLE - Whether field encoding is little-endian.\n * @returns Frozen curve parameters and fields.\n * @throws If the curve parameters or field overrides are invalid. {@link Error}\n * @example\n * Build curve fields from raw constants before constructing a curve instance.\n *\n * ```ts\n * const curve = createCurveFields('weierstrass', {\n * p: 17n,\n * n: 19n,\n * h: 1n,\n * a: 2n,\n * b: 2n,\n * Gx: 5n,\n * Gy: 1n,\n * });\n * ```\n */\nexport function createCurveFields(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: TArg>> = {},\n FpFnLE?: boolean\n): TRet & { CURVE: ValidCurveParams }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && val > _0n))\n throw new Error(`CURVE.${p} must be positive bigint`);\n }\n const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);\n const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);\n const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\n for (const p of params) {\n // @ts-ignore\n if (!Fp.isValid(CURVE[p]))\n throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);\n }\n CURVE = Object.freeze(Object.assign({}, CURVE));\n return { CURVE, Fp, Fn } as TRet & { CURVE: ValidCurveParams }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\n/**\n * @param randomSecretKey - Secret-key generator.\n * @param getPublicKey - Public-key derivation helper.\n * @returns Keypair generator.\n * @example\n * Build a `keygen()` helper from existing secret-key and public-key primitives.\n *\n * ```ts\n * import { createKeygen } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);\n * const pair = keygen();\n * ```\n */\nexport function createKeygen(\n randomSecretKey: Function,\n getPublicKey: TArg\n): TRet {\n return function keygen(seed?: TArg) {\n const secretKey = randomSecretKey(seed) as TRet;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet };\n };\n}\n", "/**\n * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields.\n * API may change at any time. The code has not been audited. Feature requests are welcome.\n * @module\n */\nimport type { TArg } from '../utils.ts';\nimport type { IField } from './modular.ts';\n\n/** Array-like coefficient storage that can be mutated in place. */\nexport interface MutableArrayLike {\n /** Element access by numeric index. */\n [index: number]: T;\n /** Current amount of stored coefficients. */\n length: number;\n /**\n * Return a sliced copy using the same storage shape.\n * @param start - Inclusive start index.\n * @param end - Exclusive end index.\n * @returns Sliced copy.\n */\n slice(start?: number, end?: number): this;\n /**\n * Iterate over stored coefficients in order.\n * @returns Coefficient iterator.\n */\n [Symbol.iterator](): Iterator;\n}\n\n/**\n * Concrete polynomial containers accepted by the high-level `poly(...)` helpers.\n * Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)`\n * intentionally keeps runtime dispatch on plain arrays and typed-array views.\n */\nexport type PolyStorage = T[] | (MutableArrayLike & ArrayBufferView);\n\nfunction checkU32(n: number) {\n // 0xff_ff_ff_ff\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new Error('wrong u32 integer:' + n);\n return n;\n}\n\n/**\n * Checks if integer is in form of `1 << X`.\n * @param x - Integer to inspect.\n * @returns `true` when the value is a power of two.\n * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Validate that an FFT size is a power of two.\n *\n * ```ts\n * isPowerOfTwo(8);\n * ```\n */\nexport function isPowerOfTwo(x: number): boolean {\n checkU32(x);\n return (x & (x - 1)) === 0 && x !== 0;\n}\n\n/**\n * @param n - Input value.\n * @returns Next power of two within the u32/array-length domain.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Round an integer up to the FFT size it needs.\n *\n * ```ts\n * nextPowerOfTwo(9);\n * ```\n */\nexport function nextPowerOfTwo(n: number): number {\n checkU32(n);\n if (n <= 1) return 1;\n // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result:\n // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1.\n if (n > 0x8000_0000) throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\n\n/**\n * @param n - Value to reverse.\n * @param bits - Number of bits to use.\n * @returns Bit-reversed integer.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Reverse the low `bits` bits of one index.\n *\n * ```ts\n * reverseBits(3, 3);\n * ```\n */\nexport function reverseBits(n: number, bits: number): number {\n checkU32(n);\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);\n let reversed = 0;\n for (let i = 0; i < bits; i++, n >>>= 1) reversed = (reversed << 1) | (n & 1);\n // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain.\n return reversed >>> 0;\n}\n\n/**\n * Similar to `bitLen(x)-1` but much faster for small integers, like indices.\n * @param n - Input value.\n * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`.\n * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\n * @example\n * Compute the radix-2 stage count for one transform size.\n *\n * ```ts\n * log2(8);\n * ```\n */\nexport function log2(n: number): number {\n checkU32(n);\n return 31 - Math.clz32(n);\n}\n\n/**\n * Moves lowest bit to highest position, which at first step splits\n * array on even and odd indices, then it applied again to each part,\n * which is core of fft\n * @param values - Mutable coefficient array.\n * @returns Mutated input array.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Reorder coefficients into bit-reversed order in place.\n *\n * ```ts\n * const values = Uint8Array.from([0, 1, 2, 3]);\n * bitReversalInplace(values);\n * ```\n */\nexport function bitReversalInplace>(values: T): T {\n const n = values.length;\n // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it.\n if (!isPowerOfTwo(n)) throw new Error('expected positive power-of-two length, got ' + n);\n const bits = log2(n);\n for (let i = 0; i < n; i++) {\n const j = reverseBits(i, bits);\n if (i < j) {\n const tmp = values[i];\n values[i] = values[j];\n values[j] = tmp;\n }\n }\n return values;\n}\n\n/**\n * @param values - Input values.\n * @returns Reordered copy.\n * @throws If the array length is not a positive power of two. {@link Error}\n * @example\n * Return a reordered copy instead of mutating the input in place.\n *\n * ```ts\n * const reordered = bitReversalPermutation([0, 1, 2, 3]);\n * ```\n */\nexport function bitReversalPermutation(values: T[]): T[] {\n return bitReversalInplace(values.slice()) as T[];\n}\n\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field: TArg>) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++);\n return G;\n}\n\n/** Cached roots-of-unity tables derived from one finite field. */\nexport type RootsOfUnity = {\n /** Generator and 2-adicity metadata for the cached field. */\n info: { G: bigint; oddFactor: bigint; powerOfTwo: number };\n /**\n * Return the natural-order roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Natural-order roots for that size.\n */\n roots: (bits: number) => bigint[];\n /**\n * Return the bit-reversal permutation of the roots for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Bit-reversed roots.\n */\n brp(bits: number): bigint[];\n /**\n * Return the inverse roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Inverse roots.\n */\n inverse(bits: number): bigint[];\n /**\n * Return one primitive root used by a radix-2 stage.\n * @param bits - Transform size as `log2(N)`.\n * @returns Primitive root for that stage.\n */\n omega: (bits: number) => bigint;\n /**\n * Drop all cached root tables.\n * @returns Nothing.\n */\n clear: () => void;\n};\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.\n * @param field - Field implementation.\n * @param generator - Optional generator override.\n * @returns Roots-of-unity cache.\n * @example\n * Cache roots once, then ask for the omega table of one FFT size.\n *\n * ```ts\n * import { rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const roots = rootsOfUnity(Field(17n));\n * const omega = roots.omega(4);\n * ```\n */\nexport function rootsOfUnity(field: TArg>, generator?: bigint): RootsOfUnity {\n // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo\n let oddFactor = field.ORDER - _1n;\n let powerOfTwo = 0;\n for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n);\n\n // Find non quadratic residue\n let G = generator !== undefined ? BigInt(generator) : findGenerator(field);\n // Powers of generator\n const omegas: bigint[] = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache: bigint[][] = [];\n const checkBits = (bits: number) => {\n checkU32(bits);\n if (bits > 31 || bits > powerOfTwo)\n throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo);\n return bits;\n };\n const precomputeRoots = (maxPower: number) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power]) continue; // Skip if we've already computed roots for this power\n const rootsAtPower: bigint[] = [];\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\n rootsCache[power] = rootsAtPower;\n }\n return rootsCache[maxPower];\n };\n const brpCache = new Map();\n const inverseCache = new Map();\n // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only.\n\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not neccesary isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits: number): bigint[] => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits: number): bigint[] {\n const b = checkBits(bits);\n if (brpCache.has(b)) return brpCache.get(b)!;\n else {\n const res = bitReversalPermutation(this.roots(b));\n brpCache.set(b, res);\n return res;\n }\n },\n inverse(bits: number): bigint[] {\n const b = checkBits(bits);\n if (inverseCache.has(b)) return inverseCache.get(b)!;\n else {\n const res = field.invertBatch(this.roots(b));\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits: number): bigint => omegas[checkBits(bits)],\n clear: (): void => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n\n/** Polynomial coefficient container used by the FFT helpers. */\nexport type Polynomial = MutableArrayLike;\n\n/**\n * Arithmetic operations used by the generic FFT implementation.\n *\n * Maps great to Field, but not to Group (EC points):\n * - inv from scalar field\n * - we need multiplyUnsafe here, instead of multiply for speed\n * - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse\n */\nexport type FFTOpts = {\n /**\n * Add two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Sum coefficient.\n */\n add: (a: T, b: T) => T;\n /**\n * Subtract two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Difference coefficient.\n */\n sub: (a: T, b: T) => T;\n /**\n * Multiply one coefficient by a scalar/root factor.\n * @param a - Coefficient value.\n * @param scalar - Scalar/root factor.\n * @returns Scaled coefficient.\n */\n mul: (a: T, scalar: R) => T;\n /**\n * Invert one scalar/root factor.\n * @param a - Scalar/root factor.\n * @returns Inverse factor.\n */\n inv: (a: R) => R;\n};\n\n/** Configuration for one low-level FFT loop. */\nexport type FFTCoreOpts = {\n /** Transform size. Must be a power of two. */\n N: number;\n /** Stage roots for the selected transform size. */\n roots: Polynomial;\n /** Whether to run the DIT variant instead of DIF. */\n dit: boolean;\n /** Whether to invert butterfly placement for decode-oriented layouts. */\n invertButterflies?: boolean;\n /** Number of initial stages to skip. */\n skipStages?: number;\n /** Whether to apply bit-reversal permutation at the boundary. */\n brp?: boolean;\n};\n\n/**\n * Callable low-level FFT loop over one polynomial storage shape.\n * @param values - Polynomial coefficients to transform in place.\n * @returns The mutated input polynomial.\n */\nexport type FFTCoreLoop =

>(values: P) => P;\n\n/**\n * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors:\n *\n * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey\n * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande\n *\n * DIT takes brp input, returns natural output.\n * DIF takes natural input, returns brp output.\n *\n * The output is actually identical. Time / frequence distinction is not meaningful\n * for Polynomial multiplication in fields.\n * Which means if protocol supports/needs brp output/inputs, then we can skip this step.\n *\n * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega\n * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa\n * @param F - Field operations.\n * @param coreOpts - FFT configuration:\n * - `N`: Transform size. Must be a power of two.\n * - `roots`: Stage roots for the selected transform size.\n * - `dit`: Whether to run the DIT variant instead of DIF.\n * - `invertButterflies` (optional): Whether to invert butterfly placement.\n * - `skipStages` (optional): Number of initial stages to skip.\n * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary.\n * @returns Low-level FFT loop.\n * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error}\n * @example\n * Constructs different flavors of FFT.\n *\n * ```ts\n * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const roots = rootsOfUnity(Fp).roots(2);\n * const loop = FFTCore(Fp, { N: 4, roots, dit: true });\n * const values = loop([1n, 2n, 3n, 4n]);\n * ```\n */\nexport const FFTCore = (F: FFTOpts, coreOpts: FFTCoreOpts): FFTCoreLoop => {\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n const bits = log2(N);\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense.\n if (roots.length !== N)\n throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`);\n const isDit = dit !== invertButterflies;\n isDit;\n return

>(values: P): P => {\n if (values.length !== N) throw new Error('FFT: wrong Polynomial length');\n if (dit && brp) bitReversalInplace(values);\n for (let i = 0, g = 1; i < bits - skipStages; i++) {\n // For each stage s (sub-FFT length m = 2^s)\n const s = dit ? i + 1 + skipStages : bits - i;\n const m = 1 << s;\n const m2 = m >> 1;\n const stride = N >> s;\n // Loop over each subarray of length m\n for (let k = 0; k < N; k += m) {\n // Loop over each butterfly within the subarray\n for (let j = 0, grp = g++; j < m2; j++) {\n const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride;\n const i0 = k + j;\n const i1 = k + j + m2;\n const omega = roots[rootPos];\n const b = values[i1];\n const a = values[i0];\n // Inlining gives us 10% perf in kyber vs functions\n if (isDit) {\n const t = F.mul(b, omega); // Standard DIT butterfly\n values[i0] = F.add(a, t);\n values[i1] = F.sub(a, t);\n } else if (invertButterflies) {\n values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode)\n values[i1] = F.mul(F.sub(b, a), omega);\n } else {\n values[i0] = F.add(a, b); // Standard DIF butterfly\n values[i1] = F.mul(F.sub(a, b), omega);\n }\n }\n }\n }\n if (!dit && brp) bitReversalInplace(values);\n return values;\n };\n};\n\n/** Forward and inverse FFT helpers for one coefficient domain. */\nexport type FFTMethods = {\n /**\n * Apply the forward transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Transformed copy.\n */\n direct

>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\n /**\n * Apply the inverse transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Inverse-transformed copy.\n */\n inverse

>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\n};\n\n/**\n * NTT aka FFT over finite field (NOT over complex numbers).\n * Naming mirrors other libraries.\n * @param roots - Roots-of-unity cache.\n * @param opts - Field operations. See {@link FFTOpts}.\n * @returns Forward and inverse FFT helpers.\n * @example\n * NTT aka FFT over finite field (NOT over complex numbers).\n *\n * ```ts\n * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const fft = FFT(rootsOfUnity(Fp), Fp);\n * const values = fft.direct([1n, 2n, 3n, 4n]);\n * ```\n */\nexport function FFT(roots: RootsOfUnity, opts: FFTOpts): FFTMethods {\n const getLoop = (\n N: number,\n roots: Polynomial,\n brpInput = false,\n brpOutput = false\n ): (

>(values: P) => P) => {\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n return (values) =>\n FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));\n }\n if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false });\n if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false });\n return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural\n };\n return {\n direct

>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n return getLoop(N, roots.roots(bits), brpInput, brpOutput)

(values.slice());\n },\n inverse

>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice());\n const ivm = opts.inv(BigInt(values.length)); // scale\n // we can get brp output if we use dif instead of dit!\n for (let i = 0; i < res.length; i++) res[i] = opts.mul(res[i], ivm);\n // Allows to re-use non-inverted roots, but is VERY fragile\n // return [res[0]].concat(res.slice(1).reverse());\n // inverse calculated as pow(-1), which transforms into \u03C9^{-kn} (-> reverses indices)\n return res;\n },\n };\n}\n\n/**\n * Factory that allocates one polynomial storage container.\n * Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted,\n * because the quadratic `mul()` / `convolve()` paths and the Kronecker-\u03B4 shortcut in\n * `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly.\n * @param len - Requested amount of coefficients.\n * @param elm - Optional fill value.\n * @returns Newly allocated polynomial container.\n */\nexport type CreatePolyFn

, T> = (len: number, elm?: T) => P;\n\n/** High-level polynomial helpers layered on top of FFT and field arithmetic. */\nexport type PolyFn

, T> = {\n /** Roots-of-unity cache used by the helper namespace. */\n roots: RootsOfUnity;\n /** Factory used to allocate new polynomial containers. */\n create: CreatePolyFn;\n /** Optional enforced polynomial length. */\n length?: number;\n\n /**\n * Compute the polynomial degree.\n * @param a - Polynomial coefficients.\n * @returns Polynomial degree.\n */\n degree: (a: P) => number;\n /**\n * Extend or truncate one polynomial to a requested length.\n * @param a - Polynomial coefficients.\n * @param len - Target length.\n * @returns Resized polynomial.\n */\n extend: (a: P, len: number) => P;\n /**\n * Add two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Sum polynomial.\n */\n add: (a: P, b: P) => P;\n /**\n * Subtract two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Difference polynomial.\n */\n sub: (a: P, b: P) => P;\n /**\n * Multiply by another polynomial or by one scalar.\n * @param a - Left polynomial.\n * @param b - Right polynomial or scalar.\n * @returns Product polynomial.\n */\n mul: (a: P, b: P | T) => P;\n /**\n * Multiply coefficients point-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Point-wise product polynomial.\n */\n dot: (a: P, b: P) => P;\n /**\n * Multiply two polynomials with convolution.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Convolution product.\n */\n convolve: (a: P, b: P) => P;\n /**\n * Apply a point-wise coefficient shift by powers of one factor.\n * @param p - Polynomial coefficients.\n * @param factor - Shift factor.\n * @returns Shifted polynomial.\n */\n shift: (p: P, factor: bigint) => P;\n /**\n * Clone one polynomial container.\n * @param a - Polynomial coefficients.\n * @returns Cloned polynomial.\n */\n clone: (a: P) => P;\n /**\n * Evaluate one polynomial on a basis vector.\n * @param a - Polynomial coefficients.\n * @param basis - Basis vector.\n * @returns Evaluated field element.\n */\n eval: (a: P, basis: P) => T;\n /** Helpers for monomial-basis polynomials. */\n monomial: {\n /** Build the monomial basis vector for one evaluation point. */\n basis: (x: T, n: number) => P;\n /** Evaluate a polynomial in the monomial basis. */\n eval: (a: P, x: T) => T;\n };\n /** Helpers for Lagrange-basis polynomials. */\n lagrange: {\n /** Build the Lagrange basis vector for one evaluation point. */\n basis: (x: T, n: number, brp?: boolean) => P;\n /** Evaluate a polynomial in the Lagrange basis. */\n eval: (a: P, x: T, brp?: boolean) => T;\n };\n /**\n * Build the vanishing polynomial for a root set.\n * @param roots - Root set.\n * @returns Vanishing polynomial.\n */\n vanishing: (roots: P) => P;\n};\n\n/**\n * Poly wants a cracker.\n *\n * Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is\n * function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:\n *\n * - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`\n * - **Basis** is array of functions\n * - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)\n * - **Array size** is domain size\n * - **Lattice** is matrix (Polynomial of Polynomials)\n * @param field - Field implementation.\n * @param roots - Roots-of-unity cache.\n * @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array`\n * and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected.\n * @param fft - Optional FFT implementation.\n * @param length - Optional fixed polynomial length.\n * @returns Polynomial helper namespace.\n * @example\n * Build polynomial helpers, then convolve two coefficient arrays.\n *\n * ```ts\n * import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const poly17 = poly(Fp, rootsOfUnity(Fp));\n * const product = poly17.convolve([1n, 2n], [3n, 4n]);\n * ```\n */\nexport function poly(\n field: TArg>,\n roots: RootsOfUnity,\n create?: undefined,\n fft?: FFTMethods,\n length?: number\n): PolyFn;\nexport function poly>(\n field: TArg>,\n roots: RootsOfUnity,\n create: CreatePolyFn,\n fft?: FFTMethods,\n length?: number\n): PolyFn;\nexport function poly>(\n field: TArg>,\n roots: RootsOfUnity,\n create?: CreatePolyFn,\n fft?: FFTMethods,\n length?: number\n): PolyFn {\n const F = field as IField;\n const _create =\n create ||\n (((len: number, elm?: T): T[] => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn);\n\n // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted\n // polynomial containers concrete instead of trying to support arbitrary wrappers.\n const isPoly = (x: any): x is P => {\n if (Array.isArray(x)) return true;\n if (!ArrayBuffer.isView(x)) return false;\n const v = x as unknown as ArrayLike & { slice?: unknown; [Symbol.iterator]?: unknown };\n return (\n typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function'\n );\n };\n const checkLength = (...lst: P[]): number => {\n if (!lst.length) return 0;\n for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i);\n const L = lst[0].length;\n for (let i = 1; i < lst.length; i++)\n if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);\n if (length !== undefined && L !== length)\n throw new Error(`poly: expected fixed length ${length}, got ${L}`);\n return L;\n };\n function findOmegaIndex(x: T, n: number, brp = false): number {\n const bits = log2(n);\n const omega = brp ? roots.brp(bits) : roots.roots(bits);\n for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) return i;\n return -1;\n }\n // TODO: mutating versions for mlkem/mldsa\n return {\n roots,\n create: _create,\n length,\n extend: (a: P, len: number): P => {\n checkLength(a);\n const out = _create(len, F.ZERO);\n // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep\n // `extend()` consistent with typed arrays and with its documented truncate behavior.\n for (let i = 0; i < Math.min(a.length, len); i++) out[i] = a[i];\n return out;\n },\n degree: (a: P): number => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;\n return -1;\n },\n add: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a: P, b: P | T): P => {\n if (isPoly(b)) {\n const len = checkLength(a, b);\n if (fft) {\n const A = fft.direct(a, false, true);\n const B = fft.direct(b, false, true);\n for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false) as P;\n } else {\n // NOTE: this is quadratic and mostly for compat tests with FFT\n const res = _create(len);\n for (let i = 0; i < len; i++) {\n for (let j = 0; j < len; j++) {\n const k = (i + j) % len; // wrap mod length\n res[k] = F.add(res[k], F.mul(a[i], b[j]));\n }\n }\n return res;\n }\n } else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a: P, b: P): P {\n const len = nextPowerOfTwo(a.length + b.length - 1);\n return this.mul(this.extend(a, len), this.extend(b, len));\n },\n shift(p: P, factor: bigint): P {\n const out = _create(checkLength(p));\n out[0] = p[0];\n for (let i = 1, power = F.ONE; i < p.length; i++) {\n power = F.mul(power, factor);\n out[i] = F.mul(p[i], power);\n }\n return out;\n },\n clone: (a: P): P => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++) out[i] = a[i];\n return out;\n },\n eval: (a: P, basis: P): T => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x: T, n: number): P => {\n const out = _create(n);\n let pow = F.ONE;\n for (let i = 0; i < n; i++) {\n out[i] = pow;\n pow = F.mul(pow, x);\n }\n return out;\n },\n eval: (a: P, x: T): T => {\n checkLength(a);\n // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way\n let acc = F.ZERO;\n for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x: T, n: number, brp = false, weights?: P): P => {\n const bits = log2(n);\n const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [\u03C9\u2070, \u03C9\u00B9, ..., \u03C9\u207F\u207B\u00B9]\n const out = _create(n);\n // Fast Kronecker-\u03B4 shortcut\n const idx = findOmegaIndex(x, n, brp);\n if (idx !== -1) {\n out[idx] = F.ONE;\n return out;\n }\n const tm = F.pow(x, BigInt(n));\n const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n) as T)); // c = (x\u207F - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T);\n const inv = F.invertBatch(denom as any as T[]);\n for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i]));\n return out;\n },\n eval(a: P, x: T, brp = false): T {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1) return a[idx]; // fast path\n const L = this.basis(x, a.length, brp); // L\u1D62(x)\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots: P): P {\n checkLength(roots);\n const out = _create(roots.length + 1, F.ZERO);\n out[0] = F.ONE;\n for (const r of roots) {\n const neg = F.neg(r);\n for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]);\n out[0] = F.mul(out[0], neg);\n }\n return out;\n },\n };\n}\n", "/**\n * Short Weierstrass curve methods. The formula is: y\u00B2 = x\u00B3 + ax + b.\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\nimport { ahash } from '@noble/hashes/utils.js';\nimport {\n abignumber,\n abool,\n abytes,\n aInRange,\n asafenumber,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type HmacFn,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n FpIsSquare,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n /** Cube root of unity used by the GLV endomorphism. */\n beta: bigint;\n /** Reduced lattice basis used for scalar splitting. */\n basises?: EndoBasis;\n /**\n * Optional custom scalar-splitting helper.\n * Receives one scalar and returns two half-sized scalar components.\n */\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\n// We construct the basis so `den` is always positive and equals `n`,\n// but the `num` sign depends on the basis, not on the secret value.\n// Exact half-way cases round away from zero, which keeps the split symmetric\n// around the reduced-basis boundaries used by endomorphism decomposition.\nconst divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n /** Whether the first split scalar should be negated. */\n k1neg: boolean;\n /** Absolute value of the first split scalar. */\n k1: bigint;\n /** Whether the second split scalar should be negated. */\n k2neg: boolean;\n /** Absolute value of the second split scalar. */\n k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\n // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)`\n // Since part can be negative, we need to do this on point.\n // Callers must provide a reduced GLV basis whose vectors satisfy\n // `a + b * lambda \u2261 0 (mod n)`; this helper only sees the basis and `n`.\n // Reject unreduced scalars instead of silently treating them mod n.\n aInRange('scalar', k, _0n, n);\n // TODO: verifyScalar function which consumes lambda\n const [[a1, b1], [a2, b2]] = basis;\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n // |k1|/|k2| is < sqrt(N), but can be negative.\n // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead.\n let k1 = k - c1 * a1 - c2 * a2;\n let k2 = -c1 * b1 - c2 * b2;\n const k1neg = k1 < _0n;\n const k2neg = k2 < _0n;\n if (k1neg) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // This should only happen on wrong bases.\n // Also, the math inside is complex enough that this guard is worth keeping.\n const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N\n if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) {\n throw new Error('splitScalar (endomorphism): failed for k');\n }\n return { k1neg, k1, k2neg, k2 };\n}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n /** Whether to hash the message before signature recovery. */\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n /** Whether to hash the message before verification. */\n prehash?: boolean;\n /** Whether to reject high-S signatures. */\n lowS?: boolean;\n /** Signature encoding to accept. */\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n * security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n /** Whether to hash the message before signing. */\n prehash?: boolean;\n /** Whether to normalize signatures into the low-S half-order. */\n lowS?: boolean;\n /** Signature encoding to produce. */\n format?: ECDSASignatureFormat;\n /** Optional hedging input for deterministic k generation. */\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): D {\n validateObject(opts);\n const optsn = {} as D;\n // Normalize only the declared option subset from `def`; unknown keys are\n // intentionally ignored so shared / superset option bags stay valid here too.\n // `extraEntropy` stays an opaque payload until the signing path consumes it.\n for (let optName of Object.keys(def) as (keyof D)[]) {\n // @ts-ignore\n optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName];\n }\n abool(optsn.lowS!, 'lowS');\n abool(optsn.prehash!, 'prehash');\n if (optsn.format !== undefined) validateSigFormat(optsn.format);\n return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /**\n * Encode the point into compressed or uncompressed SEC1 bytes.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point bytes.\n */\n toBytes(isCompressed?: boolean): TRet;\n /**\n * Encode the point into compressed or uncompressed SEC1 hex.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point hex.\n */\n toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n /**\n * Return the curve parameters captured by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Weierstrass curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts = Partial<{\n /** Optional base-field override. */\n Fp: IField;\n /** Optional scalar-field override. */\n Fn: IField;\n /** Whether the point constructor accepts infinity points. */\n allowInfinityPoint: boolean;\n /** Optional GLV endomorphism data. */\n endo: EndomorphismOpts;\n /** Optional torsion-check override. */\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n /** Optional cofactor-clearing override. */\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n /** Optional custom point decoder. */\n fromBytes: (bytes: TArg) => AffinePoint;\n /** Optional custom point encoder. */\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => TRet;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n * low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n * `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n /** Default low-S policy for this ECDSA instance. */\n lowS: boolean;\n /** HMAC implementation used by RFC6979 DRBG. */\n hmac: HmacFn;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet;\n /** Hash-to-integer conversion override. */\n bits2int: (bytes: TArg) => bigint;\n /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n bits2int_modN: (bytes: TArg) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\n /**\n * Generate a secret/public key pair.\n * @param seed - Optional seed material.\n * @returns Secret/public key pair.\n */\n keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg, isCompressed?: boolean) => TRet;\n /**\n * Compute the shared secret point from a secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded shared point.\n */\n getSharedSecret: (\n secretKeyA: TArg,\n publicKeyB: TArg,\n isCompressed?: boolean\n ) => TRet;\n /** Point constructor used by this ECDH instance. */\n Point: WeierstrassPointCons;\n /** Validation and random-key helpers. */\n utils: {\n /** Check whether a secret key has the expected encoding. */\n isValidSecretKey: (secretKey: TArg) => boolean;\n /** Check whether a public key decodes to a valid point. */\n isValidPublicKey: (publicKey: TArg, isCompressed?: boolean) => boolean;\n /** Generate a valid random secret key. */\n randomSecretKey: (seed?: TArg) => TRet;\n };\n /** Byte lengths for keys and signatures exposed by this curve. */\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n /**\n * Sign a message with the given secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n /**\n * Verify a signature against a message and public key.\n * @param signature - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n * @returns Whether the signature is valid.\n */\n verify: (\n signature: TArg,\n message: TArg,\n publicKey: TArg,\n opts?: TArg\n ) => boolean;\n /**\n * Recover the public key encoded into a recoverable signature.\n * @param signature - Recoverable signature bytes.\n * @param message - Message bytes.\n * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n * @returns Encoded recovered public key.\n */\n recoverPublicKey(\n signature: TArg,\n message: TArg,\n opts?: TArg\n ): TRet;\n /** Signature constructor and parser helpers. */\n Signature: ECDSASignatureCons;\n}\n/**\n * @param m - Error message.\n * @example\n * Throw a DER-specific error when signature parsing encounters invalid bytes.\n *\n * ```ts\n * new DERErr('bad der');\n * ```\n */\nexport class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n}\n/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n // asn.1 DER encoding utils\n /**\n * DER-specific error constructor.\n * @param m - Error message.\n * @returns DER-specific error instance.\n */\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n /** Low-level tag-length-value helpers used by DER encoders. */\n _tlv: {\n /**\n * Encode one TLV record.\n * @param tag - ASN.1 tag byte.\n * @param data - Hex-encoded value payload.\n * @returns Encoded TLV string.\n */\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n /**\n * Decode one TLV record and return the value plus leftover bytes.\n * @param tag - Expected ASN.1 tag byte.\n * @param data - Remaining DER bytes.\n * @returns Parsed value plus leftover bytes.\n */\n decode(tag: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }>;\n };\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n /** Positive-integer DER helpers used by ECDSA signature encoding. */\n _int: {\n /**\n * Encode one positive bigint as a DER INTEGER.\n * @param num - Positive integer to encode.\n * @returns Encoded DER INTEGER.\n */\n encode(num: bigint): string;\n /**\n * Decode one DER INTEGER into a bigint.\n * @param data - DER INTEGER bytes.\n * @returns Decoded bigint.\n */\n decode(data: TArg): bigint;\n };\n /**\n * Parse a DER signature into `{ r, s }`.\n * @param bytes - DER signature bytes.\n * @returns Parsed signature components.\n */\n toSig(bytes: TArg): { r: bigint; s: bigint };\n /**\n * Encode `{ r, s }` as a DER signature.\n * @param sig - Signature components.\n * @returns DER-encoded signature hex.\n */\n hexFromSig(sig: { r: bigint; s: bigint }): string;\n};\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and\n * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.\n * @example\n * ASN.1 DER encoding utilities.\n *\n * ```ts\n * const der = DER.hexFromSig({ r: 1n, s: 2n });\n * ```\n */\nexport const DER: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof data);\n // Internal helper: callers hand this already-validated hex payload, so we only enforce\n // byte alignment here instead of re-validating every nibble.\n if (data.length & 1) throw new E('tlv.encode: unpadded data');\n const dataLen = data.length / 2;\n const len = numberToHexUnpadded(dataLen);\n if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big');\n // length of length with long form flag\n const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : '';\n const t = numberToHexUnpadded(tag);\n return t + lenLen + len + data;\n },\n // v - value, l - left bytes (unparsed)\n decode(tag: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }> {\n const { Err: E } = DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv');\n const first = data[pos++];\n // First bit of first length byte is the short/long form flag.\n const isLong = !!(first & 0b1000_0000);\n let length = 0;\n if (!isLong) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\n },\n },\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n _int: {\n encode(num: bigint): string {\n const { Err: E } = DER;\n abignumber(num);\n if (num < _0n) throw new E('integer: negative integers are not allowed');\n let hex = numberToHexUnpadded(num);\n // Pad with zero byte if negative flag is present\n if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: TArg): bigint {\n const { Err: E } = DER;\n if (data.length < 1) throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative');\n // Single-byte zero `00` is the canonical DER INTEGER encoding for zero.\n if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000))\n throw new E('invalid signature integer: unnecessary leading zero');\n return bytesToNumberBE(data);\n },\n },\n toSig(bytes: TArg): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\n const rs = tlv.encode(0x02, int.encode(sig.r));\n const ss = tlv.encode(0x02, int.encode(sig.s));\n const seq = rs + ss;\n return tlv.encode(0x30, seq);\n },\n};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);\n\n/**\n * Creates weierstrass Point constructor, based on specified curve options.\n *\n * See {@link WeierstrassOpts}.\n * @param params - Curve parameters. See {@link WeierstrassOpts}.\n * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.\n * @returns Weierstrass point constructor.\n * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}\n *\n * @example\n * Construct a point type from explicit Weierstrass curve parameters.\n *\n * ```js\n * const opts = {\n * p: 0xfffffffffffffffffffffffffffffffeffffac73n,\n * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,\n * h: 1n,\n * a: 0n,\n * b: 7n,\n * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,\n * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,\n * };\n * const secp160k1_Point = weierstrass(opts);\n * ```\n */\nexport function weierstrass(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp as IField;\n const Fn = validated.Fn as IField;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp as TArg>, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): TRet {\n // SEC 1 v2.0 \u00A72.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet;\n const { x, y } = point.toAffine();\n const bx = Fp.toBytes(x);\n abool(isCompressed, 'isCompressed');\n if (isCompressed) {\n assertCompressionIsSupported();\n const hasEvenY = !Fp.isOdd!(y);\n return concatBytes(pprefix(hasEvenY), bx) as TRet;\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet;\n }\n }\n function pointFromBytes(bytes: TArg) {\n abytes(bytes, undefined, 'Point');\n const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65\n const length = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\n // No actual validation is done here: use .assertValidity()\n if (length === comp && (head === 0x02 || head === 0x03)) {\n const x = Fp.fromBytes(tail);\n if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y: T;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n } catch (sqrtError) {\n const err = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n throw new Error('bad point: is not on curve, sqrt error' + err);\n }\n assertCompressionIsSupported();\n const evenY = Fp.isOdd!(y);\n const evenH = (head & 1) === 1; // ECDSA-specific\n if (evenH !== evenY) y = Fp.neg(y);\n return { x, y };\n } else if (length === uncomp && head === 0x04) {\n // TODO: more checks\n const L = Fp.BYTES;\n const x = Fp.fromBytes(tail.subarray(0, L));\n const y = Fp.fromBytes(tail.subarray(L, L * 2));\n if (!isValidXY(x, y)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x\u00B2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\n\n // TODO: move top-level\n /** Checks whether equation holds for given x, y: y\u00B2 == x\u00B3 + ax + b */\n function isValidXY(x: T, y: T): boolean {\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\n\n // Keep constructor-time generator validation cheap: callers are responsible for supplying the\n // correct prime-order base point, while eager subgroup checks here would slow heavy module imports.\n // Test 1: equation y\u00B2 = x\u00B3 + ax + b should work for generator point.\n if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point');\n\n // Test 2: discriminant \u0394 part should be non-zero: 4a\u00B3 + 27b\u00B2 != 0.\n // Guarantees curve is genus-1, smooth (non-singular).\n const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown): asserts other is Point {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\n this.X = acoord('x', X);\n // This is not just about ZERO / infinity: ambient curves can have real\n // finite points with y=0. Those points are 2-torsion, so they cannot lie\n // in the odd prime-order subgroups this point type is meant to represent.\n this.Y = acoord('y', Y, true);\n this.Z = acoord('z', Z);\n Object.freeze(this);\n }\n\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: TArg): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\n const p = this;\n if (p.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points\n // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard.\n if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = p.toAffine();\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: WeierstrassPoint): boolean {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: WeierstrassPoint): Point {\n aprjpoint(other);\n const { X: X1, Y: Y1, Z: Z1 } = this;\n const { X: X2, Y: Y2, Z: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: WeierstrassPoint) {\n // Validate before calling `negate()` so wrong inputs fail with the point guard\n // instead of leaking a foreign `negate()` error.\n aprjpoint(other);\n return this.add(other.negate());\n }\n\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\n // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.\n // In key/signature-style callers, those values usually mean broken hash/scalar plumbing,\n // and failing closed is safer than silently producing the identity point.\n if (!Fn.isValidNot0(scalar)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\n const sc = scalar;\n // Public-scalar callers may need 0, but n and larger values stay rejected here too.\n // Reducing them mod n would turn bad caller input into an accidental identity point.\n if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\n\n /**\n * Converts Projective point to affine (x, y) coordinates.\n * (X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch\n */\n toAffine(invertedZ?: T): AffinePoint {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y };\n const is0 = p.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);\n const x = Fp.mul(X, iz);\n const y = Fp.mul(Y, iz);\n const zz = Fp.mul(Z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n }\n\n /**\n * Checks whether Point is free of torsion elements (is in prime subgroup).\n * Always torsion-free for cofactor=1 curves.\n */\n isTorsionFree(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n // Default fallback assumes the cofactor fits the usual subgroup-scalar\n // multiplyUnsafe() contract. Curves with larger / structured cofactors\n // should define a clearCofactor override anyway (e.g. psi/Frobenius maps).\n return this.multiplyUnsafe(cofactor);\n }\n\n isSmallOrder(): boolean {\n if (cofactor === _1n) return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n\n toBytes(isCompressed = true): TRet {\n abool(isCompressed, 'isCompressed');\n // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (bits >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n\n/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n /** Signature component `r`. */\n readonly r: bigint;\n /** Signature component `s`. */\n readonly s: bigint;\n /** Optional recovery bit for recoverable signatures. */\n readonly recovery?: number;\n /**\n * Return a copy of the signature with a recovery bit attached.\n * @param recovery - Recovery bit to attach.\n * @returns Signature with an attached recovery bit.\n */\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n /**\n * Check whether the signature uses the high-S half-order.\n * @returns Whether the signature uses the high-S half-order.\n */\n hasHighS(): boolean;\n /**\n * Recover the public key from the hashed message and recovery bit.\n * @param messageHash - Hashed message bytes.\n * @returns Recovered public-key point.\n */\n recoverPublicKey(messageHash: TArg): WeierstrassPoint;\n /**\n * Encode the signature into bytes.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature bytes.\n */\n toBytes(format?: string): TRet;\n /**\n * Encode the signature into hex.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature hex.\n */\n toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n /** Create a signature from `r`, `s`, and an optional recovery bit. */\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n /**\n * Decode a signature from bytes.\n * @param bytes - Encoded signature bytes.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromBytes(bytes: TArg, format?: ECDSASignatureFormat): ECDSASignature;\n /**\n * Decode a signature from hex.\n * @param hex - Encoded signature hex.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet;\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio(\n Fp: TArg>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp as IField) as IField;\n // Generic implementation\n const q = F.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU(\n Fp: TArg>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n const F = validateField(Fp as IField) as IField;\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 \u00A76.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: TArg>, Fn: TArg>) {\n return {\n secretKey: Fn.BYTES,\n publicKey: 1 + Fp.BYTES,\n publicKeyUncompressed: 1 + 2 * Fp.BYTES,\n publicKeyHasPrefix: true,\n // Raw compact `(r || s)` signature width; DER and recovered signatures use\n // different lengths outside this helper.\n signature: 2 * Fn.BYTES,\n };\n}\n\n/**\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n * This helper ensures no signature functionality is present. Less code, smaller bundle size.\n * @param Point - Weierstrass point constructor.\n * @param ecdhOpts - Optional randomness helpers:\n * - `randomBytes` (optional): Optional RNG override.\n * @returns ECDH helper namespace.\n * @example\n * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.\n *\n * ```ts\n * import { ecdh } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const dh = ecdh(p256.Point);\n * const alice = dh.keygen();\n * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);\n * ```\n */\nexport function ecdh(\n Point: WeierstrassPointCons,\n ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet }> = {}\n): ECDH {\n const { Fn } = Point;\n const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes;\n // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte\n // minimum even on toy curves.\n const lengths = Object.assign(getWLengths(Point.Fp, Fn), {\n seed: Math.max(getMinHashLength(Fn.ORDER), 16),\n });\n\n function isValidSecretKey(secretKey: TArg) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: TArg, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\n }\n\n /**\n * Produces cryptographically secure secret key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n function randomSecretKey(seed?: TArg): TRet {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet;\n }\n\n /**\n * Computes public key for a secret key. Checks for validity of the secret key.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(secretKey: TArg, isCompressed = true): TRet {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: TArg): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n if (!isBytes(item)) return undefined;\n const l = abytes(item, undefined, 'key').length;\n const isPub = l === publicKey || l === publicKeyUncompressed;\n const isSec = l === secretKey || !!allowedLengths?.includes(l);\n // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous.\n if (isPub && isSec) return undefined;\n return isPub;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes encoded shared point from secret key A and public key B.\n * Checks: 1) secret key validity 2) shared key is on-curve.\n * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.\n * Returns the encoded shared point on purpose: callers that need `x_P`\n * can derive it from the encoded point, but `x_P` alone cannot recover the\n * point/parity back.\n * This helper only exposes the fully validated public-key path, not cofactor DH.\n * @param isCompressed - whether to return compact (default), or full key\n * @returns shared point encoding\n */\n function getSharedSecret(\n secretKeyA: TArg,\n publicKeyB: TArg,\n isCompressed = true\n ): TRet {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key');\n const s = Fn.fromBytes(secretKeyA);\n const b = Point.fromBytes(publicKeyB); // checks for being on-curve\n return b.multiply(s).toBytes(isCompressed);\n }\n\n const utils = {\n isValidSecretKey,\n isValidPublicKey,\n randomSecretKey,\n };\n const keygen = createKeygen(randomSecretKey, getPublicKey);\n Object.freeze(utils);\n Object.freeze(lengths);\n\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\n\n/**\n * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.\n *\n * @param Point - created using {@link weierstrass} function\n * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)\n * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:\n * - `lowS`: Default low-S policy.\n * - `hmac`: HMAC implementation used by RFC6979 DRBG.\n * - `randomBytes`: Optional RNG override.\n * - `bits2int`: Optional hash-to-int conversion override.\n * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.\n *\n * @returns ECDSA helper namespace.\n * @example\n * Create an ECDSA signer/verifier bundle for one curve implementation.\n *\n * ```ts\n * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';\n * import { p256 } from '@noble/curves/nist.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const p256ecdsa = ecdsa(p256.Point, sha256);\n * const { secretKey, publicKey } = p256ecdsa.keygen();\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = p256ecdsa.sign(msg, secretKey);\n * const isValid = p256ecdsa.verify(sig, msg, publicKey);\n * ```\n */\nexport function ecdsa(\n Point: WeierstrassPointCons,\n hash: TArg,\n ecdsaOpts: TArg = {}\n): ECDSA {\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash as CHash;\n ahash(hash_);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac =\n ecdsaOpts.hmac === undefined\n ? (key: TArg, msg: TArg) => nobleHmac(hash_, key, msg)\n : (ecdsaOpts.hmac as HmacFn);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\n extraEntropy: false,\n };\n // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature\n // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n.\n // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the\n // smallest such lift is 1 + 2n, not 2n.\n const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\n if (!Fn.isValidNot0(num))\n throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);\n return num;\n }\n function assertRecoverableCurve(): void {\n // ECDSA recovery only supports curves where the current recovery id can distinguish\n // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches.\n // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1.\n // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n.\n // To easily get i, we either need to:\n // a. increase amount of valid recid values (4, 5...); OR\n // b. prohibit recovered signatures for those curves.\n if (hasLargeRecoveryLifts)\n throw new Error('\"recovered\" sig type is not supported for cofactor >2 curves');\n }\n function validateSigLength(bytes: TArg, format: ECDSASignatureFormat) {\n validateSigFormat(format);\n const size = lengths.signature!;\n const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined;\n return abytes(bytes, sizer);\n }\n\n /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\n this.r = validateRS('r', r); // r in [1..N-1];\n this.s = validateRS('s', s); // s in [1..N-1];\n if (recovery != null) {\n assertRecoverableCurve();\n if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: TArg,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\n return new Signature(r, s);\n }\n if (format === 'recovered') {\n recid = bytes[0];\n format = 'compact';\n bytes = bytes.subarray(1);\n }\n const L = lengths.signature! / 2;\n const r = bytes.subarray(0, L);\n const s = bytes.subarray(L, L * 2);\n return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);\n }\n\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n // Unlike the top-level helper below, this method expects a digest that has\n // already been hashed to the curve's message representative.\n recoverPublicKey(messageHash: TArg): WeierstrassPoint {\n const { r, s } = this;\n const recovery = this.assertRecovery();\n const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;\n if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x');\n const x = Fp.toBytes(radj);\n const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x));\n const ir = Fn.inv(radj); // r^-1\n const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash\n const u1 = Fn.create(-h * ir); // -hr^-1\n const u2 = Fn.create(s * ir); // sr^-1\n // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data.\n const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet;\n const { r, s } = this;\n const rb = Fn.toBytes(r);\n const sb = Fn.toBytes(s);\n if (format === 'recovered') {\n assertRecoverableCurve();\n return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet;\n }\n return concatBytes(rb, sb) as TRet;\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int: (bytes: TArg) => bigint =\n ecdsaOpts.bits2int === undefined\n ? function bits2int_def(bytes: TArg): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) throw new Error('input is too large');\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n }\n : (ecdsaOpts.bits2int as (bytes: TArg) => bigint);\n const bits2int_modN: (bytes: TArg) => bigint =\n ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes: TArg): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : (ecdsaOpts.bits2int_modN as (bytes: TArg) => bigint);\n const ORDER_MASK = bitMask(fnBits);\n // Pads output with zero as per spec.\n /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */\n function int2octets(num: bigint): TRet {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num) as TRet;\n }\n\n function validateMsgAndHash(message: TArg, prehash: boolean): TRet {\n abytes(message, undefined, 'message');\n return (\n prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n ) as TRet;\n }\n\n /**\n * Steps A, D of RFC6979 3.2.\n * Creates RFC6979 seed; converts msg/privKey to numbers.\n * Used only in sign, not in verify.\n *\n * Warning: we cannot assume here that message has same amount of bytes as curve order,\n * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.\n */\n function prepSig(\n message: TArg,\n secretKey: TArg,\n opts: TArg\n ) {\n const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m)\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(message);\n const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint\n if (!Fn.isValidNot0(d)) throw new Error('invalid private key');\n const seedArgs: TArg[] = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (extraEntropy != null && extraEntropy !== false) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n // gen random bytes OR pass as-is\n const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;\n seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes\n }\n const seed = concatBytes(...seedArgs) as TRet; // Step D of RFC6979 3.2\n const m = h1int; // no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n // To transform k => Signature:\n // q = k\u22C5G\n // r = q.x mod n\n // s = k^-1(m + rd) mod n\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: TArg): Signature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n // Important: all mod() calls here must be done over N\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = k\u22C5G\n const r = Fn.create(q.x); // r = q.x mod n\n if (r === _0n) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N\n recovery ^= 1;\n }\n return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery);\n }\n return { seed, k2sig };\n }\n\n /**\n * Signs a message or message hash with a secret key.\n * With the default `prehash: true`, raw message bytes are hashed internally;\n * only `{ prehash: false }` expects a caller-supplied digest.\n *\n * ```\n * sign(m, d) where\n * k = rfc6979_hmac_drbg(m, d)\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr) / k mod n\n * ```\n */\n function sign(\n message: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet {\n const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2.\n const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac);\n const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G\n return sig.toBytes(opts.format);\n }\n\n /**\n * Verifies a signature against message and public key.\n * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.\n * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * u1 = hs^-1 mod n\n * u2 = rs^-1 mod n\n * R = u1\u22C5G + u2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: TArg,\n message: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\n const end = signature instanceof Signature ? ', use sig.toBytes()' : '';\n throw new Error('verify expects Uint8Array signature' + end);\n }\n validateSigLength(signature, format); // execute this twice because we want loud error\n try {\n const sig = Signature.fromBytes(signature, format);\n const P = Point.fromBytes(publicKey);\n if (lowS && sig.hasHighS()) return false;\n const { r, s } = sig;\n const h = bits2int_modN(message); // mod n, not mod p\n const is = Fn.inv(s); // s^-1 mod n\n const u1 = Fn.create(h * is); // u1 = hs^-1 mod n\n const u2 = Fn.create(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: TArg,\n message: TArg,\n opts: TArg = {}\n ): TRet {\n // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message\n // bytes first unless the caller passes `{ prehash: false }`.\n const { prehash } = validateSigOpts(opts, defaultSigOpts);\n message = validateMsgAndHash(message, prehash);\n return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes();\n }\n\n return Object.freeze({\n keygen,\n getPublicKey,\n getSharedSecret,\n utils,\n lengths,\n Point,\n sign,\n verify,\n recoverPublicKey,\n Signature,\n hash: hash_,\n }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport {\n createFROST,\n type FROST,\n type FrostPublic,\n type FrostSecret,\n type Nonces,\n} from './abstract/frost.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport {\n abytes,\n asciiToBytes,\n bytesToNumberBE,\n concatBytes,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag: string, ...messages: TArg): TRet {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages)) as TRet;\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: TArg>): TRet =>\n point.toBytes(true).slice(1) as TRet;\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: TArg) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args: TArg): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey: TArg): TRet {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(\n message: TArg,\n secretKey: TArg,\n auxRand: TArg = randomBytes(32)\n): TRet {\n const { Fn, BASE } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n if (k_ === 0n) throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const k = hasEven(p.y) ? k_ : Fn.neg(k_);\n const rx = pointToBytes(p);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig as TRet;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(\n signature: TArg,\n message: TArg,\n publicKey: TArg\n): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s)) return false;\n\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport const __TEST: { lift_x: typeof lift_x } = /* @__PURE__ */ Object.freeze({ lift_x });\n\n/** Schnorr-specific secp256k1 API from BIP340. */\nexport type SecpSchnorr = {\n /**\n * Generate one Schnorr secret/public keypair.\n * @param seed - Optional seed for deterministic testing or custom randomness.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet };\n /**\n * Derive the x-only public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns X-only public key bytes.\n */\n getPublicKey: typeof schnorrGetPublicKey;\n /**\n * Create one BIP340 Schnorr signature.\n * @param message - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param auxRand - Optional auxiliary randomness.\n * @returns Compact Schnorr signature bytes.\n */\n sign: typeof schnorrSign;\n /**\n * Verify one BIP340 Schnorr signature.\n * @param signature - Compact signature bytes.\n * @param message - Signed message bytes.\n * @param publicKey - X-only public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: typeof schnorrVerify;\n /** Underlying secp256k1 point constructor. */\n Point: WeierstrassPointCons;\n /** Helper utilities for Schnorr-specific key handling and tagged hashing. */\n utils: {\n /** Generate one Schnorr secret key. */\n randomSecretKey: (seed?: TArg) => TRet;\n /** Convert one point into its x-only BIP340 byte encoding. */\n pointToBytes: (point: TArg>) => TRet;\n /** Lift one x coordinate into the unique even-Y point. */\n lift_x: typeof lift_x;\n /** Compute a BIP340 tagged hash. */\n taggedHash: typeof taggedHash;\n };\n /** Public byte lengths for keys, signatures, and seeds. */\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed?: TArg): TRet => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nconst getMapSWU = () =>\n mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\n (scalars: bigint[]) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST: TRet = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n }))();\n\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point: PointType, merkleRoot?: TArg): bigint {\n if (merkleRoot === undefined) return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t)) throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub: TArg): TRet {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y)) return pub as TRet;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(\n Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])\n ),\n } as TRet;\n}\nfunction frostSecretToEvenY(s: TArg, pub: TArg): TRet {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y)) return s as TRet;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n } as TRet;\n}\nfunction frostNoncesToEvenY(PK: PointType, nonces: TArg): TRet {\n if (hasEven(PK.y)) return nonces as TRet;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n } as TRet;\n}\n\nfunction frostTweakSecret(\n s: TArg,\n pub: TArg,\n merkleRoot?: TArg\n): TRet {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n } as TRet;\n}\n\nfunction frostTweakPublic(\n pub: TArg,\n merkleRoot?: TArg\n): TRet {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) =>\n (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes()\n );\n const verifyingShares: Record = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n } as TRet;\n}\n\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST: TRet = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32) return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33) return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n: bigint) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1) as TRet,\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx) as TRet,\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n }))();\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl, type TRet } from './utils.ts';\n\n/** Initial SHA-1 state from RFC 3174 \u00A76.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1: TRet = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\n // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves\n // update()/digest() callable on reused instances.\n this.destroyed = true;\n this.set(0, 0, 0, 0);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5: TRet = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160: TRet = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n", "/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const base58key = root.privateExtendedKey;\n * const restored = HDKey.fromExtendedKey(base58key);\n * const fromJson = HDKey.fromJSON({ xpriv: base58key });\n * const child = fromJson.derive(\"m/0/2147483647'/1\");\n * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));\n *\n * // props\n * [root.depth, root.index, root.chainCode];\n * [restored.privateKey, restored.publicKey];\n * const sig = child.sign(msgHash);\n * child.verify(msgHash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView, type TArg, type TRet } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = /* @__PURE__ */ (() => secp.Point)();\nconst Fn = /* @__PURE__ */ (() => Point.Fn)();\nconst base58check = /* @__PURE__ */ createBase58check(sha256);\nconst MASTER_SECRET = /* @__PURE__ */ (() => {\n return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n})();\n\n/** Network-specific BIP32 version bytes. */\nexport interface Versions {\n /** 4-byte version used when serializing private extended keys. */\n private: number;\n /** 4-byte version used when serializing public extended keys. */\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened child index offset from BIP32. */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: TArg) => ripemd160(sha256(data));\nconst fromU32 = (data: TArg) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): TRet => {\n if (typeof n !== 'number')\n throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n);\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)\n throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n);\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @param opt - Node fields used to construct one HDKey instance.\n * @example\n * ```js\n * import { HDKey } from '@scure/bip32';\n * import { randomBytes } from '@noble/hashes/utils.js';\n *\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const account0 = root.derive(\"m/0/1'\");\n * account0.publicKey;\n * ```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n // Returns the live private key buffer for this instance.\n // Copy it first if you need an immutable snapshot.\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new RangeError(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n // Don't alias caller-owned secret buffers.\n this._privateKey = Uint8Array.from(opt.privateKey);\n this._publicKey = secp.getPublicKey(this._privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n /**\n * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.\n */\n deriveChild(index: number, _I?: Uint8Array): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const out = _I || hmac(sha512, this.chainCode, data);\n abytes(out, 64);\n const childTweak = out.slice(0, 32);\n const chainCode = out.slice(32);\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n // Fail early instead of re-trying different index\n if (opt.depth! > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n try {\n const ctweak = Fn.fromBytes(childTweak);\n // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.\n // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.\n // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const point = Point.fromBytes(this._publicKey);\n const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n\ntype Tests = Readonly<{\n deriveChildWithI(key: TArg, index: number, I: TArg): TRet;\n}>;\n\nexport const __TESTS: TRet = /* @__PURE__ */ Object.freeze({\n deriveChildWithI(key: TArg, index: number, I: TArg): TRet {\n // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.\n return (key as HDKey).deriveChild(index, I as Uint8Array) as TRet;\n },\n});\n", "/**\n * HKDF (RFC 5869): extract + expand in one step.\n * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.\n * @module\n */\nimport { hmac } from './hmac.ts';\nimport { abytes, ahash, anumber, type CHash, clean, type TArg, type TRet } from './utils.ts';\n\n/**\n * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`\n * Arguments position differs from spec (IKM is first one, since it is not optional)\n * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @returns Pseudorandom key derived from input keying material.\n * @example\n * Run the HKDF extract step.\n * ```ts\n * import { extract } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\nexport function extract(\n hash: TArg,\n ikm: TArg,\n salt?: TArg\n): TRet {\n ahash(hash);\n // NOTE: some libraries treat zero-length array as 'not provided';\n // we don't, since we have undefined as 'not provided'\n // https://github.com/RustCrypto/KDFs/issues/15\n if (salt === undefined) salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\n\n// Shared mutable scratch byte for the RFC 5869 block counter `N`.\n// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.\nconst HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);\n// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.\nconst EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`\n * @param hash - hash function that would be used (e.g. sha256)\n * @param prk - a pseudorandom key of at least HashLen octets\n * (usually, the output from the extract step)\n * @param info - optional context and application specific information (can be a zero-length string)\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material with the requested length.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * Run the HKDF expand step.\n * ```ts\n * import { expand } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);\n * ```\n */\nexport function expand(\n hash: TArg,\n prk: TArg,\n info?: TArg,\n length: number = 32\n): TRet {\n ahash(hash);\n anumber(length, 'length');\n abytes(prk, undefined, 'prk');\n const olen = hash.outputLen;\n // RFC 5869 \u00A72.3: PRK is \"a pseudorandom key of at least HashLen octets\".\n if (prk.length < olen) throw new Error('\"prk\" must be at least HashLen octets');\n // RFC 5869 \u00A72.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.\n if (length > 255 * olen) throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined) info = EMPTY_BUFFER;\n else abytes(info, undefined, 'info');\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length) as TRet;\n}\n\n/**\n * HKDF (RFC 5869): derive keys from an initial input.\n * Combines hkdf_extract + hkdf_expand in one step\n * @param hash - hash function that would be used (e.g. sha256)\n * @param ikm - input keying material, the initial key\n * @param salt - optional salt value (a non-secret random value)\n * @param info - optional context and application specific information bytes\n * @param length - length of output keying material in bytes.\n * RFC 5869 \u00A72.3 allows `0..255*HashLen`, so `0` returns an empty OKM.\n * @returns Output keying material derived from the input key.\n * @throws If the requested output length exceeds the HKDF limit\n * for the selected hash. {@link Error}\n * @example\n * HKDF (RFC 5869): derive keys from an initial input.\n * ```ts\n * import { hkdf } from '@noble/hashes/hkdf.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js';\n * const inputKey = randomBytes(32);\n * const salt = randomBytes(32);\n * const info = utf8ToBytes('application-key');\n * const okm = hkdf(sha256, inputKey, salt, info, 32);\n * ```\n */\nexport const hkdf = (\n hash: TArg,\n ikm: TArg,\n salt: TArg,\n info: TArg,\n length: number\n): TRet => expand(hash, extract(hash, ikm, salt), info, length);\n", "/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out\n * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},\n * {@link https://keccak.team/keccak.html | Website}, and\n * {@link https://crypto.stackexchange.com/q/15727 | the differences between\n * SHA-3 and Keccak}.\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher,\n oidNist,\n swap32IfBE,\n u32,\n type CHash, type CHashXOF,\n type Hash,\n type HashInfo,\n type HashXOF,\n type TArg,\n type TRet\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\n// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors\n// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\n// `split(..., true)` keeps the local little-endian lane-word layout used by\n// `state32`, so these `H` / `L` tables follow the file's first-word /\n// second-word lane slots rather than `_u64.ts`'s usual high/low naming.\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n/**\n * `keccakf1600` internal permutation, additionally allows adjusting the round count.\n * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words\n * in this file's local little-endian lane-word order\n * @param rounds - number of rounds to execute\n * @throws If `rounds` is outside the supported `1..24` range. {@link Error}\n * @example\n * Permute a Keccak state with the default 24 rounds.\n * ```ts\n * keccakP(new Uint32Array(50));\n * ```\n */\nexport function keccakP(s: TArg, rounds: number = 24): void {\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24) throw new Error('\"rounds\" expected integer 1..24');\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta \u03B8\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (\u03C1) and Pi (\u03C0)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (\u03C7)\n // Same as:\n // for (let x = 0; x < 10; x++) B[x] = s[y + x];\n // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n for (let y = 0; y < 50; y += 10) {\n const b0 = s[y],\n b1 = s[y + 1],\n b2 = s[y + 2],\n b3 = s[y + 3];\n s[y] ^= ~s[y + 2] & s[y + 4];\n s[y + 1] ^= ~s[y + 3] & s[y + 5];\n s[y + 2] ^= ~s[y + 4] & s[y + 6];\n s[y + 3] ^= ~s[y + 5] & s[y + 7];\n s[y + 4] ^= ~s[y + 6] & s[y + 8];\n s[y + 5] ^= ~s[y + 7] & s[y + 9];\n s[y + 6] ^= ~s[y + 8] & b0;\n s[y + 7] ^= ~s[y + 9] & b1;\n s[y + 8] ^= ~b0 & b2;\n s[y + 9] ^= ~b1 & b3;\n }\n // Iota (\u03B9)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n\n/**\n * Keccak sponge function.\n * @param blockLen - absorb/squeeze rate in bytes\n * @param suffix - domain separation suffix byte\n * @param outputLen - default digest length in bytes. This base sponge only\n * requires a non-negative integer; wrappers that need positive output\n * lengths must enforce that themselves.\n * @param enableXOF - whether XOF output is allowed\n * @param rounds - number of Keccak-f rounds\n * @example\n * Build a sponge state, absorb bytes, then finalize a digest.\n * ```ts\n * const hash = new Keccak(136, 0x06, 32);\n * hash.update(new Uint8Array([1, 2, 3]));\n * hash.digest();\n * ```\n */\nexport class Keccak implements Hash, HashXOF {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n public canXOF: boolean;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.canXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen, 'outputLen');\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: TArg): this {\n aexists(this);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.\n // These byte values already include the first padding bit, while the\n // final `0x80` below supplies the closing `1` bit in the last rate byte.\n state[pos] ^= suffix;\n // If that combined suffix lands in the last rate byte and already sets\n // bit 7, absorb it first so the final pad10*1 bit can be xored into a\n // fresh block.\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: TArg): TRet {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out as TRet;\n }\n xofInto(out: TArg): TRet {\n // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base\n // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/\n // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): TRet {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: TArg): void {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest(): TRet {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n // Reused destinations can come from a different rate/capacity variant, so clone must rewrite\n // the sponge geometry as well as the state words.\n to.blockLen = blockLen;\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone\n // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.\n to.canXOF = this.canXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst genKeccak = (\n suffix: number,\n blockLen: number,\n outputLen: number,\n info: TArg = {}\n) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-224.\n * ```ts\n * sha3_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_224: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 144,\n 28,\n /* @__PURE__ */ oidNist(0x07)\n);\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-256.\n * ```ts\n * sha3_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_256: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 136,\n 32,\n /* @__PURE__ */ oidNist(0x08)\n);\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-384.\n * ```ts\n * sha3_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_384: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 104,\n 48,\n /* @__PURE__ */ oidNist(0x09)\n);\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA3-512.\n * ```ts\n * sha3_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha3_512: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 72,\n 64,\n /* @__PURE__ */ oidNist(0x0a)\n);\n\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-224.\n * ```ts\n * keccak_224(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_224: TRet = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-256.\n * ```ts\n * keccak_256(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_256: TRet = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-384.\n * ```ts\n * keccak_384(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_384: TRet = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with Keccak-512.\n * ```ts\n * keccak_512(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const keccak_512: TRet = /* @__PURE__ */ genKeccak(0x01, 72, 64);\n\n/** Options for SHAKE XOF. */\nexport type ShakeOpts = {\n /** Desired number of output bytes. */\n dkLen?: number;\n};\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number, info: TArg = {}) =>\n createHasher(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true),\n info\n );\n\n/**\n * SHAKE128 XOF with 128-bit security and a 16-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128.\n * ```ts\n * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 256-bit security and a 32-byte default output.\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256.\n * ```ts\n * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n\n/**\n * SHAKE128 XOF with 256-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE128 using a 32-byte default output.\n * ```ts\n * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 });\n * ```\n */\nexport const shake128_32: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n/**\n * SHAKE256 XOF with 512-bit output (NIST version).\n * @param msg - message bytes to hash\n * @param opts - Optional output-length override. See {@link ShakeOpts}.\n * @returns Digest bytes.\n * @example\n * Hash a message with SHAKE256 using a 64-byte default output.\n * ```ts\n * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 });\n * ```\n */\nexport const shake256_64: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n", "/**\n * Utilities for hex, bytearray and number handling.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n/**\n * Asserts that a value is a byte array and optionally checks its length.\n * Returns the original reference unchanged on success, and currently also accepts Node `Buffer`\n * values through the upstream validator.\n * This helper throws on malformed input, so APIs that must return `false` need to guard lengths\n * before decoding or before calling it.\n * @example\n * Validate that a value is a byte array with the expected length.\n * ```ts\n * abytes(new Uint8Array([1]), 1);\n * ```\n */\nconst abytesDoc: typeof abytes = abytes;\nexport { abytesDoc as abytes };\n/**\n * Concatenates byte arrays into a new `Uint8Array`.\n * Zero arguments return an empty `Uint8Array`.\n * Invalid segments throw before allocation because each argument is validated first.\n * @example\n * Concatenate two byte arrays into one result.\n * ```ts\n * concatBytes(new Uint8Array([1]), new Uint8Array([2]));\n * ```\n */\nconst concatBytesDoc: typeof concatBytes = concatBytes;\nexport { concatBytesDoc as concatBytes };\n/**\n * Returns cryptographically secure random bytes.\n * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable.\n * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation,\n * so negative and fractional values both throw instead of truncating through JS `ToIndex`.\n * @param bytesLength - Number of random bytes to generate.\n * @returns Fresh random bytes.\n * @example\n * Generate a fresh random seed.\n * ```ts\n * const seed = randomBytes(4);\n * ```\n */\nexport const randomBytes: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\n * @param a - First byte array.\n * @param b - Second byte array.\n * @returns Whether both arrays contain the same bytes.\n * @example\n * Compare two byte arrays for equality.\n * ```ts\n * equalBytes(new Uint8Array([1]), new Uint8Array([1]));\n * ```\n */\nexport function equalBytes(a: TArg, b: TArg): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\n * Copies bytes into a fresh `Uint8Array`.\n * Returns a detached plain `Uint8Array` after validating that the input is real bytes.\n * @param bytes - Source bytes.\n * @returns Copy of the input bytes.\n * @example\n * Copy bytes into a fresh array.\n * ```ts\n * copyBytes(new Uint8Array([1, 2]));\n * ```\n */\nexport function copyBytes(bytes: TArg): TRet {\n // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict\n // because callers use it at byte-validation boundaries before mutating the detached copy.\n return Uint8Array.from(abytes(bytes)) as TRet;\n}\n\n/**\n * Byte-swaps each 64-bit lane in place.\n * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need\n * this boundary helper before aliasing them as host `Float64Array` lanes.\n * @param arr - Byte buffer whose length is a multiple of 8.\n * @returns The same buffer after in-place 64-bit lane byte swaps.\n * @example\n * Byte-swap one 64-bit lane in place.\n * ```ts\n * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport function byteSwap64(arr: T): T {\n const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n for (let i = 0; i < bytes.length; i += 8) {\n const a0 = bytes[i + 0];\n const a1 = bytes[i + 1];\n const a2 = bytes[i + 2];\n const a3 = bytes[i + 3];\n bytes[i + 0] = bytes[i + 7];\n bytes[i + 1] = bytes[i + 6];\n bytes[i + 2] = bytes[i + 5];\n bytes[i + 3] = bytes[i + 4];\n bytes[i + 4] = a3;\n bytes[i + 5] = a2;\n bytes[i + 6] = a1;\n bytes[i + 7] = a0;\n }\n return arr;\n}\n/**\n * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian.\n * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as\n * `Float64Array` lanes on the current host.\n * @param arr - Buffer to pass through or swap in place.\n * @returns The same buffer, normalized for Falcon's little-endian table layout.\n * @example\n * Normalize one host-endian buffer for Falcon's float tables.\n * ```ts\n * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]));\n * ```\n */\nexport const baswap64If: (arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg) => {\n secretKey: TRet;\n publicKey: TRet;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg) => TRet;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\n/**\n * Validates that an options bag is a plain object.\n * @param opts - Options object to validate.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate that an options bag is a plain object.\n * ```ts\n * validateOpts({});\n * ```\n */\nexport function validateOpts(opts: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\n\n/**\n * Validates common verification options.\n * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support\n * further after this shared plain-object gate.\n * @param opts - Verification options. See {@link VerOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\n\n/**\n * Validates common signing options.\n * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific\n * restrictions are enforced later by callers.\n * @param opts - Signing options. See {@link SigOpts}.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts?: TArg\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg,\n msg?: TArg\n ) => {\n cipherText: TRet;\n sharedSecret: TRet;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg, secretKey: TArg) => TRet;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder extends Coder {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen = BytesCoder & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder = T extends BytesCoder ? U : never;\ntype SplitOut)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder;\n};\n/**\n * Builds a fixed-layout coder from byte lengths and nested coders.\n * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that\n * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder`\n * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards\n * caller-owned bytes, it must do so only after detaching them into a disposable copy.\n * @param label - Label used in validation errors.\n * @param lengths - Field lengths or nested coders.\n * @returns Composite fixed-length coder.\n * @example\n * Build a fixed-layout coder from byte lengths and nested coders.\n * ```ts\n * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]);\n * ```\n */\nexport function splitCoder)[]>(\n label: string,\n ...lengths: T\n): TRet> & { bytesLen: number }> {\n const getLength = (c: TArg>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < lengths.length; i++) {\n const c = lengths[i];\n const l = getLength(c);\n const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg) => {\n abytes_(buf, bytesLen, label);\n const res = [];\n for (const c of lengths) {\n const l = getLength(c);\n const b = buf.subarray(0, l);\n res.push(typeof c === 'number' ? b : c.decode(b));\n buf = buf.subarray(l);\n }\n return res as SplitOut;\n },\n } as any;\n}\n// nano-packed.array (fixed size)\n/**\n * Builds a fixed-length vector coder from another fixed-length coder.\n * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder.\n * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into\n * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned\n * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts\n * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes.\n * @param c - Element coder.\n * @param vecLen - Number of elements in the vector.\n * @returns Fixed-length vector coder.\n * @example\n * Build a fixed-length vector coder from another fixed-length coder.\n * ```ts\n * vecCoder(\n * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 },\n * 2\n * ).encode([1, 2]);\n * ```\n */\nexport function vecCoder(c: TArg>, vecLen: number): TRet> {\n const coder = c as BytesCoderLen;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg): TRet => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet;\n },\n decode: (a: TArg): TRet => {\n abytes_(a, bytesLen);\n const r: T[] = [];\n for (let i = 0; i < a.length; i += coder.bytesLen)\n r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));\n return r as TRet;\n },\n } as any;\n}\n\n/**\n * Overwrites supported typed-array inputs with zeroes in place.\n * Accepts direct typed arrays and one-level arrays of them.\n * @param list - Typed arrays or one-level lists of typed arrays to clear.\n * @example\n * Overwrite typed arrays with zeroes.\n * ```ts\n * const buf = Uint8Array.of(1, 2, 3);\n * cleanBytes(buf);\n * ```\n */\nexport function cleanBytes(...list: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\n}\n\n/**\n * Creates a 32-bit mask with the lowest `bits` bits set.\n * @param bits - Number of low bits to keep.\n * @returns Bit mask with `bits` ones.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Create a low-bit mask for packed-field operations.\n * ```ts\n * const mask = getMask(4);\n * ```\n */\nexport function getMask(bits: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..32], got ${bits}`);\n // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask.\n return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0;\n}\n\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet = /* @__PURE__ */ Uint8Array.of();\n\n/**\n * Builds the domain-separated message payload for the pure sign/verify paths.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated message payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated payload before direct signing.\n * ```ts\n * const payload = getMessage(new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessage(msg: TArg, ctx: TArg = EMPTY): TRet {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\n\n// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the\n// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128,\n// SHAKE256, or another approved hash/XOF under that subtree.\n// 06 09 60 86 48 01 65 03 04 02\nconst oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]);\n\n/**\n * Validates that a hash exposes a NIST hash OID and enough collision resistance.\n * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST\n * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough.\n * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend\n * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes.\n * @param hash - Hash function to validate.\n * @param requiredStrength - Minimum required collision-resistance strength in bits.\n * @throws If the hash metadata or collision resistance is insufficient. {@link Error}\n * @example\n * Validate that a hash exposes a NIST hash OID and enough collision resistance.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { checkHash } from '@noble/post-quantum/utils.js';\n * checkHash(sha256, 128);\n * ```\n */\nexport function checkHash(hash: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP))\n throw new Error('hash.oid is invalid: expected NIST hash');\n // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST\n // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is\n // the tighter runtime check, so enforce that lower bound here.\n const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\n}\n\n/**\n * Builds the domain-separated prehash payload for the prehash sign/verify paths.\n * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper\n * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`.\n * Context length `255` is valid; only `ctx.length > 255` is rejected.\n * @param hash - Prehash function.\n * @param msg - Message bytes.\n * @param ctx - Optional context bytes.\n * @returns Domain-separated prehash payload.\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Build the domain-separated prehash payload for external hashing.\n * ```ts\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { getMessagePrehash } from '@noble/post-quantum/utils.js';\n * getMessagePrehash(sha256, new Uint8Array([1, 2]));\n * ```\n */\nexport function getMessagePrehash(\n hash: CHash,\n msg: TArg,\n ctx: TArg = EMPTY\n): TRet {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n const hashed = hash(msg);\n return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed);\n}\n", "/**\n * Internal methods for lattice-based ML-KEM and ML-DSA.\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js';\nimport { shake128, shake256 } from '@noble/hashes/sha3.js';\nimport type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons = (n: number) => T;\n\ntype Crystals = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder) => BytesCoderLen;\n};\n\n/**\n * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes.\n * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}.\n * @returns CRYSTALS arithmetic and encoding helpers.\n * @example\n * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set.\n * ```ts\n * const crystals = genCrystals({\n * newPoly: (n) => new Uint16Array(n),\n * N: 256,\n * Q: 3329,\n * F: 3303,\n * ROOT_OF_UNITY: 17,\n * brvBits: 7,\n * isKyber: true,\n * });\n * const reduced = crystals.mod(-1);\n * ```\n */\nexport const genCrystals = (opts: CrystalOpts): TRet> => {\n // isKyber: true means Kyber, false means Dilithium\n const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts;\n // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by\n // FIPS 203 \u00A72.3 / FIPS 204 \u00A72.3 before downstream mod-q arithmetic.\n const mod = (a: number, modulo = Q): number => {\n const result = a % modulo | 0;\n return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0;\n };\n // FIPS 204 \u00A77.4 uses the centered `mod \u00B1` representative for low bits, keeping the\n // positive midpoint when `modulo` is even.\n // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`.\n const smod = (a: number, modulo = Q): number => {\n const r = mod(a, modulo) | 0;\n return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0;\n };\n // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while\n // Dilithium uses the FIPS 204 \u00A77.5 / Appendix B `BitRev_8` zetas table over all 256 entries.\n function getZettas() {\n const out = newPoly(N);\n for (let i = 0; i < N; i++) {\n const b = reverseBits(i, brvBits);\n const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q);\n out[i] = Number(p) | 0;\n }\n return out;\n }\n const nttZetas = getZettas();\n\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\n // Kyber has slightly different params, since there is no 512th primitive root of unity mod q,\n // only 256th primitive root of unity mod. Which also complicates MultiplyNTT.\n\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\n invertButterflies: true,\n skipStages: isKyber ? 1 : 0,\n brp: false,\n };\n const dif = FFTCore(field, { dit: false, ...nttOpts });\n const dit = FFTCore(field, { dit: true, ...nttOpts });\n const NTT = {\n encode: (r: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\n // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14\n // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`.\n // kyber uses 128 here, because brv && stuff\n for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]);\n return r;\n },\n };\n // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode /\n // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers.\n const bitsCoder = (d: number, c: Coder): TRet> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg): TRet => {\n const poly = poly_ as T;\n const r = new Uint8Array(bytesLen);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {\n buf |= (c.encode(poly[i]) & mask) << bufLen;\n bufLen += d;\n for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet;\n },\n decode: (bytes: TArg): TRet => {\n const r = newPoly(N);\n for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {\n buf |= bytes[i] << bufLen;\n bufLen += 8;\n for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet;\n },\n } as TRet>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet,\n NTT: {\n encode: (r: TArg): TRet => NTT.encode(r as T) as TRet,\n decode: (r: TArg): TRet => NTT.decode(r as T) as TRet,\n },\n bitsCoder: bitsCoder as TRet>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet =>\n (seed: TArg, blockLen?: number) => {\n if (!blockLen) blockLen = shake.blockLen;\n // Optimizations that won't mater:\n // - cached seed update (two .update(), on start and on the end)\n // - another cache which cloned into working copy\n\n // Faster than multiple updates, since seed less than blockLen\n const _seed = new Uint8Array(seed.length + 2);\n _seed.set(seed);\n const seedLen = seed.length;\n const buf = new Uint8Array(blockLen); // == shake128.blockLen\n let h = shake.create({});\n let calls = 0;\n let xofs = 0;\n return {\n stats: () => ({ calls, xofs }),\n get: (x: number, y: number) => {\n // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate\n // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`.\n _seed[seedLen + 0] = x;\n _seed[seedLen + 1] = y;\n h.destroy();\n h = shake.create({}).update(_seed);\n calls++;\n return () => {\n xofs++;\n return h.xofInto(buf) as TRet;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\n };\n };\n\n/**\n * SHAKE128-based extendable-output reader factory used by ML-KEM.\n * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously\n * returned readers, and each squeeze reuses one mutable internal output buffer.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-KEM SHAKE128 matrix expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF128 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF128(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF128: TRet = /* @__PURE__ */ createXofShake(shake128);\n/**\n * SHAKE256-based extendable-output reader factory used by ML-DSA.\n * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned\n * readers, and reuses one mutable internal output buffer for each squeeze.\n * @param seed - Seed bytes for the reader.\n * @param blockLen - Optional output block length.\n * @returns Stateful XOF reader.\n * @example\n * Build the ML-DSA SHAKE256 coefficient expander and read one block.\n * ```ts\n * import { randomBytes } from '@noble/post-quantum/utils.js';\n * import { XOF256 } from '@noble/post-quantum/_crystals.js';\n * const reader = XOF256(randomBytes(32));\n * const block = reader.get(0, 0)();\n * ```\n */\nexport const XOF256: TRet = /* @__PURE__ */ createXofShake(shake256);\n", "/**\n * ML-DSA: Module Lattice-based Digital Signature Algorithm from\n * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium.\n *\n * Has similar internals to ML-KEM, but their keys and params are different.\n * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml),\n * [repo](https://github.com/pq-crystals/dilithium).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { abool } from '@noble/curves/utils.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport type { CHash } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128, XOF256 } from './_crystals.ts';\nimport {\n abytes,\n type BytesCoderLen,\n checkHash,\n cleanBytes,\n type CryptoKeys,\n equalBytes,\n getMessage,\n getMessagePrehash,\n randomBytes,\n type Signer,\n type SigOpts,\n splitCoder,\n type TArg,\n type TRet,\n validateOpts,\n validateSigOpts,\n validateVerOpts,\n vecCoder,\n type VerOpts,\n} from './utils.ts';\n\n/** Internal ML-DSA options. */\nexport type DSAInternalOpts = {\n /**\n * Whether `internal.sign` / `internal.verify` receive a caller-supplied 64-byte `mu`\n * instead of the usual FIPS 204 formatted message `M'` / prehash-formatted message.\n * validateInternalOpts() only checks this flag; callers still must supply the right input length.\n */\n externalMu?: boolean;\n};\nfunction validateInternalOpts(opts: TArg) {\n validateOpts(opts);\n if (opts.externalMu !== undefined) abool(opts.externalMu, 'opts.externalMu');\n}\n\n/** ML-DSA signer surface with access to the internal message formatting mode. */\nexport type DSAInternal = CryptoKeys & {\n lengths: Signer['lengths'];\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n verify: (\n sig: TArg,\n msg: TArg,\n pubKey: TArg,\n opts?: TArg\n ) => boolean;\n};\n/** Public ML-DSA signer surface. */\nexport type DSA = Signer & { internal: TRet };\n\n// Constants\n// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients.\nconst N = 256;\n// 2**23 \u2212 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints\nconst Q = 8380417;\n// FIPS 204 \u00A72.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT.\nconst ROOT_OF_UNITY = 1753;\n// f = 256**\u22121 mod q, pow(256, -1, q) = 8347681 (python3)\nconst F = 8347681;\n// FIPS 204 Table 1 / \u00A77.4 fixes d = 13 dropped low bits for Power2Round on t.\nconst D = 13;\n// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87;\n// \u00A77.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint.\n// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value.\nconst GAMMA2_1 = Math.floor((Q - 1) / 88) | 0;\nconst GAMMA2_2 = Math.floor((Q - 1) / 32) | 0;\n\ntype XofGet = ReturnType['get']>;\n\n/** Various lattice params. */\n/** Public ML-DSA parameter-set description. */\nexport type DSAParam = {\n /** Matrix row count. */\n K: number;\n /** Matrix column count. */\n L: number;\n /** Bit width used when rounding `t`. */\n D: number;\n /** Bound used for the `y` sampling range. */\n GAMMA1: number;\n /** Bound used during decomposition and hints. */\n GAMMA2: number;\n /** Number of non-zero challenge coefficients. */\n TAU: number;\n /** Centered-binomial noise parameter. */\n ETA: number;\n /** Maximum number of hint bits in a signature. */\n OMEGA: number;\n};\n/** Internal params for different versions of ML-DSA */\n// prettier-ignore\n/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5`\n * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`.\n * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later,\n * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers.\n */\nexport const PARAMS: Record = /* @__PURE__ */ (() =>\n Object.freeze({\n 2: Object.freeze({\n K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80\n }),\n 3: Object.freeze({\n K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55\n }),\n 5: Object.freeze({\n K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75\n }),\n } as const))();\n\n// NOTE: there is a lot cases where negative numbers used (with smod instead of mod).\ntype Poly = Int32Array;\nconst newPoly = (n: number): TRet => new Int32Array(n) as TRet;\n\n// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal,\n// and Int32Array polys because ordinary-form coefficients can be negative / centered.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly,\n isKyber: false,\n brvBits: 8,\n});\n\nconst id = (n: T): T => n;\ntype IdNum = (n: number) => number;\n\n// compress()/verify() must be compatible in both directions:\n// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps.\n// malformed-input rejection only happens through the optional verify hook.\nconst polyCoder = (d: number, compress: IdNum = id, verify: IdNum = id) =>\n crystals.bitsCoder(d, {\n encode: (i: number) => compress(verify(i)),\n decode: (i: number) => verify(compress(i)),\n });\n\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polyAdd = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] + b[i]);\n return a as TRet;\n};\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polySub = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] - b[i]);\n return a as TRet;\n};\n\n// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.\nconst polyShiftl = (p_: TArg): TRet => {\n const p = p_ as Poly;\n for (let i = 0; i < N; i++) p[i] <<= D;\n return p as TRet;\n};\n\nconst polyChknorm = (p_: TArg, B: number): boolean => {\n const p = p_ as Poly;\n // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.\n for (let i = 0; i < N; i++) if (Math.abs(crystals.smod(p[i])) >= B) return true;\n return false;\n};\n\n// Both inputs must already be in NTT / `T_q` form.\nconst MultiplyNTTs = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints,\n // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit,\n // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits).\n // Barrett reduction is slower than mod :(\n const c = newPoly(N);\n for (let i = 0; i < a.length; i++) c[i] = crystals.mod(a[i] * b[i]);\n return c as TRet;\n};\n\n// Return poly in NTT representation\nfunction RejNTTPoly(xof_: TArg): TRet {\n const xof = xof_ as XofGet;\n // Samples a polynomial \u2208 Tq. xof() must return byte lengths divisible by 3.\n const r = newPoly(N);\n // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :(\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('RejNTTPoly: unaligned block');\n for (let i = 0; j < N && i <= b.length - 3; i += 3) {\n // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate.\n const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes\n if (t < Q) r[j++] = t;\n }\n }\n return r as TRet;\n}\n\ntype DilithiumOpts = {\n K: number;\n L: number;\n GAMMA1: number;\n GAMMA2: number;\n TAU: number;\n ETA: number;\n OMEGA: number;\n C_TILDE_BYTES: number;\n CRH_BYTES: number;\n TR_BYTES: number;\n XOF128: XOF;\n XOF256: XOF;\n securityLevel: number;\n};\n\n// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the\n// Table 2 byte lengths / hash-width choices used by the public wrappers below.\nfunction getDilithium(opts_: TArg): TRet {\n const opts = opts_ as DilithiumOpts;\n const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;\n const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;\n\n if (![2, 4].includes(ETA)) throw new Error('Wrong ETA');\n if (![1 << 17, 1 << 19].includes(GAMMA1)) throw new Error('Wrong GAMMA1');\n if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) throw new Error('Wrong GAMMA2');\n const BETA = TAU * ETA;\n\n const decompose = (r: number) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1(2\u03B32) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0;\n // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`.\n if (rPlus - r0 === Q - 1) return { r1: 0 | 0, r0: (r0 - 1) | 0 };\n const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0;\n return { r1, r0 }; // r1 = HighBits, r0 = LowBits\n };\n\n const HighBits = (r: number) => decompose(r).r1;\n const LowBits = (r: number) => decompose(r).r0;\n const MakeHint = (z: number, r: number) => {\n // Compute hint bit indicating whether adding z to r alters the high bits of r.\n // FIPS 204 \u00A76.2 also permits the Section 5.1 alternative from [6], which uses the\n // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally.\n // This optimized predicate only applies to those transformed Section 5.1 inputs; it is\n // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs.\n\n // From dilithium code\n const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1;\n // from FIPS204:\n // // const r1 = HighBits(r);\n // // const v1 = HighBits(r + z);\n // // const res1 = +(r1 !== v1);\n // But they return different results! However, decompose is same.\n // So, either there is a bug in Dilithium ref implementation or in FIPS204.\n // For now, lets use dilithium one, so test vectors can be passed.\n // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after\n // `r0 += ct0`.\n // See dilithium-py README section \"Optimising decomposition and making hints\".\n return res0;\n };\n\n const UseHint = (h: number, r: number) => {\n // Returns the high bits of r adjusted according to hint h\n const m = Math.floor((Q - 1) / (2 * GAMMA2));\n const { r1, r0 } = decompose(r);\n // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m\n // 4: if h = 1 and r0 \u2264 0 return (r1 \u2212 1) mod m\n if (h === 1) return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0;\n return r1 | 0;\n };\n const Power2Round = (r: number) => {\n // Decomposes r into (r1, r0) such that r \u2261 r1*(2**d) + r0 mod q.\n const rPlus = crystals.mod(r);\n const r0 = crystals.smod(rPlus, 2 ** D) | 0;\n return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 };\n };\n\n const hintCoder: BytesCoderLen = {\n bytesLen: OMEGA + K,\n encode: (h_: TArg): TRet => {\n const h = h_ as Poly[] | false;\n if (h === false) throw new Error('hint.encode: hint is false'); // should never happen\n const res = new Uint8Array(OMEGA + K);\n for (let i = 0, k = 0; i < K; i++) {\n for (let j = 0; j < N; j++) if (h[i][j] !== 0) res[k++] = j;\n res[OMEGA + i] = k;\n }\n return res as TRet;\n },\n decode: (buf: TArg): TRet => {\n const h = [];\n let k = 0;\n for (let i = 0; i < K; i++) {\n const hi = newPoly(N);\n if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA) return false as TRet;\n for (let j = k; j < buf[OMEGA + i]; j++) {\n if (j > k && buf[j] <= buf[j - 1]) return false as TRet;\n hi[buf[j]] = 1;\n }\n k = buf[OMEGA + i];\n h.push(hi);\n }\n for (let j = k; j < OMEGA; j++) if (buf[j] !== 0) return false as TRet;\n return h as TRet;\n },\n };\n\n const ETACoder = polyCoder(\n ETA === 2 ? 3 : 4,\n (i: number) => ETA - i,\n (i: number) => {\n if (!(-ETA <= i && i <= ETA))\n throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`);\n return i;\n }\n );\n const T0Coder = polyCoder(13, (i: number) => (1 << (D - 1)) - i);\n const T1Coder = polyCoder(10);\n // Requires smod. Need to fix!\n const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i: number) => crystals.smod(GAMMA1 - i));\n const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4);\n const W1Vec = vecCoder(W1Coder, K);\n // Main structures\n const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K));\n const secretCoder = splitCoder(\n 'secretKey',\n 32,\n 32,\n TR_BYTES,\n vecCoder(ETACoder, L),\n vecCoder(ETACoder, K),\n vecCoder(T0Coder, K)\n );\n const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);\n const CoefFromHalfByte =\n ETA === 2\n ? (n: number) => (n < 15 ? 2 - (n % 5) : false)\n : (n: number) => (n < 9 ? 4 - n : false);\n\n // Return poly in ordinary representation.\n // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply\n // `NTT.encode()` later when needed.\n function RejBoundedPoly(xof_: TArg): TRet {\n const xof = xof_ as XofGet;\n // Samples an element a \u2208 Rq with coeffcients in [\u2212\u03B7, \u03B7] computed via rejection sampling from \u03C1.\n const r: Poly = newPoly(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n for (let i = 0; j < N && i < b.length; i += 1) {\n // half byte. Should be superfast with vector instructions. But very slow with js :(\n const d1 = CoefFromHalfByte(b[i] & 0x0f);\n const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f);\n if (d1 !== false) r[j++] = d1;\n if (j < N && d2 !== false) r[j++] = d2;\n }\n }\n return r as TRet;\n }\n\n const SampleInBall = (seed: TArg): TRet => {\n // Samples a polynomial c \u2208 Rq with coeffcients from {\u22121, 0, 1} and Hamming weight \u03C4\n const pre = newPoly(N);\n const s = shake256.create({}).update(seed);\n const buf = new Uint8Array(shake256.blockLen);\n s.xofInto(buf);\n // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`,\n // then rejection-samples coefficient positions from the remaining XOF stream.\n const masks = buf.slice(0, 8);\n for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) {\n let b = i + 1;\n for (; b > i; ) {\n b = buf[pos++];\n if (pos < shake256.blockLen) continue;\n s.xofInto(buf);\n pos = 0;\n }\n pre[i] = pre[b];\n pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1);\n if (maskBit >= 8) {\n maskPos++;\n maskBit = 0;\n }\n }\n return pre as TRet;\n };\n\n const polyPowerRound = (p_: TArg) => {\n const p = p_ as Poly;\n const res0 = newPoly(N);\n const res1 = newPoly(N);\n for (let i = 0; i < p.length; i++) {\n const { r0, r1 } = Power2Round(p[i]);\n res0[i] = r0;\n res1[i] = r1;\n }\n return { r0: res0, r1: res1 };\n };\n const polyUseHint = (u_: TArg, h_: TArg): TRet => {\n const u = u_ as Poly;\n const h = h_ as Poly;\n // In-place on `u`: verification only needs the recovered high bits, so reuse the\n // temporary `wApprox` buffer instead of allocating another polynomial.\n for (let i = 0; i < N; i++) u[i] = UseHint(h[i], u[i]);\n return u as TRet;\n };\n const polyMakeHint = (a_: TArg, b_: TArg) => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n const v = newPoly(N);\n let cnt = 0;\n for (let i = 0; i < N; i++) {\n const h = MakeHint(a[i], b[i]);\n v[i] = h;\n cnt += h;\n }\n return { v, cnt };\n };\n\n const signRandBytes = 32;\n const seedCoder = splitCoder('seed', 32, 64, 32);\n // API & argument positions are exactly as in FIPS204.\n const internal: TRet = Object.freeze({\n info: Object.freeze({ type: 'internal-ml-dsa' }),\n lengths: Object.freeze({\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n seed: 32,\n signature: sigCoder.bytesLen,\n signRand: signRandBytes,\n }),\n keygen: (seed?: TArg) => {\n // H(\uD835\uDF09||IntegerToBytes(\uD835\uDC58, 1)||IntegerToBytes(\u2113, 1), 128) 2: \u25B7 expand seed\n const seedDst = new Uint8Array(32 + 2);\n const randSeed = seed === undefined;\n if (randSeed) seed = randomBytes(32);\n abytes(seed!, 32, 'seed');\n seedDst.set(seed!);\n if (randSeed) cleanBytes(seed!);\n seedDst[32] = K;\n seedDst[33] = L;\n const [rho, rhoPrime, K_] = seedCoder.decode(\n shake256(seedDst, { dkLen: seedCoder.bytesLen })\n );\n const xofPrime = XOF256(rhoPrime);\n const s1 = [];\n for (let i = 0; i < L; i++) s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s2 = [];\n for (let i = L; i < L + K; i++)\n s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff)));\n const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice()));\n const t0 = [];\n const t1 = [];\n const xof = XOF128(rho);\n const t = newPoly(N);\n for (let i = 0; i < K; i++) {\n // t \u2190 NTT\u22121(A*NTT(s1)) + s2\n cleanBytes(t); // don't-reallocate\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // super slow!\n polyAdd(t, MultiplyNTTs(aij, s1Hat[j]));\n }\n crystals.NTT.decode(t);\n const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) \u2190 Power2Round(t, d)\n t0.push(r0);\n t1.push(r1);\n }\n const publicKey = publicCoder.encode([rho, t1]); // pk \u2190 pkEncode(\u03C1, t1)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr \u2190 H(BytesToBits(pk), 512)\n // sk \u2190 skEncode(\u03C1, K,tr, s1, s2, t0)\n const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]);\n xof.clean();\n xofPrime.clean();\n // STATS\n // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 },\n // Kyber1024: { calls: 16, xofs: 48 }\n // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 },\n // DSA87: { calls: 71, xofs: 71 }\n cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst);\n return {\n publicKey: publicKey as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey);\n const xof = XOF128(rho);\n const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice()));\n const t1: Poly[] = [];\n const tmp = newPoly(N);\n for (let i = 0; i < K; i++) {\n tmp.fill(0);\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT\n polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j\n }\n crystals.NTT.decode(tmp); // NTT\u207B\u00B9\n polyAdd(tmp, s2[i]); // t_i = A\u00B7s1 + s2\n const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 \u2248 t0\n t1.push(r1);\n }\n xof.clean();\n cleanBytes(tmp, s1Hat, _t0, s1, s2);\n return publicCoder.encode([rho, t1]);\n },\n // NOTE: random is optional.\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n validateInternalOpts(opts);\n let { extraEntropy: random, externalMu = false } = opts;\n // This part can be pre-cached per secretKey, but there is only minor performance improvement,\n // since we re-use a lot of variables to computation.\n // (\u03C1, K,tr, s1, s2, t0) \u2190 skDecode(sk)\n const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey);\n // Cache matrix to avoid re-compute later\n const A: Poly[][] = []; // A \u2190 ExpandA(\u03C1)\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const pv = [];\n for (let j = 0; j < L; j++) pv.push(RejNTTPoly(xof.get(j, i)));\n A.push(pv);\n }\n xof.clean();\n for (let i = 0; i < L; i++) crystals.NTT.encode(s1[i]); // s\u02C61 \u2190 NTT(s1)\n for (let i = 0; i < K; i++) {\n crystals.NTT.encode(s2[i]); // s\u02C62 \u2190 NTT(s2)\n crystals.NTT.encode(t0[i]); // t\u02C60 \u2190 NTT(t0)\n }\n // This part is per msg\n const mu = externalMu\n ? msg\n : // 6: \u00B5 \u2190 H(tr||M, 512)\n // \u25B7 Compute message representative \u00B5\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n\n // Compute private random seed\n const rnd =\n random === false\n ? new Uint8Array(32)\n : random === undefined\n ? randomBytes(signRandBytes)\n : random;\n abytes(rnd, 32, 'extraEntropy');\n const rhoprime = shake256\n .create({ dkLen: CRH_BYTES })\n .update(_K)\n .update(rnd)\n .update(mu)\n .digest(); // \u03C1\u2032\u2190 H(K||rnd||\u00B5, 512)\n\n abytes(rhoprime, CRH_BYTES);\n const x256 = XOF256(rhoprime, ZCoder.bytesLen);\n // Rejection sampling loop\n main_loop: for (let kappa = 0; ; ) {\n const y = [];\n // y \u2190 ExpandMask(\u03C1 , \u03BA)\n for (let i = 0; i < L; i++, kappa++)\n y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)()));\n const z = y.map((i) => crystals.NTT.encode(i.slice()));\n const w = [];\n for (let i = 0; i < K; i++) {\n // w \u2190 NTT\u22121(A \u25E6 NTT(y))\n const wi = newPoly(N);\n for (let j = 0; j < L; j++) polyAdd(wi, MultiplyNTTs(A[i][j], z[j]));\n crystals.NTT.decode(wi);\n w.push(wi);\n }\n const w1 = w.map((j) => j.map(HighBits)); // w1 \u2190 HighBits(w)\n // Commitment hash: c\u02DC \u2208{0, 1 2\u03BB } \u2190 H(\u00B5||w1Encode(w1), 2\u03BB)\n const cTilde = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(w1))\n .digest();\n // Verifer\u2019s challenge\n // c \u2190 SampleInBall(c\u02DC1); c\u02C6 \u2190 NTT(c)\n const cHat = crystals.NTT.encode(SampleInBall(cTilde));\n // \u27E8\u27E8cs1\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C61)\n const cs1 = s1.map((i) => MultiplyNTTs(i, cHat));\n for (let i = 0; i < L; i++) {\n polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z \u2190 y + \u27E8\u27E8cs1\u27E9\u27E9\n if (polyChknorm(cs1[i], GAMMA1 - BETA)) continue main_loop; // ||z||\u221E \u2265 \u03B31 \u2212 \u03B2\n }\n // cs1 is now z (\u25B7 Signer\u2019s response)\n let cnt = 0;\n const h = [];\n for (let i = 0; i < K; i++) {\n const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // \u27E8\u27E8cs2\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 s\u02C62)\n const r0 = polySub(w[i], cs2).map(LowBits); // r0 \u2190 LowBits(w \u2212 \u27E8\u27E8cs2\u27E9\u27E9)\n if (polyChknorm(r0, GAMMA2 - BETA)) continue main_loop; // ||r0||\u221E \u2265 \u03B32 \u2212 \u03B2\n const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // \u27E8\u27E8ct0\u27E9\u27E9 \u2190 NTT\u22121(c\u02C6\u25E6 t\u02C60)\n if (polyChknorm(ct0, GAMMA2)) continue main_loop;\n polyAdd(r0, ct0);\n // \u25B7 Signer\u2019s hint\n const hint = polyMakeHint(r0, w1[i]); // h \u2190 MakeHint(\u2212\u27E8\u27E8ct0\u27E9\u27E9, w\u2212 \u27E8\u27E8cs2\u27E9\u27E9 + \u27E8\u27E8ct0\u27E9\u27E9)\n h.push(hint.v);\n cnt += hint.cnt;\n }\n if (cnt > OMEGA) continue; // the number of 1\u2019s in h is greater than \u03C9\n x256.clean();\n const res = sigCoder.encode([cTilde, cs1, h]); // \u03C3 \u2190 sigEncode(c\u02DC, z mod\u00B1q, h)\n // rho, _K, tr is subarray of secretKey, cannot clean.\n cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A);\n // `externalMu` hands ownership of `mu` to the caller,\n // so only wipe the internally derived digest form here;\n // zeroizing caller memory would break the caller's own reuse / verify path.\n if (!externalMu) cleanBytes(mu);\n return res as TRet;\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateInternalOpts(opts);\n const { externalMu = false } = opts;\n // ML-DSA.Verify(pk, M, \u03C3): Verifes a signature \u03C3 for a message M.\n const [rho, t1] = publicCoder.decode(publicKey); // (\u03C1, t1) \u2190 pkDecode(pk)\n const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr \u2190 H(BytesToBits(pk), 512)\n\n if (sig.length !== sigCoder.bytesLen) return false; // return false instead of exception\n // (c\u02DC, z, h) \u2190 sigDecode(\u03C3)\n // \u25B7 Signer\u2019s commitment hash c \u02DC, response z and hint\n const [cTilde, z, h] = sigCoder.decode(sig);\n if (h === false) return false; // if h = \u22A5 then return false\n for (let i = 0; i < L; i++) if (polyChknorm(z[i], GAMMA1 - BETA)) return false;\n const mu = externalMu\n ? msg\n : // 7: \u00B5 \u2190 H(tr||M, 512)\n shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest();\n // Compute verifer\u2019s challenge from c\u02DC\n const c = crystals.NTT.encode(SampleInBall(cTilde)); // c \u2190 SampleInBall(c\u02DC1)\n const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z)\n for (let i = 0; i < L; i++) crystals.NTT.encode(zNtt[i]);\n const wTick1 = [];\n const xof = XOF128(rho);\n for (let i = 0; i < K; i++) {\n const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d)\n const Az = newPoly(N); // // A * z\n for (let j = 0; j < L; j++) {\n const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace\n polyAdd(Az, MultiplyNTTs(aij, zNtt[j]));\n }\n // wApprox = A*z - c*t1 * (2**d)\n const wApprox = crystals.NTT.decode(polySub(Az, ct12d));\n // Reconstruction of signer\u2019s commitment\n wTick1.push(polyUseHint(wApprox, h[i])); // w \u2032 \u2190 UseHint(h, w'approx )\n }\n xof.clean();\n // c\u02DC\u2032\u2190 H (\u00B5||w1Encode(w\u20321), 2\u03BB), Hash it; this should match c\u02DC\n const c2 = shake256\n .create({ dkLen: C_TILDE_BYTES })\n .update(mu)\n .update(W1Vec.encode(wTick1))\n .digest();\n // Additional checks in FIPS-204:\n // [[ ||z||\u221E < \u03B31 \u2212 \u03B2 ]] and [[c \u02DC = c\u02DC\u2032]] and [[number of 1\u2019s in h is \u2264 \u03C9]]\n for (const t of h) {\n const sum = t.reduce((acc, i) => acc + i, 0);\n if (!(sum <= OMEGA)) return false;\n }\n for (const t of z) if (polyChknorm(t, GAMMA1 - BETA)) return false;\n return equalBytes(cTilde, c2);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-dsa' }),\n internal,\n securityLevel: securityLevel,\n keygen: internal.keygen,\n lengths: internal.lengths,\n getPublicKey: internal.getPublicKey,\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash: CHash) => {\n checkHash(hash, securityLevel);\n return Object.freeze({\n info: Object.freeze({ type: 'hashml-dsa' }),\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n const M = getMessagePrehash(hash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessagePrehash(hash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n\n/** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa44: TRet = /* @__PURE__ */ (() =>\n getDilithium({\n ...PARAMS[2],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 32,\n XOF128,\n XOF256,\n securityLevel: 128,\n }))();\n\n/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa65: TRet = /* @__PURE__ */ (() =>\n getDilithium({\n ...PARAMS[3],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 48,\n XOF128,\n XOF256,\n securityLevel: 192,\n }))();\n\n/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */\nexport const ml_dsa87: TRet = /* @__PURE__ */ (() =>\n getDilithium({\n ...PARAMS[5],\n CRH_BYTES: 64,\n TR_BYTES: 64,\n C_TILDE_BYTES: 64,\n XOF128,\n XOF256,\n securityLevel: 256,\n }))();\n", "/**\n * SLH-DSA: StateLess Hash-based Digital Signature Standard from\n * [FIPS-205](https://csrc.nist.gov/pubs/fips/205/ipd). A.k.a. Sphincs+ v3.1.\n *\n * There are many different kinds of SLH, but basically `sha2` / `shake` indicate internal hash,\n * `128` / `192` / `256` indicate security level, and `s` /`f` indicate trade-off (Small / Fast).\n *\n * Hashes function similarly to signatures. You hash a private key to get a public key,\n * which can be used to verify the private key. However, this only works once since\n * disclosing the pre-image invalidates the key.\n *\n * To address the \"one-time\" limitation, we can use a Merkle tree root hash:\n * h(h(h(0) || h(1)) || h(h(2) || h(3))))\n *\n * This allows us to have the same public key output from the hash, but disclosing one\n * path in the tree doesn't invalidate the others. By choosing a path related to the\n * message, we can \"sign\" it.\n *\n * Limitation: Only a fixed number of signatures can be made. For instance, a Merkle tree\n * with depth 8 allows 256 distinct messages. Using different trees for each node can\n * prevent forgeries, but the key will still degrade over time.\n *\n * WOTS: One-time signatures (can be forged if same key used twice).\n * FORS: Forest of Random Subsets\n *\n * Check out [official site](https://sphincs.org) & [repo](https://github.com/sphincs/sphincsplus).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport {\n bytesToHex,\n concatBytes,\n createView,\n hexToBytes,\n type CHash,\n} from '@noble/hashes/utils.js';\nimport {\n abytes,\n checkHash,\n cleanBytes,\n copyBytes,\n equalBytes,\n getMask,\n getMessage,\n getMessagePrehash,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n vecCoder,\n type Signer,\n type SigOpts,\n type TArg,\n type TRet,\n type VerOpts,\n} from './utils.ts';\n\n/**\n * * N: Security parameter (in bytes). W: Winternitz parameter\n * * H: Hypertree height. D: Hypertree layers\n * * K: FORS trees numbers. A: FORS trees height\n */\nexport type SphincsOpts = {\n /** Security parameter in bytes. */\n N: number;\n /** Winternitz parameter. */\n W: number;\n /** Total hypertree height. */\n H: number;\n /** Number of hypertree layers. */\n D: number;\n /** Number of FORS trees. */\n K: number;\n /** Height of each FORS tree. */\n A: number;\n /** Target security level in bits. */\n securityLevel: number;\n};\n\n/** Hash customization options for SLH-DSA context creation. */\nexport type SphincsHashOpts = {\n /** Whether to use the compressed-address variant from the standard. */\n isCompressed?: boolean;\n /** Factory that binds one parameter set to one per-key hash context generator. */\n getContext: GetContext;\n};\n\n/** Winternitz signature params. */\n/**\n * Built-in SLH-DSA Table 2 subset keyed by strength/profile.\n * SHA2 and SHAKE pairs share the same numeric rows here, so the hash family is chosen separately.\n * `securityLevel` stores 128/192/256-bit strengths for `checkHash(...)`,\n * not Table 2's category labels 1/3/5.\n * Other Table 2 columns such as `m`, public-key bytes, and signature bytes\n * stay derived at the export layer.\n */\nexport const PARAMS: Record = /* @__PURE__ */ (() =>\n Object.freeze({\n '128f': Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }),\n '128s': Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }),\n '192f': Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }),\n '192s': Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }),\n '256f': Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }),\n '256s': Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }),\n } as const))();\n\n// FIPS 205 `ADRS.setTypeAndClear(...)` selectors. Local names shorten the spec labels\n// (`WOTS_HASH` -> `WOTS`, `TREE` -> `HASHTREE`, `FORS_ROOTS` -> `FORSPK`), and `setAddr({ type })`\n// below only writes the type word; callers still need to preserve or overwrite the trailing words.\nconst AddressType = {\n WOTS: 0,\n WOTSPK: 1,\n HASHTREE: 2,\n FORSTREE: 3,\n FORSPK: 4,\n WOTSPRF: 5,\n FORSPRF: 6,\n} as const;\n\n/** Address byte array of size `ADDR_BYTES`. */\nexport type ADRS = Uint8Array;\n\n/** Hash and tweakable-hash callbacks bound to one SLH-DSA keypair context. */\nexport type Context = {\n /**\n * Derive a PRF output for one address.\n * @param addr - Address bytes.\n * @returns PRF output bytes.\n */\n PRFaddr: (addr: TArg) => TRet;\n /**\n * Derive the randomized message hash prefix.\n * @param skPRF - Secret PRF seed.\n * @param random - Per-signature randomness.\n * @param msg - Message bytes.\n * @returns PRF output bytes.\n */\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ) => TRet;\n /**\n * Hash one randomized message transcript.\n * @param R - Randomized message prefix.\n * @param pk - Public key bytes.\n * @param m - Message bytes.\n * @param outLen - Output length in bytes.\n * @returns Transcript hash bytes.\n */\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen: number\n ) => TRet;\n /**\n * Tweakable hash over one input block.\n * @param input - Input block.\n * @param addr - Address bytes.\n * @returns Hash output bytes.\n */\n thash1: (input: TArg, addr: TArg) => TRet;\n /**\n * Tweakable hash over multiple input blocks.\n * @param blocks - Number of input blocks.\n * @param input - Concatenated input bytes.\n * @param addr - Address bytes.\n * @returns Hash output bytes.\n */\n thashN: (blocks: number, input: TArg, addr: TArg) => TRet;\n /** Wipe any buffered hash state for the current context. */\n clean: () => void;\n};\n/** Factory that creates a context generator for one SLH-DSA parameter set. */\nexport type GetContext = (\n opts: SphincsOpts\n) => (pub_seed: TArg, sk_seed?: TArg) => TRet;\n\nfunction hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian. This is the local FIPS 205 `toInt(...)` equivalent.\nfunction bytesToNumberBE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Local in-range FIPS 205 `toByte(x, n)` equivalent; callers must keep `n < 256^len`.\nfunction numberToBytesBE(n: number | bigint, len: number): TRet {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// Local FIPS 205 Algorithm 4 `base_2^b(...)` implementation. Bits are consumed in big-endian\n// order within each input byte, and callers must provide at least `ceil(outLen * b / 8)` bytes;\n// short inputs are not rejected and would zero-extend implicitly.\nconst base2b = (outLen: number, b: number) => {\n const mask = getMask(b);\n return (bytes: TArg): TRet => {\n const baseB = new Uint32Array(outLen);\n for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) {\n while (bits < b) {\n total = (total << 8) | bytes[pos++];\n bits += 8;\n }\n bits -= b;\n baseB[out] = (total >>> bits) & mask;\n }\n return baseB as TRet;\n };\n};\n\nfunction getMaskBig(bits: number) {\n return (1n << BigInt(bits)) - 1n; // 4 -> 0b1111\n}\n\n/** Public SLH-DSA signer with prehash customization. */\nexport type SphincsSigner = Signer & {\n internal: TRet;\n securityLevel: number;\n prehash: (hash: TArg) => TRet;\n};\n\n/** One parameter/hash instantiation of the public SLH-DSA API.\n * `keygen(seed)` is a deterministic 3N-byte library hook around the internal keygen flow,\n * and `getPublicKey(secretKey)` only extracts the embedded public key\n * instead of recomputing `PK.root`.\n */\nfunction gen(opts: SphincsOpts, hashOpts_: TArg): TRet {\n const hashOpts = hashOpts_ as SphincsHashOpts;\n const { N, W, H, D, K, A, securityLevel: securityLevel } = opts;\n const getContext = hashOpts.getContext(opts);\n if (W !== 16) throw new Error('Unsupported Winternitz parameter');\n const WOTS_LOGW = 4;\n const WOTS_LEN1 = Math.floor((8 * N) / WOTS_LOGW);\n const WOTS_LEN2 = N <= 8 ? 2 : N <= 136 ? 3 : 4;\n const TREE_HEIGHT = Math.floor(H / D);\n const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2;\n\n let ADDR_BYTES = 22;\n let OFFSET_LAYER = 0;\n let OFFSET_TREE = 1;\n let OFFSET_TYPE = 9;\n let OFFSET_KP_ADDR2 = 12;\n let OFFSET_KP_ADDR1 = 13;\n let OFFSET_CHAIN_ADDR = 17;\n let OFFSET_TREE_INDEX = 18;\n let OFFSET_HASH_ADDR = 21;\n if (!hashOpts.isCompressed) {\n ADDR_BYTES = 32;\n OFFSET_LAYER += 3;\n OFFSET_TREE += 7;\n OFFSET_TYPE += 10;\n OFFSET_KP_ADDR2 += 10;\n OFFSET_KP_ADDR1 += 10;\n OFFSET_CHAIN_ADDR += 10;\n OFFSET_TREE_INDEX += 10;\n OFFSET_HASH_ADDR += 10;\n }\n\n // Mutates and returns `addr` in place. For the built-in parameter sets, the layer / chain /\n // hash / height / keypair values fit in the low byte(s), and the tree value fits in 64 bits,\n // so the untouched leading bytes in the wider FIPS 205 ADRS / ADRS_c fields stay zero.\n // `height` / `chain` and `index` / `hash` share the same spec words, so callers must use the\n // address-type-specific combinations instead of mixing both meanings in one call.\n const setAddr = (\n opts: TArg<{\n type?: (typeof AddressType)[keyof typeof AddressType];\n height?: number;\n tree?: bigint;\n index?: number;\n layer?: number;\n chain?: number;\n hash?: number;\n keypair?: number;\n subtreeAddr?: ADRS;\n keypairAddr?: ADRS;\n }>,\n addr: TArg = new Uint8Array(ADDR_BYTES)\n ) => {\n const { type, height, tree, layer, index, chain, hash, keypair } = opts;\n const { subtreeAddr, keypairAddr } = opts;\n const v = createView(addr);\n\n if (height !== undefined) addr[OFFSET_CHAIN_ADDR] = height;\n if (layer !== undefined) addr[OFFSET_LAYER] = layer;\n if (type !== undefined) addr[OFFSET_TYPE] = type;\n if (chain !== undefined) addr[OFFSET_CHAIN_ADDR] = chain;\n if (hash !== undefined) addr[OFFSET_HASH_ADDR] = hash;\n if (index !== undefined) v.setUint32(OFFSET_TREE_INDEX, index, false);\n if (subtreeAddr) addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8));\n if (tree !== undefined) v.setBigUint64(OFFSET_TREE, tree, false);\n if (keypair !== undefined) {\n addr[OFFSET_KP_ADDR1] = keypair;\n if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypair >>> 8;\n }\n if (keypairAddr) {\n addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8));\n addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1];\n if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2];\n }\n return addr;\n };\n\n const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW);\n const chainLengths = (msg: TArg) => {\n const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg);\n let csum = 0;\n for (let i = 0; i < W1.length; i++) csum += W - 1 - W1[i]; // \u25B7 Compute checksum\n // csum \u2190 csum \u226A ((8 \u2212 ((len2 \u00B7 lg(w)) mod 8)) mod 8\n csum <<= (8 - ((WOTS_LEN2 * WOTS_LOGW) % 8)) % 8;\n // Checksum to base(LOG_W)\n const W2 = chainCoder(numberToBytesBE(csum, Math.ceil((WOTS_LEN2 * WOTS_LOGW) / 8)));\n // W1 || W2 (concatBytes cannot concat TypedArrays)\n const lengths = new Uint32Array(WOTS_LEN);\n lengths.set(W1);\n lengths.set(W2, W1.length);\n return lengths;\n };\n const messageToIndices = base2b(K, A);\n\n const TREE_BITS = TREE_HEIGHT * (D - 1);\n const LEAF_BITS = TREE_HEIGHT;\n const hashMsgCoder = splitCoder(\n 'hashedMessage',\n Math.ceil((A * K) / 8),\n Math.ceil(TREE_BITS / 8),\n Math.ceil(TREE_HEIGHT / 8)\n );\n // `pkSeed` is the full public key byte string `PK.seed || PK.root`; after splitting `Hmsg`,\n // mask away any spare high bits so `idx_tree` / `idx_leaf` match the spec's final mod-2^k steps.\n const hashMessage = (\n R: TArg,\n pkSeed: TArg,\n msg: TArg,\n context: TArg\n ) => {\n const rawContext = context as Context;\n // digest \u2190 Hmsg(R, PK.seed, PK.root, M)\n const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen);\n const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest);\n const tree = bytesToNumberBE(tmpIdxTree) & getMaskBig(TREE_BITS);\n const leafIdx = Number(bytesToNumberBE(tmpIdxLeaf)) & getMask(LEAF_BITS);\n return { tree, leafIdx, md };\n };\n\n // Iterative `xmss_node` / `xmss_sign` core: mutate `treeAddr` in place, collapse completed\n // sibling pairs on `stack`, and record the sibling whenever the current subtree is the auth-path\n // neighbor of the target leaf at that height.\n const treehash = (\n height: number,\n fn: TArg<(leafIdx: number, addrOffset: number, context: Context, info: T) => Uint8Array>\n ) =>\n function treehash_i(\n context: TArg,\n leafIdx: number,\n idxOffset: number,\n treeAddr: TArg,\n info: T\n ) {\n const rawContext = context as Context;\n const leafFn = fn as (\n leafIdx: number,\n addrOffset: number,\n context: Context,\n info: T\n ) => Uint8Array;\n const maxIdx = (1 << height) - 1;\n const stack = new Uint8Array(height * N);\n const authPath = new Uint8Array(height * N);\n for (let idx = 0; ; idx++) {\n const current = new Uint8Array(2 * N);\n const cur0 = current.subarray(0, N);\n const cur1 = current.subarray(N);\n const addrOffset = idx + idxOffset;\n cur1.set(leafFn(leafIdx, addrOffset, rawContext, info));\n let h = 0;\n for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) {\n if (h === height) return { root: cur1, authPath }; // Returns from here\n if ((i ^ l) === 1) authPath.subarray(h * N).set(cur1); // authPath.push(cur1)\n if ((i & 1) === 0 && idx < maxIdx) break;\n setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr);\n cur0.set(stack.subarray(h * N).subarray(0, N));\n cur1.set(rawContext.thashN(2, current, treeAddr));\n }\n stack.subarray(h * N).set(cur1); // stack.push(cur1)\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n };\n\n type LeafInfo = {\n wotsSig: Uint8Array;\n wotsSteps: Uint32Array;\n leafAddr: ADRS;\n pkAddr: ADRS;\n };\n const wotsTreehash = treehash(\n TREE_HEIGHT,\n (leafIdx: number, addrOffset: number, context: TArg, info: TArg) => {\n const rawContext = context as Context;\n const wotsPk = new Uint8Array(WOTS_LEN * N);\n // `keygen()` passes `leafIdx = ~0 >>> 0`, so no real XMSS leaf matches and this suppresses\n // WOTS signature capture while still hashing every chain to its public-key endpoint.\n const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0;\n setAddr({ keypair: addrOffset }, info.leafAddr);\n setAddr({ keypair: addrOffset }, info.pkAddr);\n for (let i = 0; i < WOTS_LEN; i++) {\n const wotsK = info.wotsSteps[i] | wotsKmask;\n const pk = wotsPk.subarray(i * N, (i + 1) * N);\n setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr);\n pk.set(rawContext.PRFaddr(info.leafAddr));\n setAddr({ type: AddressType.WOTS }, info.leafAddr);\n for (let k = 0; ; k++) {\n if (k === wotsK) info.wotsSig.subarray(i * N).set(pk); //wotsSig.push()\n if (k === W - 1) break;\n setAddr({ hash: k }, info.leafAddr);\n pk.set(rawContext.thash1(pk, info.leafAddr));\n }\n }\n return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr);\n }\n );\n\n const forsTreehash = treehash(\n A,\n (_: number, addrOffset: number, context: TArg, forsLeafAddr: TArg) => {\n const rawContext = context as Context;\n setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr);\n const prf = rawContext.PRFaddr(forsLeafAddr);\n setAddr({ type: AddressType.FORSTREE }, forsLeafAddr);\n return rawContext.thash1(prf, forsLeafAddr);\n }\n );\n\n // Fuse `xmss_sign` with the subtree-root computation needed by `ht_sign`, so one tree walk\n // yields both the WOTS/auth-path signature and the root that the next hypertree layer signs.\n const merkleSign = (\n context: TArg,\n wotsAddr: TArg,\n treeAddr: TArg,\n leafIdx: number,\n prevRoot: TArg = new Uint8Array(N)\n ): TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }> => {\n setAddr({ type: AddressType.HASHTREE }, treeAddr);\n // State variables\n const info = {\n wotsSig: new Uint8Array(wotsCoder.bytesLen),\n wotsSteps: chainLengths(prevRoot),\n leafAddr: setAddr({ subtreeAddr: wotsAddr }),\n pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }),\n };\n const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info);\n return {\n root,\n sigWots: info.wotsSig.subarray(0, WOTS_LEN * N),\n sigAuth: authPath,\n } as TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }>;\n };\n\n type ForsLeafInfo = ADRS;\n\n const computeRoot = (\n leaf: TArg,\n leafIdx: number,\n idxOffset: number,\n authPath: TArg,\n treeHeight: number,\n context: TArg,\n addr: TArg\n ) => {\n const rawContext = context as Context;\n const buffer = new Uint8Array(2 * N);\n const b0 = buffer.subarray(0, N);\n const b1 = buffer.subarray(N, 2 * N);\n // Algorithm 11 hashes `node || AUTH[k]` for even nodes and `AUTH[k] || node` for odd ones,\n // so reuse one `2N` buffer and just swap which half receives the sibling at each level.\n // `idxOffset` carries the subtree base for the shared FORS path, so `leafIdx + idxOffset`\n // tracks the same tree-global index updates that Algorithms 11 and 17 apply to ADRS.\n // First iter\n if ((leafIdx & 1) !== 0) {\n b1.set(leaf.subarray(0, N));\n b0.set(authPath.subarray(0, N));\n } else {\n b0.set(leaf.subarray(0, N));\n b1.set(authPath.subarray(0, N));\n }\n leafIdx >>>= 1;\n idxOffset >>>= 1;\n // Rest\n for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) {\n setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr);\n const a = authPath.subarray((i + 1) * N, (i + 2) * N);\n if ((leafIdx & 1) !== 0) {\n b1.set(rawContext.thashN(2, buffer, addr));\n b0.set(a);\n } else {\n buffer.set(rawContext.thashN(2, buffer, addr));\n b1.set(a);\n }\n }\n // Root\n setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr);\n return rawContext.thashN(2, buffer, addr);\n };\n\n const seedCoder = splitCoder('seed', N, N, N);\n const publicCoder = splitCoder('publicKey', N, N);\n const secretCoder = splitCoder('secretKey', N, N, publicCoder.bytesLen);\n const forsCoder = vecCoder(splitCoder('fors', N, N * A), K);\n const wotsCoder = vecCoder(splitCoder('wots', WOTS_LEN * N, TREE_HEIGHT * N), D);\n const sigCoder = splitCoder('signature', N, forsCoder, wotsCoder); // random || fors || wots\n const internal: TRet = Object.freeze({\n info: Object.freeze({ type: 'internal-slh-dsa' }),\n lengths: Object.freeze({\n publicKey: publicCoder.bytesLen,\n secretKey: secretCoder.bytesLen,\n signature: sigCoder.bytesLen,\n seed: seedCoder.bytesLen,\n signRand: N,\n }),\n keygen(seed?: TArg) {\n if (seed !== undefined) abytes(seed, seedCoder.bytesLen, 'seed');\n seed = seed === undefined ? randomBytes(seedCoder.bytesLen) : copyBytes(seed);\n // Set SK.seed, SK.prf, and PK.seed to random n-byte\n const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed);\n const context = getContext(publicSeed, secretSeed);\n // ADRS.setLayerAddress(d \u2212 1)\n const topTreeAddr = setAddr({ layer: D - 1 });\n const wotsAddr = setAddr({ layer: D - 1 });\n //PK.root \u2190_xmss node(SK.seed, 0, h\u2032, PK.seed, ADRS)\n const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0);\n const publicKey = publicCoder.encode([publicSeed, root]);\n const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]);\n context.clean();\n cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr);\n return {\n publicKey: publicKey as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\n const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey);\n return Uint8Array.from(pk) as TRet;\n },\n sign: (msg: TArg, sk: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n let { extraEntropy: random } = opts;\n const [skSeed, skPRF, pk] = secretCoder.decode(sk); // todo: fix\n const [pkSeed, _] = publicCoder.decode(pk);\n // Set opt_rand to either PK.seed or to a random n-byte string\n if (random === false) random = copyBytes(pkSeed);\n else if (random === undefined) random = randomBytes(N);\n else random = copyBytes(random);\n abytes(random, N);\n const context = getContext(pkSeed, skSeed);\n // Generate randomizer\n const R = context.PRFmsg(skPRF, random, msg); // R \u2190 PRFmsg(SK.prf, opt_rand, M)\n let { tree, leafIdx, md } = hashMessage(R, pk, msg, context);\n // Create FORS signatures\n const wotsAddr = setAddr({\n type: AddressType.WOTS,\n tree,\n keypair: leafIdx,\n });\n const roots = [];\n const forsLeaf = setAddr({ keypairAddr: wotsAddr });\n const forsTreeAddr = setAddr({ keypairAddr: wotsAddr });\n const indices = messageToIndices(md);\n const fors: [Uint8Array, Uint8Array][] = [];\n for (let i = 0; i < indices.length; i++) {\n const idxOffset = i << A;\n setAddr(\n {\n type: AddressType.FORSPRF,\n height: 0,\n index: indices[i] + idxOffset,\n },\n forsTreeAddr\n );\n const prf = context.PRFaddr(forsTreeAddr);\n setAddr({ type: AddressType.FORSTREE }, forsTreeAddr);\n const { root, authPath } = forsTreehash(\n context,\n indices[i],\n idxOffset,\n forsTreeAddr,\n forsLeaf\n );\n roots.push(root);\n fors.push([prf, authPath]);\n }\n const forsPkAddr = setAddr({\n type: AddressType.FORSPK,\n keypairAddr: wotsAddr,\n });\n const root = context.thashN(K, concatBytes(...roots), forsPkAddr);\n // WOTS signatures\n const treeAddr = setAddr({ type: AddressType.HASHTREE });\n const wots: [Uint8Array, Uint8Array][] = [];\n for (let i = 0; i < D; i++, tree >>= BigInt(TREE_HEIGHT)) {\n setAddr({ tree, layer: i }, treeAddr);\n setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);\n const {\n sigWots,\n sigAuth,\n root: r,\n } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root);\n root.set(r);\n cleanBytes(r);\n wots.push([sigWots, sigAuth]);\n leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));\n }\n context.clean();\n const SIG = sigCoder.encode([R, fors, wots]);\n cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots);\n return SIG as TRet;\n },\n verify: (sig: TArg, msg: TArg, publicKey: TArg) => {\n const [pkSeed, pubRoot] = publicCoder.decode(publicKey);\n const [random, forsVec, wotsVec] = sigCoder.decode(sig);\n const pk = publicKey;\n if (sig.length !== sigCoder.bytesLen) return false;\n const context = getContext(pkSeed);\n let { tree, leafIdx, md } = hashMessage(random, pk, msg, context);\n const wotsAddr = setAddr({\n type: AddressType.WOTS,\n tree,\n keypair: leafIdx,\n });\n // FORS signature\n const roots = [];\n const forsTreeAddr = setAddr({\n type: AddressType.FORSTREE,\n keypairAddr: wotsAddr,\n });\n const indices = messageToIndices(md);\n for (let i = 0; i < forsVec.length; i++) {\n const [prf, authPath] = forsVec[i];\n const idxOffset = i << A;\n setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr);\n const leaf = context.thash1(prf, forsTreeAddr);\n // Compute inplace, because we need all roots in same byte array\n roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr));\n }\n const forsPkAddr = setAddr({\n type: AddressType.FORSPK,\n keypairAddr: wotsAddr,\n });\n let root = context.thashN(K, concatBytes(...roots), forsPkAddr); // root = thash()\n // WOTS signature\n const treeAddr = setAddr({ type: AddressType.HASHTREE });\n const wotsPkAddr = setAddr({ type: AddressType.WOTSPK });\n const wotsPk = new Uint8Array(WOTS_LEN * N);\n for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) {\n const [wots, sigAuth] = wotsVec[i];\n setAddr({ tree, layer: i }, treeAddr);\n setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);\n setAddr({ keypairAddr: wotsAddr }, wotsPkAddr);\n const lengths = chainLengths(root);\n for (let i = 0; i < WOTS_LEN; i++) {\n setAddr({ chain: i }, wotsAddr);\n const steps = W - 1 - lengths[i];\n const start = lengths[i];\n const out = wotsPk.subarray(i * N);\n out.set(wots.subarray(i * N, (i + 1) * N));\n for (let j = start; j < start + steps && j < W; j++) {\n setAddr({ hash: j }, wotsAddr);\n out.set(context.thash1(out, wotsAddr));\n }\n }\n const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr);\n root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr);\n leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));\n }\n return equalBytes(root, pubRoot);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'slh-dsa' }),\n internal,\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash: TArg): TRet => {\n checkHash(hash as CHash, securityLevel);\n const rawHash = hash as CHash;\n return Object.freeze({\n info: Object.freeze({ type: 'hashslh-dsa' }),\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n const M = getMessagePrehash(rawHash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n\n// FIPS 205 \u00A711.1 SHAKE instantiation: this path hashes the full uncompressed address bytes,\n// unlike the compressed 22-byte SHA2 path in \u00A711.2.\nconst genShake =\n (): TRet =>\n (opts: SphincsOpts) =>\n (pubSeed: TArg, skSeed?: TArg): TRet => {\n const { N } = opts;\n const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0 };\n // \u00A711.1 prefixes PRF/F/H/T_l with `PK.seed`, so cache that absorbed prefix once and clone it\n // for each address-bound call instead of reabsorbing the same seed every time.\n const h0 = shake256.create({}).update(pubSeed);\n const h0tmp = h0.clone();\n const thash = (blocks: number, input: TArg, addr: TArg): TRet => {\n stats.thash++;\n return h0\n ._cloneInto(h0tmp)\n .update(addr)\n .update(input.subarray(0, blocks * N))\n .xof(N) as TRet;\n };\n return {\n PRFaddr: (addr: TArg): TRet => {\n if (!skSeed) throw new Error('no sk seed');\n stats.prf++;\n const res = h0._cloneInto(h0tmp).update(addr).update(skSeed).xof(N);\n return res as TRet;\n },\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ): TRet => {\n stats.gen_message_random++;\n return shake256\n .create({})\n .update(skPRF)\n .update(random)\n .update(msg)\n .digest()\n .subarray(0, N) as TRet;\n },\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen\n ): TRet => {\n stats.hmsg++;\n return shake256.create({}).update(R.subarray(0, N)).update(pk).update(m).xof(outLen);\n },\n thash1: thash.bind(null, 1),\n thashN: thash,\n clean: () => {\n h0.destroy();\n h0tmp.destroy();\n //console.log(stats);\n },\n } as TRet;\n };\n\nconst SHAKE_SIMPLE = /* @__PURE__ */ (() => ({ getContext: genShake() }))();\n\n/**\n * SLH-DSA-SHAKE-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_128f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_128s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128s'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_192f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_192s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192s'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_256f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_256s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256s'], SHAKE_SIMPLE))();\n\ntype ShaType = typeof sha256 | typeof sha512;\n// FIPS 205 \u00A711.2 SHA2 instantiation. The `h0` / `h1` split is intentional:\n// category-1 keeps everything on SHA-256, while category-3/5 keep `PRFaddr` / `thash1`\n// on SHA-256 but switch `PRFmsg`, `Hmsg`, and multi-block `thashN` to SHA-512.\nconst genSha =\n (h0: ShaType, h1: ShaType): TRet =>\n (opts) =>\n (pub_seed: TArg, sk_seed?: TArg): TRet => {\n const { N } = opts;\n /*\n Perf debug stats, how much hashes we call?\n 128f_simple: { prf: 8305, thash: 96_922, hmsg: 1, gen_message_random: 1, mgf1: 2 }\n 256s_robust: { prf: 497_686, thash: 2_783_203, hmsg: 1, gen_message_random: 1, mgf1: 2_783_205}\n 256f_simple: { prf: 36_179, thash: 309_693, hmsg: 1, gen_message_random: 1, mgf1: 2 }\n */\n const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 };\n\n const counterB = new Uint8Array(4);\n const counterV = createView(counterB);\n // \u00A711.2 prefixes SHA2 PRF/F/H/T_l with `PK.seed || toByte(0, blockLen-N)`, so cache the\n // zero-padded seed block once for the SHA-256 lane and once for the SHA-512 lane.\n const h0ps = h0\n .create()\n .update(pub_seed)\n .update(new Uint8Array(h0.blockLen - N));\n const h1ps = h1\n .create()\n .update(pub_seed)\n .update(new Uint8Array(h1.blockLen - N));\n\n const h0tmp = h0ps.clone();\n const h1tmp = h1ps.clone();\n\n // https://www.rfc-editor.org/rfc/rfc8017.html#appendix-B.2.1\n // This local helper is intentionally stricter than generic MGF1 reuse: current SLH-DSA callers\n // only request tiny `m`-byte outputs, but the guard below rejects `length > 2^32` instead of\n // RFC 8017's broader `maskLen > 2^32 * hLen` bound.\n function mgf1(seed: TArg, length: number, hash: ShaType): TRet {\n stats.mgf1++;\n const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen);\n // NOT 2^32-1\n if (length > 2 ** 32) throw new Error('mask too long');\n for (let counter = 0, o = out; o.length; counter++) {\n counterV.setUint32(0, counter, false);\n hash.create().update(seed).update(counterB).digestInto(o);\n o = o.subarray(hash.outputLen);\n }\n cleanBytes(out.subarray(length));\n return out.subarray(0, length) as TRet;\n }\n\n const thash =\n (_: ShaType, h: typeof h0ps, hTmp: typeof h0ps) =>\n (blocks: number, input: TArg, addr: TArg): TRet => {\n stats.thash++;\n const d = h\n ._cloneInto(hTmp as any)\n .update(addr)\n .update(input.subarray(0, blocks * N))\n .digest();\n return d.subarray(0, N) as TRet;\n };\n return {\n PRFaddr: (addr: TArg): TRet => {\n if (!sk_seed) throw new Error('No sk seed');\n stats.prf++;\n const res = h0ps\n ._cloneInto(h0tmp as any)\n .update(addr)\n .update(sk_seed)\n .digest()\n .subarray(0, N);\n return res as TRet;\n },\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ): TRet => {\n stats.gen_message_random++;\n return hmac\n .create(h1, skPRF)\n .update(random)\n .update(msg)\n .digest()\n .subarray(0, N) as TRet;\n },\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen\n ): TRet => {\n stats.hmsg++;\n const seed = concatBytes(\n R.subarray(0, N),\n pk.subarray(0, N),\n h1.create().update(R.subarray(0, N)).update(pk).update(m).digest()\n );\n return mgf1(seed, outLen, h1);\n },\n thash1: thash(h0, h0ps, h0tmp).bind(null, 1),\n thashN: thash(h1, h1ps, h1tmp),\n clean: () => {\n h0ps.destroy();\n h1ps.destroy();\n h0tmp.destroy();\n h1tmp.destroy();\n //console.log(stats);\n },\n } as TRet;\n };\n\nconst SHA256_SIMPLE = /* @__PURE__ */ (() => ({\n isCompressed: true,\n getContext: genSha(sha256, sha256),\n}))();\nconst SHA512_SIMPLE = /* @__PURE__ */ (() => ({\n isCompressed: true,\n getContext: genSha(sha256, sha512),\n}))();\n\n/**\n * SLH-DSA-SHA2-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_128f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128f'], SHA256_SIMPLE))();\n/**\n * SLH-DSA-SHA2-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_128s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128s'], SHA256_SIMPLE))();\n/**\n * SLH-DSA-SHA2-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_192f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192f'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_192s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192s'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_256f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256f'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_256s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256s'], SHA512_SIMPLE))();\n", "/**\n * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from\n * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber.\n *\n * Key encapsulation is similar to DH / ECDH (think X25519), with important differences:\n * * Unlike in ECDH, we can't verify if it was \"Bob\" who've sent the shared secret\n * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG).\n * * Decapsulation never throws an error, even when shared secret was\n * encrypted by a different public key. It will just return a different shared secret.\n *\n * There are some concerns with regards to security: see\n * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and\n * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E).\n *\n * Has similar internals to ML-DSA, but their keys and params are different.\n *\n * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml),\n * [repo](https://github.com/pq-crystals/kyber),\n * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js';\nimport { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\nconst N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256\nconst Q = 3329; // 13*(2**8)+1, modulo prime\nconst F = 3303; // 3303 \u2261 128**(\u22121) mod q (FIPS-203)\nconst ROOT_OF_UNITY = 17; // \u03B6 = 17 \u2208 Zq is a primitive 256-th root of unity modulo Q. \u03B6**128 \u2261\u22121\n// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely.\n// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal,\n// and Uint16Array polys because current coefficients stay reduced modulo q.\nconst crystals = /* @__PURE__ */ genCrystals({\n N,\n Q,\n F,\n ROOT_OF_UNITY,\n newPoly: (n: number): TRet => new Uint16Array(n) as TRet,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\n};\n/** Internal params of ML-KEM versions */\n// prettier-ignore\n/** Built-in ML-KEM parameter presets keyed by the public export names\n * `ml_kem512` / `ml_kem768` / `ml_kem1024`.\n * `RBGstrength` is Table 2's required randomness-source strength in bits,\n * not a generic security label.\n */\nexport const PARAMS: Record = /* @__PURE__ */ (() =>\n Object.freeze({\n 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),\n 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),\n 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }),\n } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder => {\n // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression.\n // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key\n // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095.\n if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) };\n // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber)\n // const round = (i: number) => Math.floor(i + 0.5) | 0;\n const a = 2 ** (d - 1);\n return {\n // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).\n encode: (i: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\n};\n\n// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly.\n// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy\n// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need\n// this exact non-lossy variant instead.\nconst byteCoder = (d: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\n// NOTE: we merge encoding and compress because it is faster, also both require same d param\n// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side\n// public-key modulus checks route through this helper's decode/encode roundtrip.\n// Converts between bytes and d-bits compressed representation.\n// Kinda like convertRadix2 from @scure/base.\n// decode(encode(t)) == t, but there is loss of information on encode(decode(t))\nconst polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg, b_: TArg) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg, b_: TArg) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's \u03B3 = \u03B6^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\n\n// FIPS-203: Computes the product (in the ring Tq) of two NTT representations.\n// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form.\nfunction MultiplyNTTs(f_: TArg, g_: TArg): TRet {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) z = -z;\n const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);\n f[2 * i + 0] = c0;\n f[2 * i + 1] = c1;\n }\n return f as TRet;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg): TRet {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) throw new Error('SampleNTT: unaligned block');\n for (let i = 0; j < N && i + 3 <= b.length; i += 3) {\n const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff;\n const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff;\n if (d1 < Q) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet;\n}\n\n// Sampling from the centered binomial distribution\n// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form.\n// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes.\nconst sampleCBDBytes = (buf: TArg, eta: number): TRet => {\n const r: Poly = new Uint16Array(N);\n // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE,\n // then swap it back so callers still observe `buf` as read-only.\n const b32 = u32(buf);\n swap32IfBE(b32);\n let len = 0;\n for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {\n let b = b32[i];\n for (let j = 0; j < 32; j++) {\n bb += b & 1;\n b >>= 1;\n len += 1;\n if (len === eta) {\n t0 = bb;\n bb = 0;\n } else if (len === 2 * eta) {\n r[p++] = crystals.mod(t0 - bb);\n bb = 0;\n len = 0;\n }\n }\n }\n swap32IfBE(b32);\n if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet;\n};\n\nfunction sampleCBD(\n PRF_: TArg,\n seed: TArg,\n nonce: number,\n eta: number\n): TRet {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\n\n// K-PKE\n// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs\n// come from Algorithms 13-15, and the helper mutates decoded temporary\n// polynomials in place while leaving caller byte arrays unchanged.\nconst genKPKE = (opts_: TArg) => {\n const opts = opts_ as KyberOpts;\n const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts;\n const poly1 = polyCoder(1);\n const polyV = polyCoder(dv);\n const polyU = polyCoder(du);\n const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32);\n const secretCoder = vecCoder(polyCoder(12), K);\n const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV);\n const seedCoder = splitCoder('seed', 32, 32);\n return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg) => {\n abytes(seed, 32, 'seed');\n const seedDst = new Uint8Array(33);\n seedDst.set(seed);\n // FIPS 203 Algorithm 13 appends the parameter-set byte `k`\n // before `G(d || k)`, so expanding the same 32-byte seed\n // under a different ML-KEM parameter set yields unrelated keys.\n seedDst[32] = K;\n const seedHash = HASH512(seedDst);\n\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));\n const x = XOF(rho);\n for (let i = 0; i < K; i++) {\n const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));\n for (let j = 0; j < K; j++) {\n const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace\n polyAdd(e, MultiplyNTTs(aji, sHat[j]));\n }\n tHat.push(e); // t \u2190 A \u25E6 s + e\n }\n x.clean();\n const res = {\n publicKey: publicCoder.encode([tHat, rho]),\n secretKey: secretCoder.encode(sHat),\n };\n cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);\n return res;\n },\n encrypt: (\n publicKey: TArg,\n msg: TArg,\n seed: TArg\n ): TRet => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\n const tmp2 = new Uint16Array(N);\n const u = [];\n for (let i = 0; i < K; i++) {\n const e1 = sampleCBD(PRF, seed, K + i, ETA2);\n const tmp = new Uint16Array(N);\n for (let j = 0; j < K; j++) {\n const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access\n polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j]\n }\n polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp\n u.push(e1);\n polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i]\n cleanBytes(tmp);\n }\n x.clean();\n const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);\n polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2\n const v = poly1.decode(msg); // encode plaintext m into polynomial v\n polyAdd(v, e2); // v += e2\n cleanBytes(tHat, rHat, tmp2, e2);\n return cipherCoder.encode([u, v]) as TRet;\n },\n decrypt: (cipherText: TArg, privateKey: TArg): TRet => {\n const [u, v] = cipherCoder.decode(cipherText);\n const sk = secretCoder.decode(privateKey); // s \u2190 ByteDecode_12(dkPKE)\n const tmp = new Uint16Array(N);\n // tmp += sk[i] * u[i]\n for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet;\n },\n };\n};\n\n/**\n * Public ML-KEM wrapper over the internal K-PKE subroutine.\n * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map\n * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20.\n * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as\n * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on\n * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no\n * constant-time guarantees for that path.\n */\nfunction createKyber(opts: TArg): TRet {\n const rawOpts = opts as KyberOpts;\n const KPKE = genKPKE(rawOpts);\n const { HASH256, HASH512, KDF } = rawOpts;\n const { secretCoder: KPKESecretCoder, lengths } = KPKE;\n const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32);\n const msgLen = 32;\n const seedLen = 64;\n const kemLengths = Object.freeze({\n ...lengths,\n seed: 64,\n msg: msgLen,\n msgRand: msgLen,\n secretKey: secretCoder.bytesLen,\n });\n return Object.freeze({\n info: Object.freeze({ type: 'ml-kem' }),\n lengths: kemLengths,\n keygen: (seed: TArg = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet;\n },\n encapsulate: (publicKey: TArg, msg: TArg = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.K);\n // Copy because of inplace encoding\n const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));\n // (Modulus check.) Perform the computation ek \u2190 ByteEncode12(ByteDecode12(eke)).\n // If ek = \u0338 eke, the input is invalid. (See Section 4.2.1.)\n if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet,\n sharedSecret: kr.subarray(0, 32) as TRet,\n };\n },\n decapsulate: (cipherText: TArg, secretKey: TArg): TRet => {\n abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96\n abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv)\n // test \u2190 H(dk[384\uD835\uDC58 \u2236 768\uD835\uDC58 + 32])) .\n const k768 = secretCoder.bytesLen - 96;\n const start = k768 + 32;\n const test = HASH256(secretKey.subarray(k768 / 2, start));\n // If test \u2260 dk[768\uD835\uDC58 + 32 \u2236 768\uD835\uDC58 + 64], then input checking has failed.\n if (!equalBytes(test, secretKey.subarray(start, start + 32)))\n throw new Error('invalid secretKey: hash check failed');\n const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);\n const msg = KPKE.decrypt(cipherText, sk);\n // derive randomness, Khat, rHat = G(mHat || h)\n const kr = HASH512.create().update(msg).update(publicKeyHash).digest();\n const Khat = kr.subarray(0, 32);\n // re-encrypt using the derived randomness\n const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n // if ciphertexts do not match, \u201Cimplicitly reject\u201D\n const isValid = equalBytes(cipherText, cipherText2);\n const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();\n cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet;\n },\n });\n}\n\n// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces,\n// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here.\nfunction shakePRF(dkLen: number, key: TArg, nonce: number): TRet {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet;\n}\n\n// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call,\n// and swapping any field changes the scheme rather than tuning an internal dependency.\nconst opts = /* @__PURE__ */ (() => ({\n HASH256: sha3_256,\n HASH512: sha3_512,\n KDF: shake256,\n XOF: XOF128,\n PRF: shakePRF,\n}))();\n// Parameter-set instantiation step for the spec's \"ML-KEM-x\" names; current correctness relies\n// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects.\nconst mk = (params: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\n\n/**\n * ML-KEM-512: Table 2 row `k=2, \u03B71=3, \u03B72=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem512: TRet = /* @__PURE__ */ (() => mk(PARAMS[512]))();\n/**\n * ML-KEM-768: Table 2 row `k=3, \u03B71=2, \u03B72=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem768: TRet = /* @__PURE__ */ (() => mk(PARAMS[768]))();\n/**\n * ML-KEM-1024: Table 2 row `k=4, \u03B71=2, \u03B72=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`.\n * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement.\n */\nexport const ml_kem1024: TRet = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\n// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available\n// without re-implementing them in separate test code.\nexport const __tests: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`);\n return compress(d).encode(x) & getMask(d);\n },\n Decompress_d: (y: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet);\n },\n ByteDecode_d: (B: TArg, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg, gHat: TArg) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg) => {\n abytes(B, 34, 'B');\n const xof = XOF128(B.subarray(0, 32));\n try {\n return SampleNTT(xof.get(B[32], B[33]));\n } finally {\n xof.clean();\n }\n },\n }))();\n", "/**\n * Post-Quantum Crypto Module for Nostr\n *\n * Provides:\n * - BIP39 seed phrase generation\n * - NIP-06 key derivation (secp256k1 from seed)\n * - PQ key derivation from seed (ML-DSA-65, SLH-DSA-128s, ML-KEM-768)\n * - PQ signing (ML-DSA, SLH-DSA)\n * - NIP-QR event construction\n *\n * Uses @noble/post-quantum (pure JS, no WASM needed)\n */\n\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english.js';\nimport { HDKey } from '@scure/bip32';\nimport { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 as sha256Hash, sha512 as sha512Hash } from '@noble/hashes/sha2.js';\nimport { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\nimport { slh_dsa_sha2_128s } from '@noble/post-quantum/slh-dsa.js';\nimport { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n\n// ============================================================================\n// BIP39 SEED PHRASE\n// ============================================================================\n\n/**\n * Generate a new 12-word BIP39 mnemonic.\n * @returns {string} 12-word seed phrase\n */\nexport function generateSeedPhrase() {\n return generateMnemonic(wordlist, 128); // 128 bits = 12 words\n}\n\n/**\n * Convert a mnemonic to a 64-byte BIP39 seed (PBKDF2-HMAC-SHA512).\n * @param {string} mnemonic - 12/24 word seed phrase\n * @param {string} [passphrase=''] - optional BIP39 passphrase\n * @returns {Uint8Array} 64-byte seed\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n if (!validateMnemonic(mnemonic, wordlist)) {\n throw new Error('Invalid mnemonic');\n }\n return mnemonicToSeedSync(mnemonic, passphrase);\n}\n\n/**\n * Validate a BIP39 mnemonic.\n * @param {string} mnemonic\n * @returns {boolean}\n */\nexport function isValidMnemonic(mnemonic) {\n return validateMnemonic(mnemonic, wordlist);\n}\n\n// ============================================================================\n// NIP-06 KEY DERIVATION (secp256k1 from seed)\n// ============================================================================\n\n/**\n * Derive a secp256k1 keypair from a BIP39 seed using NIP-06.\n * Path: m/44'/1237'/0'/0/0\n *\n * @param {Uint8Array} seed - 64-byte BIP39 seed\n * @param {number} [accountIndex=0] - account index\n * @returns {{privateKey: Uint8Array, publicKey: Uint8Array}} secp256k1 keypair\n */\nexport function deriveSecp256k1FromSeed(seed, accountIndex = 0) {\n const hdKey = HDKey.fromMasterSeed(seed);\n const path = `m/44'/1237'/${accountIndex}'/0/0`;\n const child = hdKey.derive(path);\n if (!child.privateKey) {\n throw new Error('Failed to derive private key');\n }\n return {\n privateKey: child.privateKey,\n publicKey: child.publicKey\n };\n}\n\n// ============================================================================\n// PQ KEY DERIVATION FROM SEED\n// ============================================================================\n\n/**\n * Derive PQ key seeds from a BIP39 seed using HKDF.\n * Each algorithm gets a unique label so keys are independent.\n *\n * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed\n * @param {string} label - algorithm label (e.g. 'nostr-pq-ml-dsa-65')\n * @param {number} length - output length in bytes\n * @returns {Uint8Array} deterministic seed for PQ keygen\n */\nfunction derivePQSeed(bip39Seed, label, length) {\n const info = new TextEncoder().encode(label);\n return hkdf(sha512Hash, bip39Seed, undefined, info, length);\n}\n\n/**\n * Derive all PQ keypairs from a BIP39 seed.\n *\n * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed\n * @returns {{\n * mlDsa: {publicKey: Uint8Array, secretKey: Uint8Array},\n * slhDsa: {publicKey: Uint8Array, secretKey: Uint8Array},\n * mlKem: {publicKey: Uint8Array, secretKey: Uint8Array}\n * }}\n */\nexport function derivePQKeysFromSeed(bip39Seed) {\n // ML-DSA-65 needs 32-byte seed\n const mlDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-dsa-65', 32);\n const mlDsa = ml_dsa65.keygen(mlDsaSeed);\n\n // SLH-DSA-128s needs 48-byte seed (3 * 16 for sk seed, pk seed, etc.)\n const slhDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-slh-dsa-128s', 48);\n const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed);\n\n // ML-KEM-768 needs 64-byte seed\n const mlKemSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-kem-768', 64);\n const mlKem = ml_kem768.keygen(mlKemSeed);\n\n return { mlDsa, slhDsa, mlKem };\n}\n\n// ============================================================================\n// PQ SIGNING\n// ============================================================================\n\n/**\n * Sign a message with ML-DSA-65.\n * @param {Uint8Array} message\n * @param {Uint8Array} secretKey\n * @returns {Uint8Array} signature\n */\nexport function signWithMLDSA(message, secretKey) {\n return ml_dsa65.sign(message, secretKey);\n}\n\n/**\n * Verify an ML-DSA-65 signature.\n * @param {Uint8Array} signature\n * @param {Uint8Array} message\n * @param {Uint8Array} publicKey\n * @returns {boolean}\n */\nexport function verifyMLDSA(signature, message, publicKey) {\n return ml_dsa65.verify(signature, message, publicKey);\n}\n\n/**\n * Sign a message with SLH-DSA-128s.\n * @param {Uint8Array} message\n * @param {Uint8Array} secretKey\n * @returns {Uint8Array} signature\n */\nexport function signWithSLHDSA(message, secretKey) {\n return slh_dsa_sha2_128s.sign(message, secretKey);\n}\n\n/**\n * Verify an SLH-DSA-128s signature.\n * @param {Uint8Array} signature\n * @param {Uint8Array} message\n * @param {Uint8Array} publicKey\n * @returns {boolean}\n */\nexport function verifySLHDSA(signature, message, publicKey) {\n return slh_dsa_sha2_128s.verify(signature, message, publicKey);\n}\n\n// ============================================================================\n// UTILITIES\n// ============================================================================\n\n/**\n * Convert Uint8Array to base64 string.\n * @param {Uint8Array} bytes\n * @returns {string}\n */\nexport function bytesToBase64(bytes) {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Convert base64 string to Uint8Array.\n * @param {string} base64\n * @returns {Uint8Array}\n */\nexport function base64ToBytes(base64) {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Convert Uint8Array to hex string.\n * @param {Uint8Array} bytes\n * @returns {string}\n */\nexport function bytesToHex(bytes) {\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to Uint8Array.\n * @param {string} hex\n * @returns {Uint8Array}\n */\nexport function hexToBytes(hex) {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return bytes;\n}\n\n// ============================================================================\n// NIP-QR EVENT CONSTRUCTION\n// ============================================================================\n\n/**\n * Build the NIP-QR event content (the JSON that goes in the event's content field).\n *\n * The content contains:\n * - A link statement\n * - All PQ public keys\n * - PQ signatures over the statement\n * - The ML-KEM public key (no signature \u2014 KEM can't sign)\n *\n * @param {string} npub - The user's Nostr npub (hex pubkey)\n * @param {string} successorNpub - The successor's hex pubkey (for Path B), or null for Path A\n * @param {{mlDsa: *, slhDsa: *, mlKem: *}} pqKeys - PQ keypairs\n * @returns {{statement: string, content: object, statementBytes: Uint8Array}}\n */\nexport function buildNIPQRContent(npub, successorNpub, pqKeys) {\n let statement;\n if (successorNpub) {\n // Path B: migration from old nsec to seed-derived key\n statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`;\n } else {\n // Path A: direct link (identity already seed-derived)\n statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`;\n }\n\n const statementBytes = new TextEncoder().encode(statement);\n\n // Sign the statement with each PQ signature scheme\n const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey);\n const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey);\n\n const content = {\n statement,\n pq_keys: [\n {\n algorithm: 'ml-dsa-65',\n public_key: bytesToBase64(pqKeys.mlDsa.publicKey),\n signature: bytesToBase64(mlDsaSig)\n },\n {\n algorithm: 'slh-dsa-128s',\n public_key: bytesToBase64(pqKeys.slhDsa.publicKey),\n signature: bytesToBase64(slhDsaSig)\n },\n {\n algorithm: 'ml-kem-768',\n public_key: bytesToBase64(pqKeys.mlKem.publicKey),\n note: 'KEM key for encryption; ownership asserted by secp256k1 signature over this content'\n }\n ]\n };\n\n // If Path B, include successor info\n if (successorNpub) {\n content.successor_pubkey = successorNpub;\n }\n\n return { statement, content, statementBytes };\n}\n\n/**\n * Verify a NIP-QR event's PQ signatures.\n * @param {object} content - The parsed content object\n * @returns {{valid: boolean, results: Array}} verification results\n */\nexport function verifyNIPQRContent(content) {\n const results = [];\n\n for (const keyEntry of content.pq_keys) {\n if (keyEntry.algorithm === 'ml-kem-768') {\n // KEM can't sign \u2014 skip verification\n results.push({ algorithm: keyEntry.algorithm, valid: true, note: 'KEM (no signature to verify)' });\n continue;\n }\n\n const pubKey = base64ToBytes(keyEntry.public_key);\n const sig = base64ToBytes(keyEntry.signature);\n const msg = new TextEncoder().encode(content.statement);\n\n let valid = false;\n if (keyEntry.algorithm === 'ml-dsa-65') {\n valid = verifyMLDSA(sig, msg, pubKey);\n } else if (keyEntry.algorithm === 'slh-dsa-128s') {\n valid = verifySLHDSA(sig, msg, pubKey);\n }\n\n results.push({ algorithm: keyEntry.algorithm, valid });\n }\n\n return {\n valid: results.every(r => r.valid),\n results\n };\n}\n\n// ============================================================================\n// KEY SIZE INFO (for display)\n// ============================================================================\n\nexport const PQ_KEY_INFO = {\n 'ml-dsa-65': {\n name: 'ML-DSA-65 (Dilithium)',\n publicKeySize: 1952,\n signatureSize: 3309,\n fips: 'FIPS 204',\n type: 'signature'\n },\n 'slh-dsa-128s': {\n name: 'SLH-DSA-128s (SPHINCS+)',\n publicKeySize: 32,\n signatureSize: 7856,\n fips: 'FIPS 205',\n type: 'signature'\n },\n 'ml-kem-768': {\n name: 'ML-KEM-768 (Kyber)',\n publicKeySize: 1184,\n ciphertextSize: 1088,\n fips: 'FIPS 203',\n type: 'kem'\n }\n};\n"], - "mappings": ";;;;;AAwHM,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAA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es", "anumber", "isBytes", "sha256", "wordlist", "abytes", "anumber", "bytesToHex", "concatBytes", "hexToBytes", "isBytes", "randomBytes", "abytes", "concatBytes", "gen", "_0n", "_1n", "_0n", "_1n", "gcd", "F", "Q", "opts", "_1n", "F", "_0n", "F", "_1n", "anumber", "_0n", "opts", "_1n", "abytes", "isLE", "_1n", "isLE", "abytes", "_0n", "_1n", "_1n", "_0n", "Point", "_1n", "isLE", "_0n", "Fn", "F", "N", "_2n", "_0n", "_1n", "opts", "abytes", "_3n", "_4n", "Fn", "concatBytes", "Point", "hexToBytes", "endo", "bytesToHex", "Fn", "Point", "randomBytes", "abytes", "isBytes", "utils", "hmac", "_2n", "_1n", "r", "s", "hexToBytes", "concatBytes", "Q", "bytesToHex", "_0n", "opts", "_2n", "_3n", "_0n", "_1n", "_2n", "_7n", "opts", "randomBytes", "copyBytes", "opts", "validateSigOpts", "opts", "newPoly", "N", "Q", "F", "ROOT_OF_UNITY", "mod", "opts", "compress", "XOF128", "XOF256", "randomBytes", "validateSigOpts", "PARAMS", "hexToNumber", "bytesToNumberBE", "numberToBytesBE", "opts", "N", "D", "chain", "randomBytes", "copyBytes", "validateSigOpts", "root", "i", "opts", "N", "PARAMS", "N", "Q", "F", "ROOT_OF_UNITY", "crystals", "PARAMS", "polyCoder", "polyAdd", "polySub", "MultiplyNTTs", "opts", "randomBytes", "copyBytes", "PARAMS", "bytesToHex", "hexToBytes"] -} diff --git a/www/tools.html b/www/tools.html index 644bc3d..01ecee6 100644 --- a/www/tools.html +++ b/www/tools.html @@ -441,6 +441,22 @@

Decrypt
+ + +
+
HMAC-SHA256 D TAG
+
nsec/hex (privkey):
+
+
Path (e.g. Work/Projects/Secret):
+
+
Key derivation label (optional, defaults to sovereign-browser/bookmarks-folder-id-v1):
+
+
HMAC key (hex, derived from privkey + label):
+
 
+
d tag (HMAC-SHA256(hmac_key, path), 64 hex chars):
+
 
+
Compute
+